1. Command line and environment命令行和环境

The CPython interpreter scans the command line and the environment for various settings.CPython解释器扫描命令行和环境中的各种设置。

CPython implementation detail:CPython实施细节: Other implementations’ command line schemes may differ. 其他实现的命令行方案可能不同。See Alternate Implementations for further resources.有关更多资源,请参阅替代实现

1.1. Command line命令行

When invoking Python, you may specify any of these options:调用Python时,可以指定以下任何选项:

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

The most common use case is, of course, a simple invocation of a script:当然,最常见的用例是简单的脚本调用:

python myscript.py

1.1.1. Interface options接口选项

The interpreter interface resembles that of the UNIX shell, but provides some additional methods of invocation:解释器接口类似于UNIX shell,但提供了一些额外的调用方法:

  • When called with standard input connected to a tty device, it prompts for commands and executes them until an EOF (an end-of-file character, you can produce that with Ctrl-D on UNIX or Ctrl-Z, Enter on Windows) is read.当使用连接到tty设备的标准输入调用时,它会提示输入命令并执行它们,直到读取EOF(文件结束字符,您可以在UNIX上使用Ctrl-D或在Windows上使用Ctrl-ZEnter生成该字符)。

  • When called with a file name argument or with a file as standard input, it reads and executes a script from that file.当使用文件名参数或文件作为标准输入调用时,它从该文件读取并执行脚本。

  • When called with a directory name argument, it reads and executes an appropriately named script from that directory.当使用目录名参数调用时,它从该目录中读取并执行一个适当命名的脚本。

  • When called with -c command, it executes the Python statement(s) given as command. 当用-c command调用时,它执行作为命令给出的Python语句。Here command may contain multiple statements separated by newlines. Leading whitespace is significant in Python statements!此处,命令可能包含多个由换行符分隔的语句。在Python语句中,前导空格非常重要!

  • When called with -m module-name, the given module is located on the Python module path and executed as a script.当使用-m module-name调用时,给定模块位于Python模块路径上,并作为脚本执行。

In non-interactive mode, the entire input is parsed before it is executed.在非交互模式下,在执行之前对整个输入进行解析。

An interface option terminates the list of options consumed by the interpreter, all consecutive arguments will end up in sys.argv – note that the first element, subscript zero (sys.argv[0]), is a string reflecting the program’s source.接口选项终止解释器使用的选项列表,所有连续参数将在sys.argv中结束-注意,第一个元素下标零(sys.argv[0])是一个反映程序源的字符串。

-c <command>

Execute the Python code in command. 在命令中执行Python代码。command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code.命令可以是一个或多个由换行符分隔的语句,与正常模块代码中一样,具有重要的前导空格。

If this option is given, the first element of sys.argv will be "-c" and the current directory will be added to the start of sys.path (allowing modules in that directory to be imported as top level modules).如果给定此选项,sys.argv的第一个元素将是"-c",当前目录将添加到sys.path的开头(允许将该目录中的模块作为顶级模块导入)。

Raises an auditing event cpython.run_command with argument command.使用command命令引发审核事件cpython.run_command

-m <module-name>

Search sys.path for the named module and execute its contents as the __main__ module.sys.path中搜索命名模块,并将其内容作为__main__模块执行。

Since the argument is a module name, you must not give a file extension (.py). 由于参数是module名称,因此不能提供文件扩展名(.py)。The module name should be a valid absolute 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).模块名应该是有效的绝对Python模块名,但实现可能并不总是强制执行该名称(例如,它可能允许您使用包含连字符的名称)。

Package names (including namespace packages) are also permitted. 也允许使用包名(包括命名空间包)。When a package name is supplied instead of a normal module, the interpreter will execute <pkg>.__main__ as the main module. 当提供包名而不是普通模块时,解释器将执行<pkg>.__main__作为主模块。This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument.这种行为故意类似于处理作为脚本参数传递给解释器的目录和zipfiles。

Note

This option cannot be used with built-in modules and extension modules written in C, since they do not have Python module files. 此选项不能用于用C编写的内置模块和扩展模块,因为它们没有Python模块文件。However, it can still be used for precompiled modules, even if the original source file is not available.然而,即使原始源文件不可用,它仍然可以用于预编译模块。

If this option is given, the first element of sys.argv will be the full path to the module file (while the module file is being located, the first element will be set to "-m"). 如果给定此选项,sys.argv的第一个元素将是模块文件的完整路径(在定位模块文件时,第一个元素将设置为"-m")。As with the -c option, the current directory will be added to the start of sys.path.-c选项一样,当前目录将添加到sys.path的开头。

-I option can be used to run the script in isolated mode where sys.path contains neither the current directory nor the user’s site-packages directory. -I选项可用于在隔离模式下运行脚本,其中sys.path既不包含当前目录,也不包含用户的站点包目录。All PYTHON* environment variables are ignored, too.所有PYTHON*环境变量也被忽略。

Many standard library modules contain code that is invoked on their execution as a script. 许多标准库模块包含在执行时作为脚本调用的代码。An example is the timeit module:例如timeit模块:

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

Raises an auditing event cpython.run_module with argument module-name.引发具有参数module-name审核事件cpython.run_module

See also另请参见

runpy.run_module()

Equivalent functionality directly available to Python code直接可用于Python代码的等效功能

PEP 338Executing modules as scripts将模块作为脚本执行

Changed in version 3.1:版本3.1中更改: Supply the package name to run a __main__ submodule.提供包名以运行__main__子模块。

Changed in version 3.4:版本3.4中更改: namespace packages are also supported还支持命名空间包

-

Read commands from standard input (sys.stdin). 从标准输入(sys.stdin)读取命令。If standard input is a terminal, -i is implied.如果标准输入是一个端子,则表示-i

If this option is given, the first element of sys.argv will be "-" and the current directory will be added to the start of sys.path.如果给定此选项,sys.argv的第一个元素将为"-",当前目录将添加到sys.path的开头。

Raises an auditing event cpython.run_stdin with no arguments.引发审核事件cpython.run_stdin,不带参数。

<script>

Execute the Python code contained in script, which must be a filesystem path (absolute or relative) referring to either a Python file, a directory containing a __main__.py file, or a zipfile containing a __main__.py file.执行script中包含的Python代码,该代码必须是一个文件系统路径(绝对或相对),引用Python文件、包含__main__.py文件的目录或包含__main__.py文件的zipfile。

If this option is given, the first element of sys.argv will be the script name as given on the command line.如果给定此选项,sys.argv的第一个元素将是命令行中给定的脚本名称。

If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module.如果脚本名称直接指向Python文件,则包含该文件的目录将添加到sys.path的开头,并将该文件作为__main__模块执行。

If the script name refers to a directory or zipfile, the script name is added to the start of sys.path and the __main__.py file in that location is executed as the __main__ module.如果脚本名称引用目录或zipfile,则脚本名称将添加到sys.path的开头,并且该位置中的__main__.py文件将作为__main__模块执行。

-I option can be used to run the script in isolated mode where sys.path contains neither the script’s directory nor the user’s site-packages directory. -I选项可用于在隔离模式下运行脚本,其中sys.path既不包含脚本的目录,也不包含用户的站点包目录。All PYTHON* environment variables are ignored, too.所有PYTHON*环境变量也被忽略。

Raises an auditing event cpython.run_file with argument filename.使用参数filename引发审核事件cpython.run_file

See also另请参见

runpy.run_path()

Equivalent functionality directly available to Python code直接可用于Python代码的等效功能

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. 如果没有给出接口选项,则表示-isys.argv[0]是一个空字符串(""),当前目录将添加到sys.path的开头。Also, tab-completion and history editing is automatically enabled, if available on your platform (see Readline configuration).此外,如果在您的平台上可用,则会自动启用选项卡完成和历史编辑(请参阅Readline配置)。

Changed in version 3.4:版本3.4中更改: Automatic enabling of tab-completion and history editing.自动启用选项卡完成和历史编辑。

1.1.2. Generic options通用选项

-?
-h
--help

Print a short description of all command line options.打印所有命令行选项的简短说明。

-V
--version

Print the Python version number and exit. 打印Python版本号并退出。Example output could be:示例输出可以是:

Python 3.8.0b2+

When given twice, print more information about the build, like:当给出两次时,打印有关生成的更多信息,如:

Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)
[GCC 6.2.0 20161005]

New in version 3.6.版本3.6中新增。The -VV option.-VV选项。

1.1.3. Miscellaneous options其他选项

-b

Issue a warning when comparing bytes or bytearray with str or bytes with int. 当比较bytesbytearraystrbytesint时发出警告。Issue an error when the option is given twice (-bb).当两次给出该选项时发出错误(-bb)。

Changed in version 3.5:版本3.5中更改: Affects comparisons of bytes with int.影响bytesint的比较。

-B

If given, Python won’t try to write .pyc files on the import of source modules. 如果给定,Python不会尝试在导入源模块时编写.pyc文件。See also PYTHONDONTWRITEBYTECODE.另请参见PYTHONDONTWRITEBYTECODE

--check-hash-based-pycs default|always|never

Control the validation behavior of hash-based .pyc files. 控制基于哈希的.pyc文件的验证行为。See Cached bytecode invalidation. 请参阅缓存字节码无效When set to default, checked and unchecked hash-based bytecode cache files are validated according to their default semantics. 当设置为default时,基于哈希的选中和未选中字节码缓存文件将根据其默认语义进行验证。When set to always, all hash-based .pyc files, whether checked or unchecked, are validated against their corresponding source file. 当设置为always时,所有基于哈希的.pyc文件(无论是否选中)都会根据其相应的源文件进行验证。When set to never, hash-based .pyc files are not validated against their corresponding source files.当设置为never时,基于哈希的.pyc文件不会根据其相应的源文件进行验证。

The semantics of timestamp-based .pyc files are unaffected by this option.基于时间戳的.pyc文件的语义不受此选项的影响。

-d

Turn on parser debugging output (for expert only, depending on compilation options). 启用解析器调试输出(仅限专家使用,具体取决于编译选项)。See also PYTHONDEBUG.另见PYTHONDEBUG

-E

Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set.忽略所有可能设置的PYTHON*环境变量,例如PYTHONPATHPYTHONHOME

-i

When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. 当脚本作为第一个参数传递或使用-c选项时,在执行脚本或命令后进入交互模式,即使sys.stdin似乎不是终端。The PYTHONSTARTUP file is not read.未读取PYTHONSTARTUP文件。

This can be useful to inspect global variables or a stack trace when a script raises an exception. 当脚本引发异常时,这对于检查全局变量或堆栈跟踪非常有用。See also PYTHONINSPECT.另请参见PYTHONINSPECT

-I

Run Python in isolated mode. 在隔离模式下运行Python。This also implies -E and -s. In isolated mode sys.path contains neither the script’s directory nor the user’s site-packages directory. 这也意味着-E和-s。在隔离模式下,sys.path既不包含脚本的目录,也不包含用户的站点包目录。All PYTHON* environment variables are ignored, too. 所有PYTHON*环境变量也被忽略。Further restrictions may be imposed to prevent the user from injecting malicious code.可能会施加进一步的限制,以防止用户注入恶意代码。

New in version 3.4.版本3.4中新增。

-O

Remove assert statements and any code conditional on the value of __debug__. 删除assert语句和任何以__debug__的值为条件的代码。Augment the filename for compiled (bytecode) files by adding .opt-1 before the .pyc extension (see PEP 488). 通过在.pyc扩展名之前添加.opt-1来增加编译(字节码)文件的文件名(参见PEP 488)。See also PYTHONOPTIMIZE.另请参见PYTHONOPTIMIZE

Changed in version 3.5:版本3.5中更改: Modify .pyc filenames according to PEP 488.根据PEP 488修改.pyc文件名。

-OO

Do -O and also discard docstrings. 执行-O并丢弃docstring。Augment the filename for compiled (bytecode) files by adding .opt-2 before the .pyc extension (see PEP 488).通过在.pyc扩展名之前添加.opt-2来增加编译(字节码)文件的文件名(参见PEP 488)。

Changed in version 3.5:版本3.5中更改: Modify .pyc filenames according to PEP 488.根据PEP 488修改.pyc文件名。

-q

Don’t display the copyright and version messages even in interactive mode.即使在交互模式下,也不要显示版权和版本消息。

New in version 3.2.版本3.2中新增。

-R

Turn on hash randomization. 打开散列随机化。This option only has an effect if the PYTHONHASHSEED environment variable is set to 0, since hash randomization is enabled by default.此选项仅在PYTHONHASHSEED环境变量设置为0时有效,因为默认情况下启用了哈希随机化。

On previous versions of Python, this option turns on hash randomization, so that the __hash__() values of str and bytes objects are “salted” with an unpredictable random value. 在Python的早期版本中,此选项启用散列随机化,因此str和bytes对象的__hash__()值用不可预测的随机值“salt”。Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.虽然它们在单个Python进程中保持不变,但在重复调用Python之间是不可预测的。

Hash randomization 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(n2) complexity. 散列随机化旨在针对精心选择的输入造成的拒绝服务提供保护,这些输入利用dict构造的最坏情况性能O(n2)复杂性。See http://www.ocert.org/advisories/ocert-2011-003.html for details.参阅http://www.ocert.org/advisories/ocert-2011-003.html以了解详细信息。

PYTHONHASHSEED allows you to set a fixed value for the hash seed secret.允许您为哈希种子机密设置固定值。

Changed in version 3.7:版本3.7中更改: The option is no longer ignored.该选项不再被忽略。

New in version 3.2.3.版本3.2.3中新增。

-s

Don’t add the user site-packages directory to sys.path.不要将user site-packages directory添加到sys.path

See also另请参见

PEP 370Per user site-packages directory每个用户站点包目录

-S

Disable the import of the module site and the site-dependent manipulations of sys.path that it entails. 禁用模块site的导入及其所需的sys.path的站点相关操作。Also disable these manipulations if site is explicitly imported later (call site.main() if you want them to be triggered).如果以后显式导入site,请禁用这些操作(如果希望触发它们,请调用site.main()

-u

Force the stdout and stderr streams to be unbuffered. 强制取消缓冲stdout和stderr流。This option has no effect on the stdin stream.此选项对stdin流没有影响。

See also PYTHONUNBUFFERED.另请参见PYTHONUNBUFFERED

Changed in version 3.7:版本3.7中更改: The text layer of the stdout and stderr streams now is unbuffered.stdout和stderr流的文本层现在是无缓冲的。

-v

Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. 每次初始化模块时打印一条消息,显示加载模块的位置(文件名或内置模块)。When given twice (-vv), print a message for each file that is checked for when searching for a module. 当给出两次(-vv)时,为搜索模块时检查的每个文件打印一条消息。Also provides information on module cleanup at exit.还提供了有关在退出时清理模块的信息。

Changed in version 3.10:版本3.10中更改: The site module reports the site-specific paths and .pth files being processed.site模块报告正在处理的站点特定路径和.pth文件。

See also PYTHONVERBOSE.另见PYTHONVERBOSE

-W arg

Warning control. 警告控制。Python’s warning machinery by default prints warning messages to sys.stderr.默认情况下,Python的警告机制将警告消息打印到sys.stderr

The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default):最简单的设置将特定操作无条件地应用于进程发出的所有警告(即使是默认情况下忽略的警告):

-Wdefault  # Warn once per call location
-Werror # Convert to exceptions
-Walways # Warn every time
-Wmodule # Warn once per calling module
-Wonce # Warn once per Python process
-Wignore # Never warn

The action names can be abbreviated as desired and the interpreter will resolve them to the appropriate action name. 动作名称可以根据需要缩写,解释器将它们解析为适当的动作名称。For example, -Wi is the same as -Wignore.例如,-Wi-Wignore相同。

The full form of argument is:参数的完整形式是:

action:message:category:module:lineno

Empty fields match all values; trailing empty fields may be omitted. 空字段匹配所有值;尾随空字段可以省略。For example -W ignore::DeprecationWarning ignores all DeprecationWarning warnings.例如-W ignore::DeprecationWarning忽略所有DeprecationWarning警告。

The action field is as explained above but only applies to warnings that match the remaining fields.action字段如上所述,但仅适用于与其余字段匹配的警告。

The message field must match the whole warning message; this match is case-insensitive.message字段必须与整个警告消息匹配;此匹配不区分大小写。

The category field matches the warning category (ex: DeprecationWarning). category字段与警告类别匹配(例如:DeprecationWarning)。This must be a class name; the match test whether the actual warning category of the message is a subclass of the specified warning category.这必须是类名;匹配测试消息的实际警告类别是否为指定警告类别的子类。

The module field matches the (fully-qualified) module name; this match is case-sensitive.module字段与(完全限定的)模块名称匹配;此匹配区分大小写。

The lineno field matches the line number, where zero matches all line numbers and is thus equivalent to an omitted line number.lineno字段匹配行号,其中零匹配所有行号,因此相当于省略的行号。

Multiple -W options can be given; when a warning matches more than one option, the action for the last matching option is performed. 可以提供多个-W选项;当警告匹配多个选项时,将执行最后一个匹配选项的操作。Invalid -W options are ignored (though, a warning message is printed about invalid options when the first warning is issued).忽略无效-W选项(不过,在发出第一个警告时,会打印一条关于无效选项的警告消息)。

Warnings can also be controlled using the PYTHONWARNINGS environment variable and from within a Python program using the warnings module. 还可以使用PYTHONWARNINGS环境变量和使用warnings模块从Python程序中控制警告。For example, the warnings.filterwarnings() function can be used to use a regular expression on the warning message.例如,warnings.filterwarnings()函数可用于在警告消息上使用正则表达式。

See The Warnings Filter and Describing Warning Filters for more details.有关更多详细信息,请参阅警告筛选器描述警告筛选器

-x

Skip the first line of the source, allowing use of non-Unix forms of #!cmd. 跳过源代码的第一行,允许使用#!cmd的非Unix形式。This is intended for a DOS specific hack only.这仅适用于特定于DOS的黑客攻击。

-X

Reserved for various implementation-specific options. 保留用于各种特定于实现的选项。CPython currently defines the following possible values:CPython当前定义了以下可能的值:

  • -X faulthandler to enable faulthandler;-X faulthandler以启用faulthandler

  • -X showrefcount to output the total reference count and number of used memory blocks when the program finishes or after each statement in the interactive interpreter. 当程序完成时或在交互式解释器中的每个语句之后,-X showrefcount输出总引用计数和使用的内存块数。This only works on debug builds.这只适用于调试版本

  • -X tracemalloc to start tracing Python memory allocations using the tracemalloc module. By default, only the most recent frame is stored in a traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a traceback limit of NFRAME frames. See the tracemalloc.start() for more information.

  • -X importtime to show how long each import takes. It shows module name, cumulative time (including nested imports) and self time (excluding nested imports). Note that its output may be broken in multi-threaded application. Typical usage is python3 -X importtime -c 'import asyncio'. See also PYTHONPROFILEIMPORTTIME.

  • -X dev: enable Python Development Mode, introducing additional runtime checks that are too expensive to be enabled by default.

  • -X utf8 enables the Python UTF-8 Mode. -X utf8=0 explicitly disables Python UTF-8 Mode (even when it would otherwise activate automatically).

  • -X pycache_prefix=PATH enables writing .pyc files to a parallel tree rooted at the given directory instead of to the code tree. See also PYTHONPYCACHEPREFIX.

  • -X warn_default_encoding issues a EncodingWarning when the locale-specific default encoding is used for opening files. See also PYTHONWARNDEFAULTENCODING.

It also allows passing arbitrary values and retrieving them through the sys._xoptions dictionary.它还允许传递任意值并通过sys._xoptions字典检索它们。

Changed in version 3.2:版本3.2中更改: The -X option was added.添加了-X选项。

New in version 3.3.版本3.3中新增。The -X faulthandler option.-X faulthandler选项。

New in version 3.4.版本3.4中新增。The -X showrefcount and -X tracemalloc options.

New in version 3.6.版本3.6中新增。The -X showalloccount option.

New in version 3.7.版本3.7中新增。The -X importtime, -X dev and -X utf8 options.

New in version 3.8.版本3.8中新增。The -X pycache_prefix option. The -X dev option now logs close() exceptions in io.IOBase destructor.

Changed in version 3.9:版本3.9中更改: Using -X dev option, check encoding and errors arguments on string encoding and decoding operations.

The -X showalloccount option has been removed.已删除-X showalloccount选项。

New in version 3.10.版本3.10中新增。The -X warn_default_encoding option.-X warn_default_encoding选项。

Deprecated since version 3.9, removed in version 3.10: 自版本3.9起弃用,在版本3.10中删除:The -X oldparser option.-X oldparser选项。

1.1.4. Options you shouldn’t use不应使用的选项

-J

Reserved for use by Jython.保留供Jython使用。

1.2. Environment variables环境变量

These environment variables influence Python’s behavior, they are processed before the command-line switches other than -E or -I. 这些环境变量影响Python的行为,它们在命令行开关(而不是-E或-I)之前处理。It is customary that command-line switches override environmental variables where there is a conflict.通常,在存在冲突的地方,命令行开关会覆盖环境变量。

PYTHONHOME

Change the location of the standard Python libraries. 更改标准Python库的位置。By default, the libraries are searched in prefix/lib/pythonversion and exec_prefix/lib/pythonversion, where prefix and exec_prefix are installation-dependent directories, both defaulting to /usr/local.

When PYTHONHOME is set to a single directory, its value replaces both prefix and exec_prefix. To specify different values for these, set PYTHONHOME to prefix:exec_prefix.

PYTHONPATH

Augment the default search path for module files. 增加模块文件的默认搜索路径。The format is the same as the shell’s PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.

In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.

The default search path is installation dependent, but generally begins with prefix/lib/pythonversion (see PYTHONHOME above). It is always appended to PYTHONPATH.

An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options. The search path can be manipulated from within a Python program as the variable sys.path.搜索路径可以在Python程序中作为变量sys.path进行操作。

PYTHONPLATLIBDIR

If this is set to a non-empty string, it overrides the sys.platlibdir value.如果将其设置为非空字符串,则会覆盖sys.platlibdir值。

New in version 3.9.版本3.9中新增。

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. 如果这是可读文件的名称,则在交互模式下显示第一个提示之前,将执行该文件中的Python命令。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 and the hook sys.__interactivehook__ in this file.

Raises an auditing event cpython.run_startup with the filename as the argument when called on startup.在启动时调用时,以文件名作为参数引发审核事件cpython.run_startup

PYTHONOPTIMIZE

If this is set to a non-empty string it is equivalent to specifying the -O option. 如果将其设置为非空字符串,则相当于指定-O选项。If set to an integer, it is equivalent to specifying -O multiple times.如果设置为整数,则相当于多次指定-O

PYTHONBREAKPOINT

If this is set, it names a callable using dotted-path notation. The module containing the callable will be imported and then the callable will be run by the default implementation of sys.breakpointhook() which itself is called by built-in breakpoint(). If not set, or set to the empty string, it is equivalent to the value “pdb.set_trace”. Setting this to the string “0” causes the default implementation of sys.breakpointhook() to do nothing but return immediately.

New in version 3.7.版本3.7中新增。

PYTHONDEBUG

If this is set to a non-empty string it is equivalent to specifying the -d option. 如果将其设置为非空字符串,则相当于指定-d选项。If set to an integer, it is equivalent to specifying -d multiple times.如果设置为整数,则相当于多次指定-d

PYTHONINSPECT

If this is set to a non-empty string it is equivalent to specifying the -i option.如果将其设置为非空字符串,则相当于指定-i选项。

This variable can also be modified by Python code using os.environ to force inspect mode on program termination.这个变量也可以通过Python代码修改,使用os.environ在程序终止时强制检查模式。

PYTHONUNBUFFERED

If this is set to a non-empty string it is equivalent to specifying the -u option.如果将其设置为非空字符串,则相当于指定-u选项。

PYTHONVERBOSE

If this is set to a non-empty string it is equivalent to specifying the -v option. 如果将其设置为非空字符串,则相当于指定-v选项。If set to an integer, it is equivalent to specifying -v multiple times.如果设置为整数,则相当于多次指定-v

PYTHONCASEOK

If this is set, Python ignores case in import statements. 如果设置了该值,Python将忽略import语句中的大小写。This only works on Windows and macOS.这只适用于Windows和macOS。

PYTHONDONTWRITEBYTECODE

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

PYTHONPYCACHEPREFIX

If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in __pycache__ directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.

New in version 3.8.版本3.8中新增。

PYTHONHASHSEED

If this variable is not set or set to random, a random value is used to seed the hashes of str and bytes objects.

If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.

Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.其目的是允许可重复的哈希,例如用于解释器本身的自测试,或者允许python进程集群共享哈希值。

The integer must be a decimal number in the range [0,4294967295]. 整数必须是[0, 4294967295]范围内的十进制数。Specifying the value 0 will disable hash randomization.指定值0将禁用哈希随机化。

New in version 3.2.3.版本3.2.3中新增。

PYTHONIOENCODING

If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax encodingname:errorhandler. Both the encodingname and the :errorhandler parts are optional and have the same meaning as in str.encode().

For stderr, the :errorhandler part is ignored; the handler will always be 'backslashreplace'.

Changed in version 3.4:版本3.4中更改: The encodingname part is now optional.

Changed in version 3.6:版本3.6中更改: On Windows, the encoding specified by this variable is ignored for interactive console buffers unless PYTHONLEGACYWINDOWSSTDIO is also specified. Files and pipes redirected through the standard streams are not affected.

PYTHONNOUSERSITE

If this is set, Python won’t add the user site-packages directory to sys.path.

See also

PEP 370Per user site-packages directory每个用户站点包目录

PYTHONUSERBASE

Defines the user base directory, which is used to compute the path of the user site-packages directory and Distutils installation paths for python setup.py install --user.

See also

PEP 370Per user site-packages directory每个用户站点包目录

PYTHONEXECUTABLE

If this environment variable is set, sys.argv[0] will be set to its value instead of the value got through the C runtime. 如果设置了此环境变量,sys.argv[0]将被设置为其值,而不是通过C运行时获得的值。Only works on macOS.仅适用于macOS。

PYTHONWARNINGS

This is equivalent to the -W option. If set to a comma separated string, it is equivalent to specifying -W multiple times, with filters later in the list taking precedence over those earlier in the list.

The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default):最简单的设置将特定操作无条件地应用于进程发出的所有警告(即使是默认情况下忽略的警告):

PYTHONWARNINGS=default  # Warn once per call location
PYTHONWARNINGS=error # Convert to exceptions
PYTHONWARNINGS=always # Warn every time
PYTHONWARNINGS=module # Warn once per calling module
PYTHONWARNINGS=once # Warn once per Python process
PYTHONWARNINGS=ignore # Never warn

See The Warnings Filter and Describing Warning Filters for more details.有关更多详细信息,请参阅警告筛选器描述警告筛选器

PYTHONFAULTHANDLER

If this environment variable is set to a non-empty string, faulthandler.enable() is called at startup: install a handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals to dump the Python traceback. This is equivalent to -X faulthandler option.这相当于-X faulthandler选项。

New in version 3.3.版本3.3中新增。

PYTHONTRACEMALLOC

If this environment variable is set to a non-empty string, start tracing Python memory allocations using the tracemalloc module. 如果此环境变量设置为非空字符串,请使用tracemalloc模块开始跟踪Python内存分配。The value of the variable is the maximum number of frames stored in a traceback of a trace. 变量的值是记录道回溯中存储的最大帧数。For example, PYTHONTRACEMALLOC=1 stores only the most recent frame. 例如,PYTHONTRACEMALLOC=1仅存储最近的帧。See the tracemalloc.start() for more information.有关更多信息,请参阅tracemalloc.start()

New in version 3.4.版本3.4中新增。

PYTHONPROFILEIMPORTTIME

If this environment variable is set to a non-empty string, Python will show how long each import takes. 如果将此环境变量设置为非空字符串,Python将显示每次导入所需的时间。This is exactly equivalent to setting -X importtime on the command line.这完全等同于在命令行上设置-X importtime

New in version 3.7.版本3.7中新增。

PYTHONASYNCIODEBUG

If this environment variable is set to a non-empty string, enable the debug mode of the asyncio module.如果此环境变量设置为非空字符串,请启用asyncio模块的调试模式

New in version 3.4.版本3.4中新增。

PYTHONMALLOC

Set the Python memory allocators and/or install debug hooks.设置Python内存分配器和/或安装调试挂钩。

Set the family of memory allocators used by Python:设置Python使用的内存分配器系列:

  • default: use the default memory allocators.

  • malloc: use the malloc() function of the C library for all domains (PYMEM_DOMAIN_RAW, PYMEM_DOMAIN_MEM, PYMEM_DOMAIN_OBJ).

  • pymalloc: use the pymalloc allocator for PYMEM_DOMAIN_MEM and PYMEM_DOMAIN_OBJ domains and use the malloc() function for the PYMEM_DOMAIN_RAW domain.

Install debug hooks:

  • debug: install debug hooks on top of the default memory allocators.

  • malloc_debug: same as malloc but also install debug hooks.

  • pymalloc_debug: same as pymalloc but also install debug hooks.

Changed in version 3.7:版本3.7中更改: Added the "default" allocator.添加了"default"分配器。

New in version 3.6.版本3.6中新增。

PYTHONMALLOCSTATS

If set to a non-empty string, Python will print statistics of the pymalloc memory allocator every time a new pymalloc object arena is created, and on shutdown.如果设置为非空字符串,Python将在每次创建新的pymalloc对象时以及关闭时打印pymalloc内存分配器的统计信息。

This variable is ignored if the PYTHONMALLOC environment variable is used to force the malloc() allocator of the C library, or if Python is configured without pymalloc support.

Changed in version 3.6:版本3.6中更改: This variable can now also be used on Python compiled in release mode. 这个变量现在也可以在发布模式下编译的Python上使用。It now has no effect if set to an empty string.现在,如果设置为空字符串,则无效。

PYTHONLEGACYWINDOWSFSENCODING

If set to a non-empty string, the default filesystem encoding and error handler mode will revert to their pre-3.6 values of ‘mbcs’ and ‘replace’, respectively. 如果设置为非空字符串,则默认的文件系统编码和错误处理程序模式将分别恢复为3.6之前的值“mbcs”和“replace”。Otherwise, the new defaults ‘utf-8’ and ‘surrogatepass’ are used.否则,将使用新的默认值“utf-8”和“代理类”。

This may also be enabled at runtime with sys._enablelegacywindowsfsencoding().

Availability: Windows.

New in version 3.6.版本3.6中新增。See PEP 529 for more details.

PYTHONLEGACYWINDOWSSTDIO

If set to a non-empty string, does not use the new console reader and writer. 如果设置为非空字符串,则不使用新的控制台读写器。This means that Unicode characters will be encoded according to the active console code page, rather than using utf-8.这意味着Unicode字符将根据活动控制台代码页进行编码,而不是使用utf-8。

This variable is ignored if the standard streams are redirected (to files or pipes) rather than referring to console buffers.如果标准流被重定向(到文件或管道)而不是引用控制台缓冲区,则忽略此变量。

Availability: Windows.

New in version 3.6.版本3.6中新增。

PYTHONCOERCECLOCALE

If set to the value 0, causes the main Python command line application to skip coercing the legacy ASCII-based C and POSIX locales to a more capable UTF-8 based alternative.如果设置为值0,则会导致主Python命令行应用程序跳过将传统的基于ASCII的C和POSIX语言环境强制为更强大的基于UTF-8的替代方案。

If this variable is not set (or is set to a value other than 0), the LC_ALL locale override environment variable is also not set, and the current locale reported for the LC_CTYPE category is either the default C locale, or else the explicitly ASCII-based POSIX locale, then the Python CLI will attempt to configure the following locales for the LC_CTYPE category in the order listed before loading the interpreter runtime:

  • C.UTF-8

  • C.utf8

  • UTF-8

If setting one of these locale categories succeeds, then the LC_CTYPE environment variable will also be set accordingly in the current process environment before the Python runtime is initialized. This ensures that in addition to being seen by both the interpreter itself and other locale-aware components running in the same process (such as the GNU readline library), the updated setting is also seen in subprocesses (regardless of whether or not those processes are running a Python interpreter), as well as in operations that query the environment rather than the current C locale (such as Python’s own locale.getdefaultlocale()).

Configuring one of these locales (either explicitly or via the above implicit locale coercion) automatically enables the surrogateescape error handler for sys.stdin and sys.stdout (sys.stderr continues to use backslashreplace as it does in any other locale). This stream handling behavior can be overridden using PYTHONIOENCODING as usual.

For debugging purposes, setting PYTHONCOERCECLOCALE=warn will cause Python to emit warning messages on stderr if either the locale coercion activates, or else if a locale that would have triggered coercion is still active when the Python runtime is initialized.

Also note that even when locale coercion is disabled, or when it fails to find a suitable target locale, PYTHONUTF8 will still activate by default in legacy ASCII-based locales. Both features must be disabled in order to force the interpreter to use ASCII instead of UTF-8 for system interfaces.

Availability: *nix.

New in version 3.7.版本3.7中新增。See PEP 538 for more details.

PYTHONDEVMODE

If this environment variable is set to a non-empty string, enable Python Development Mode, introducing additional runtime checks that are too expensive to be enabled by default.

New in version 3.7.版本3.7中新增。

PYTHONUTF8

If set to 1, enable the Python UTF-8 Mode.

If set to 0, disable the Python UTF-8 Mode.

Setting any other non-empty string causes an error during interpreter initialisation.设置任何其他非空字符串会导致解释器初始化期间出错。

New in version 3.7.版本3.7中新增。

PYTHONWARNDEFAULTENCODING

If this environment variable is set to a non-empty string, issue a EncodingWarning when the locale-specific default encoding is used.

See Opt-in EncodingWarning for details.有关详细信息,请参阅Opt-in EncodingWarning

New in version 3.10.版本3.10中新增。

1.2.1. Debug-mode variables调试模式变量

PYTHONTHREADDEBUG

If set, Python will print threading debug info into stdout.如果设置,Python将把线程调试信息打印到标准输出中。

Need a debug build of Python.需要Python的调试版本

Deprecated since version 3.10, will be removed in version 3.12.自版本3.10以来已弃用,将在版本3.12中删除。

PYTHONDUMPREFS

If set, Python will dump objects and reference counts still alive after shutting down the interpreter.如果设置,Python将在关闭解释器后转储仍处于活动状态的对象和引用计数。

Need Python configured with the --with-trace-refs build option.需要使用--with-trace-refs选项配置Python。