python3 命令详解与参数实测(Ubuntu 22.04)
python3 逐参数实测详解:-c 内联、-m 模块运行、- 管道脚本、-O/-OO 优化、-B 禁 pyc、-E/-I/-s/-S 隔离族、-u 无缓冲、-W 警告控制、-x 跳首行、-b 字节警告、-q/-i 交互控制,REPL 会话与 sys.exit 退出码,全部命令与回显在 Ubuntu 22.04(Python 3.10.12)实测通过。
python3 命令详解与参数实测(Ubuntu 22.04)
目标:全面掌握 python3 解释器的启动参数——内联执行、模块运行、优化档位、隔离模式、警告控制、缓冲行为与 REPL 交互,全部命令与回显已在 Ubuntu 22.04(Python 3.10.12)实测通过。
一、环境信息
- 操作系统:Ubuntu 22.04.5 LTS(x86_64)
- 解释器:Python 3.10.12(
/usr/bin/python3,GCC 11.4.0 编译) - 实测工作目录:
/root/pydemo/
$ python3 --version
Python 3.10.12
$ python3 -V
Python 3.10.12
$ python3 -VV
Python 3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]
二、命令概览
2.1 语法
python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
-c、-m、脚本文件、-(stdin)四选一作为入口;其后的参数全部进入 sys.argv(-c 的 cmd 不算 argv[0],argv[0] 为 -c;脚本文件时 argv[0] 是文件路径)。
2.2 选项速查(均已实测)
| 选项 | 作用 | 实测要点 |
|---|---|---|
-c cmd | 执行内联代码 | 终止选项列表,其后全是参数 |
-m mod | 以模块方式运行 | 实测 -m json.tool、-m timeit |
- | 从 stdin 读脚本 | 管道喂代码 |
-O | 移除 assert | 断言被跳过 |
-OO | 再剥离 docstring | __doc__ 变 None |
-B | 不写 .pyc | 无 __pycache__ |
-E | 忽略 PYTHON* 环境变量 | PYTHONPATH 失效 |
-I | 隔离模式(= -E -s 且脚本目录不进 path) | 实测 path 干净 |
-s | 不加用户 site 目录 | ~/.local 不进 path |
-S | 启动时不 import site | site-packages 全不加载 |
-u | stdout/stderr 无缓冲 | 管道实时输出 |
-W ctrl | 警告控制 | -W error::、-W ignore |
-x | 跳过源文件第一行 | 坏 shebang 也能跑 |
-b | bytes/str 混用警告 | BytesWarning |
-q | REPL 不显示 banner | 仅交互模式 |
-i | 脚本跑完进入交互 | 配合 - 从 stdin |
-V/-VV | 版本信息 | -VV 含编译信息 |
三、参数逐项实测
3.1 -c 内联执行
$ python3 -c 'print("hello from -c"); import sys; print(sys.version_info[:3])'
hello from -c
(3, 10, 12)
-c 终止选项解析:python3 -c 'import sys; print(sys.argv[1:])' a b 中 a b 进入 argv。
3.2 -m 以模块运行
$ echo '{"a":1,"b":[2,3]}' | python3 -m json.tool
{
"a": 1,
"b": [
2,
3
]
}
$ python3 -m timeit '"-".join(str(n) for n in range(20))'
200000 loops, best of 5: 1.13 usec per loop
-m 在 sys.path 中查找模块并按 __main__ 执行,标准库工具链(json.tool、timeit、http.server、venv、pip)都走这条路。
3.3 - 从标准输入读脚本
$ printf 'print(sum(range(10)))' | python3 -
45
3.4 脚本执行、shebang 与 argv
$ cat > hello.py <<'EOF'
#!/usr/bin/env python3
import sys
print("script argv:", sys.argv)
print("__name__:", __name__)
EOF
$ python3 hello.py arg1 "arg two"
script argv: ['/root/pydemo/hello.py', 'arg1', 'arg two']
__name__: __main__
$ chmod +x hello.py && ./hello.py direct
script argv: ['/root/pydemo/hello.py', 'direct']
__name__: __main__
shebang 加执行位后可独立运行;作为模块导入时 __name__ 不再是 __main__。
3.5 退出码:sys.exit 与 SystemExit
$ python3 -c 'import sys; sys.exit(3)'; echo "rc=$?"
rc=3
$ python3 -c 'raise SystemExit("bye")' 2>/dev/null; echo "rc=$?"
rc=1
整数参数即退出码;字符串参数打印到 stderr 并以 1 退出;未捕获异常同样退出码 1。
3.6 交互 REPL(伪终端实测)
>>> 2**32
4294967296
>>> "py"*3
'pypypy'
>>> _
'pypypy'
>>> len(dir())
7
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=10, micro=12, releaselevel='final', serial=0)
>>> exit()
_ 保存上一个表达式结果;dir() 列出当前命名空间;exit() 退出(quit() 等价,Ctrl-D 同效)。注意:管道把代码喂给 python3 时不是 REPL(_ 未定义,实测报 NameError),REPL 只在交互终端出现。
3.7 -O 关闭断言
$ printf 'assert False, "boom"\nprint("ran with -O")\n' > optest.py
$ python3 optest.py
AssertionError: boom
$ python3 -O optest.py
ran with -O
-O 移除 assert 语句(并设置 __debug__ 为 False)。
3.8 -OO 再剥 docstring
$ printf 'def f():\n """my doc"""\n' > doc.py
$ python3 -c 'import doc; print(doc.f.__doc__)' # 在 doc.py 所在目录
my doc
$ python3 -OO -c 'import doc; print(doc.f.__doc__)'
None
3.9 -B 不写字节码
$ python3 main.py && ls __pycache__/
helper.cpython-310.pyc
$ rm -rf __pycache__
$ python3 -B main.py && ls __pycache__/ 2>/dev/null || echo "no pycache (with -B)"
no pycache (with -B)
等价环境变量 PYTHONDONTWRITEBYTECODE=x。
3.10 -E 忽略环境变量
$ PYTHONPATH=/nonexistent python3 -c 'import sys; print("/nonexistent" in sys.path)'
True
$ PYTHONPATH=/nonexistent python3 -E -c 'import sys; print([p for p in sys.path if "nonexistent" in p])'
[]
-E 使 PYTHONPATH、PYTHONHOME、PYTHONWARNINGS 等 PYTHON* 变量全部失效。
3.11 -I 隔离模式 / -s / -S
$ PYTHONPATH=/nonexistent python3 -I -c 'import sys; print([p for p in sys.path if "nonexistent" in p])'
[]
$ python3 -s -c 'import sys; print(not any(".local" in p for p in sys.path))'
True
$ python3 -S -c 'import sys; print("site-packages" not in str(sys.path))'
True
-I 隐含 -E -s,且脚本所在目录不再插入 sys.path 头部,适合运行不受信任脚本;-S 连 site 模块都不导入,启动最快但标准库路径需手工保证。
3.12 -W 警告控制
$ python3 -W error::DeprecationWarning -c 'import warnings; warnings.warn("w", DeprecationWarning)' 2>&1 | tail -1
DeprecationWarning: w
$ python3 -W ignore -c 'import warnings; warnings.warn("w", DeprecationWarning); print("no warn shown")'
no warn shown
格式 -W action::category(error/ignore/always/default/once);等价环境变量 PYTHONWARNINGS。
3.13 -x 跳过首行、-b 字节警告
$ printf '#!/nonexistent/interp\nprint("ran despite bad shebang")\n' > xf.py
$ python3 -x xf.py
ran despite bad shebang
$ python3 -b -c 'print(str(b"abc"))' 2>&1 | head -2
<string>:1: BytesWarning: str() on a bytes instance
b'abc'
-b 对 str(bytes)、bytes 与 str 比较等混用发 BytesWarning(-bb 直接报错)。
3.14 -q 与 -i
$ python3 -q # 交互启动不打印 "Python 3.10.12 ... >>>" 头部横幅
$ printf 'print("in -i session")\nexit()\n' | python3 -i -
in -i session
>>>
-i 在脚本/stdin 执行完毕后保持交互,便于事后检查变量状态。
3.15 -u 无缓冲
-u 强制 stdout/stderr 不缓冲(binary 层 unbuffered),管道下游可实时读到输出;等价环境变量 PYTHONUNBUFFERED=x。日志型脚本写入管道/文件时建议加上。
四、实战示例
4.1 JSON 校验与格式化
$ python3 -m json.tool config.json > pretty.json
$ python3 -m json.tool --compact config.json
4.2 一次性计算/转换
$ python3 -c 'print(int("ff", 16), 0b1010, round(3.14159, 2))'
255 10 3.14
4.3 启动本地静态服务
$ python3 -m http.server 8000 --directory /var/www
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
4.4 隔离运行外来脚本
$ python3 -I -B untrusted.py
不读环境变量、不写 pyc、不加载用户 site——最小副作用组合。
五、注意事项与常见问题
-c之后不再解析选项:python3 -c '...' -O的-O会被当作参数传给脚本。- 管道不是 REPL:
echo ... | python3是脚本模式,_、tab 补全、exit()快捷名都不可用;要交互行为用python3 -i -。 -O不等于"优化性能":只影响 assert 与__debug__,性能基本不变。-OO会让依赖__doc__的代码(如 argparse 帮助、doctest)失效。-S省略 site 会导致 site-packages 缺失,第三方库 import 失败,仅用于极简启动。-I下脚本目录不进 sys.path:import 同目录模块会失败,需要显式sys.path操作。- 退出码习惯:
sys.exit(0)成功、非 0 失败;未捕获异常 1;sys.exit("msg")打印 msg 且退出码 1。 -u只影响二进制缓冲层,文本层行缓冲规则仍在;交互 tty 下 stdout 本就行缓冲。- 版本对齐:
python3指向 alternatives 管理的默认解释器,python3 -VV核对版本再写脚本。 -m与直接跑文件的区别:-m按sys.path搜索包并可运行包内__main__,推荐入口一律-m(如-m pip)。
六、参考链接
- Python 官方命令行文档:https://docs.python.org/3/using/cmdline.html
- Python 3.10 发布说明:https://docs.python.org/3/whatsnew/3.10.html
man python3、python3 --help- REPL 交互教程:https://docs.python.org/3/tutorial/interpreter.html
站内相关:jq 篇