1. 命令行与环境

CPython 解析器会扫描命令行与环境用于获取各种设置信息。

其他实现的命令行方案可能有所不同。 更多相关资源请参阅 其他实现

1.1. 命令行

对 Python 发起调用时,你可以指定以下的任意选项:

python [-bBdEiOQsRStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]

当然最常见的用例就是简单地启动执行一个脚本:

python myscript.py

1.1.1. 接口选项

解释器接口类似于 UNIX shell,但提供了一些额外的发起调用方法:

  • 当调用时附带连接到某个 tty 设备的标准输入时,它会提示输入命令并执行它们,直到读入一个 EOF(文件结束字符,其产生方式是在 UNIX 中按 Ctrl-D 或在 Windows 中按 Ctrl-Z, Enter。)

  • 当调用时附带一个文件名参数或以一个文件作为标准输入时,它会从该文件读取并执行脚本程序。

  • 当调用时附带一个目录名参数时,它会从该目录读取并执行具有适当名称的脚本程序。

  • 当调用时附带 -c command 时,它会执行 command 所给出的 Python 语句。 在这里 command 可以包含以换行符分隔的多条语句。 请注意前导空格在 Python 语句中是有重要作用的!

  • 当调用时附带 -m module-name 时,会在 Python 模块路径中查找指定的模块,并将其作为脚本程序执行。

在非交互模式下,会对全部输入先解析再执行。

一个接口选项会终结解释器所读入的选项列表,后续的所有参数将被放入 sys.argv – 请注意其中首个元素即第零项 (sys.argv[0]) 会是一个表示程序源的字符串。

-c <command>

执行 command 中的 Python 代码。 command 可以为一条或以换行符分隔的多条语句,其中前导空格像在普通模块代码中一样具有作用。

如果给出此选项,sys.argv 的首个元素将为 "-c" 并且当前目录将被加入 sys.path 的开头(以允许该目录中的模块作为最高层级模块被导入)。

-m <module-name>

sys.path 中搜索指定名称的模块并将其内容作为 __main__ 模块来执行。

Since the argument is a module name, you must not give a file extension (.py). The module-name should be a valid Python module name, but the implementation may not always enforce this (e.g. it may allow you to use a name that includes a hyphen).

Package names are also permitted. When a package name is supplied instead of a normal module, the interpreter will execute <pkg>.__main__ as the main module. This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument.

注解

此选项不适用于内置模块和以 C 编写的扩展模块,因为它们并没有对应的 Python 模块文件。 但是它仍然适用于预编译的模块,即使没有可用的初始源文件。

If this option is given, the first element of sys.argv will be the full path to the module file. As with the -c option, the current directory will be added to the start of sys.path.

许多标准库模块都包含作为脚本执行时会被发起调用的代码。 其中的一个例子是 timeit 模块:

python -mtimeit -s 'setup here' 'benchmarked code here'
python -mtimeit -h # for details

参见

runpy.run_module()

Python 代码可以直接使用的等效功能

PEP 338 – 将模块作为脚本执行

2.4 新版功能.

在 2.5 版更改: The named module can now be located inside a package.

在 2.7 版更改: Supply the package name to run a __main__ submodule. sys.argv[0] is now set to "-m" while searching for the module (it was previously incorrectly set to "-c")

-

从标准输入 (sys.stdin) 读取命令。 如果标准输入为一个终端,则使用 -i

如果给出此选项,sys.argv 的首个元素将为 "-" 并且当前目录将被加入 sys.path 的开头。

参见

runpy.run_path()

Python 代码可以直接使用的等效功能

<script>

执行 script 中的 Python 代码,该参数应为一个(绝对或相对)文件系统路径,指向某个 Python 文件、包含 __main__.py 文件的目录,或包含 __main__.py 文件的 zip 文件。

如果给出此选项,sys.argv 的首个元素将为在命令行中指定的脚本名称。

如果脚本名称直接指向一个 Python 文件,则包含该文件的目录将被加入 sys.path 的开头,并且该文件会被作为 __main__ 模块来执行。

如果脚本名称指向一个目录或 zip 文件,则脚本名称将被加入 sys.path 的开头,并且该位置中的 __main__.py 文件会被作为 __main__ 模块来执行。

在 2.5 版更改: Directories and zipfiles containing a __main__.py file at the top level are now considered valid Python scripts.

If no interface option is given, -i is implied, sys.argv[0] is an empty string ("") and the current directory will be added to the start of sys.path.

1.1.2. 通用选项

-?
-h
--help

打印全部命令行选项的简短描述。

在 2.5 版更改: The --help variant.

-V
--version

Print the Python version number and exit. Example output could be:

Python 2.5.1

在 2.5 版更改: The --version variant.

1.1.3. 其他选项

-b

Issue a warning when comparing unicode with bytearray. Issue an error when the option is given twice (-bb).

Note that, unlike the corresponding Python 3.x flag, this will not emit warnings for comparisons between str and unicode. Instead, the str instance will be implicitly decoded to unicode and Unicode comparison used.

2.6 新版功能.

-B

If given, Python won’t try to write .pyc or .pyo files on the import of source modules. See also PYTHONDONTWRITEBYTECODE.

2.6 新版功能.

-d

Turn on parser debugging output (for wizards only, depending on compilation options). See also PYTHONDEBUG.

-E

忽略所有 PYTHON* 环境变量,例如可能已设置的 PYTHONPATHPYTHONHOME

2.2 新版功能.

-i

当有脚本被作为首个参数传入或使用了 -c 选项时,在执行脚本或命令之后进入交互模式,即使是在 sys.stdin 并不是一个终端的时候。 PYTHONSTARTUP 文件不会被读取。

这一选项的用处是在脚本引发异常时检查全局变量或者栈跟踪。 另请参阅 PYTHONINSPECT

-O

Turn on basic optimizations. This changes the filename extension for compiled (bytecode) files from .pyc to .pyo. See also PYTHONOPTIMIZE.

-OO

Discard docstrings in addition to the -O optimizations.

-Q <arg>

Division control. The argument must be one of the following:

old

division of int/int and long/long return an int or long (default)

new

new division semantics, i.e. division of int/int and long/long returns a float

warn

old division semantics with a warning for int/int and long/long

warnall

old division semantics with a warning for all uses of the division operator

参见

Tools/scripts/fixdiv.py

for a use of warnall

PEP 238 – Changing the division operator

-R

Turn on hash randomization, so that the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict construction, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the order in which keys are retrieved from a dict. Although Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds), enough real-world code implicitly relies on this non-guaranteed behavior that the randomization is disabled by default.

See also PYTHONHASHSEED.

2.6.8 新版功能.

-s

不要将 用户 site-packages 目录 添加到 sys.path

2.6 新版功能.

参见

PEP 370 – 分用户的 site-packages 目录

-S

Disable the import of the module site and the site-dependent manipulations of sys.path that it entails.

-t

Issue a warning when a source file mixes tabs and spaces for indentation in a way that makes it depend on the worth of a tab expressed in spaces. Issue an error when the option is given twice (-tt).

-u

Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.

Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.

另请参阅 PYTHONUNBUFFERED

-v

每当一个模块被初始化时打印一条信息,显示其加载位置(文件名或内置模块)。 当重复给出时 (-vv),为搜索模块时所检查的每个文件都打印一条消息。 此外还提供退出时有关模块清理的信息A。 另请参阅 PYTHONVERBOSE

-W arg

Warning control. Python’s warning machinery by default prints warning messages to sys.stderr. A typical warning message has the following form:

file:line: category: message

默认情况下,每个警告都对于其发生所在的每个源行都会打印一次。 此选项可控制警告打印的频繁程度。

可以给出多个 -W 选项;当某个警告能与多个选项匹配时,将执行最后一个匹配选项的操作。 无效的 -W 选项将被忽略(但是,在发出第一个警告时会打印有关无效选项的警告消息)。

Starting from Python 2.7, DeprecationWarning and its descendants are ignored by default. The -Wd option can be used to re-enable them.

Warnings can also be controlled from within a Python program using the warnings module.

The simplest form of argument is one of the following action strings (or a unique abbreviation) by themselves:

ignore

Ignore all warnings.

default

Explicitly request the default behavior (printing each warning once per source line).

all

Print a warning each time it occurs (this may generate many messages if a warning is triggered repeatedly for the same source line, such as inside a loop).

module

Print each warning only the first time it occurs in each module.

once

Print each warning only the first time it occurs in the program.

error

Raise an exception instead of printing a warning message.

The full form of argument is:

action:message:category:module:line

Here, action is as explained above but only applies to messages that match the remaining fields. Empty fields match all values; trailing empty fields may be omitted. The message field matches the start of the warning message printed; this match is case-insensitive. The category field matches the warning category. This must be a class name; the match tests whether the actual warning category of the message is a subclass of the specified warning category. The full class name must be given. The module field matches the (fully-qualified) module name; this match is case-sensitive. The line field matches the line number, where zero matches all line numbers and is thus equivalent to an omitted line number.

参见

warnings – the warnings module

PEP 230 – Warning framework

PYTHONWARNINGS

-x

跳过源中第一行,以允许使用非 Unix 形式的 #!cmd。 这适用于 DOS 专属的破解操作。

-3

Warn about Python 3.x possible incompatibilities by emitting a DeprecationWarning for features that are removed or significantly changed in Python 3 and can’t be detected using static code analysis.

2.6 新版功能.

See 将 Python 2 代码迁移到 Python 3 for more details.

1.1.4. 不应当使用的选项

-J

保留给 Jython 使用。

-U

Turns all string literals into unicodes globally. Do not be tempted to use this option as it will probably break your world. It also produces .pyc files with a different magic number than normal. Instead, you can enable unicode literals on a per-module basis by using:

from __future__ import unicode_literals

at the top of the file. See __future__ for details.

-X

Reserved for alternative implementations of Python to use for their own purposes.

1.2. 环境变量

These environment variables influence Python’s behavior, they are processed before the command-line switches other than -E. It is customary that command-line switches override environmental variables where there is a conflict.

PYTHONHOME

更改标准 Python 库的位置。 默认情况下库是在 prefix/lib/pythonversionexec_prefix/lib/pythonversion 中搜索,其中 prefixexec_prefix 是由安装位置确定的目录,默认都位于 /usr/local

PYTHONHOME 被设为单个目录时,它的值会同时替代 prefixexec_prefix。 要为两者指定不同的值,请将 PYTHONHOME 设为 prefix:exec_prefix

PYTHONPATH

增加模块文件默认搜索路径。 所用格式与终端的 PATH 相同:一个或多个由 os.pathsep 分隔的目录路径名称(例如 Unix 上用冒号而在 Windows 上用分号)。 默认忽略不存在的目录。

除了普通目录之外,单个 PYTHONPATH 条目可以引用包含纯Python模块的zip文件(源代码或编译形式)。无法从zip文件导入扩展模块。

默认索引路径依赖于安装路径,但通常都是以 prefix/lib/pythonversion 开始 (参见上文中的 PYTHONHOME)。 它 总是 会被添加到 PYTHONPATH

有一个附加目录将被插入到索引路径的 PYTHONPATH 之前,正如上文中 接口选项 所描述的。 搜索路径可以在 Python 程序内作为变量 sys.path 来进行操作。

PYTHONSTARTUP

If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts sys.ps1 and sys.ps2 in this file.

PYTHONY2K

Set this to a non-empty string to cause the time module to require dates specified as strings to include 4-digit years, otherwise 2-digit years are converted based on rules described in the time module documentation.

PYTHONOPTIMIZE

这如果被设为一个非空字符串,它就相当于指定 -O 选项。 如果设为一个整数,则它就相当于多次指定 -O

PYTHONDEBUG

此变量如果被设为一个非空字符串,它就相当于指定 -d 选项。 如果设为一个整数,则它就相当于多次指定 -d

PYTHONINSPECT

此变量如果被设为一个非空字符串,它就相当于指定 -i 选项。

此变量也可由 Python 代码使用 os.environ 来修改以在程序终结时强制检查模式。

PYTHONUNBUFFERED

此变量如果被设为一个非空字符串,它就相当于指定 -u 选项。

PYTHONVERBOSE

此变量如果被设为一个非空字符串,它就相当于指定 -v 选项。 如果设为一个整数,则它就相当于多次指定 -v

PYTHONCASEOK

If this is set, Python ignores case in import statements. This only works on Windows, OS X, OS/2, and RiscOS.

PYTHONDONTWRITEBYTECODE

If this is set, Python won’t try to write .pyc or .pyo files on the import of source modules. This is equivalent to specifying the -B option.

2.6 新版功能.

PYTHONHASHSEED

If this variable is set to random, the effect is the same as specifying the -R option: a random value is used to seed the hashes of str, bytes and datetime objects.

如果 PYTHONHASHSEED 被设为一个整数值,它将被作为固定的种子数用来生成哈希随机化所涵盖的类型的 hash() 结果。

它的目的是允许可复现的哈希运算,例如用于解释器本身的自我检测,或允许一组 python 进程共享哈希值。

The integer must be a decimal number in the range [0,4294967295]. Specifying the value 0 will lead to the same hash values as when hash randomization is disabled.

2.6.8 新版功能.

PYTHONIOENCODING

Overrides the encoding used for stdin/stdout/stderr, in the syntax encodingname:errorhandler. The :errorhandler part is optional and has the same meaning as in str.encode().

2.6 新版功能.

PYTHONNOUSERSITE

如果设置了此变量,Python 将不会把 用户 site-packages 目录 添加到 sys.path

2.6 新版功能.

参见

PEP 370 – 分用户的 site-packages 目录

PYTHONUSERBASE

定义 用户基准目录,它会在执行 python setup.py install --user 时被用来计算 用户 site-packages 目录 的路径以及 Distutils 安装路径

2.6 新版功能.

参见

PEP 370 – 分用户的 site-packages 目录

PYTHONEXECUTABLE

如果设置了此环境变量,则 sys.argv[0] 将被设为此变量的值而不是通过 C 运行时所获得的值。 仅在 Mac OS X 上起作用。

PYTHONWARNINGS

This is equivalent to the -W option. If set to a comma separated string, it is equivalent to specifying -W multiple times.

PYTHONHTTPSVERIFY

If this environment variable is set specifically to 0, then it is equivalent to implicitly calling ssl._https_verify_certificates() with enable=False when ssl is first imported.

Refer to the documentation of ssl._https_verify_certificates() for details.

2.7.12 新版功能.

1.2.1. 调试模式变量

设置这些变量只会在Python的调试版本中产生影响,也就是说,如果Python配置了 --with-pydebug 构建选项。

PYTHONTHREADDEBUG

如果设置,Python将打印线程调试信息。

在 2.6 版更改: Previously, this variable was called THREADDEBUG.

PYTHONDUMPREFS

如果设置,Python在关闭解释器,及转储对象和引用计数后仍将保持活动。

PYTHONMALLOCSTATS

If set, Python will print memory allocation statistics every time a new object arena is created, and on shutdown.

PYTHONSHOWALLOCCOUNT

If set and Python was compiled with COUNT_ALLOCS defined, Python will dump allocations counts into stderr on shutdown.

2.7.15 新版功能.

PYTHONSHOWREFCOUNT

If set, Python will print the total reference count when the program finishes or after each statement in the interactive interpreter.

2.7.15 新版功能.