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-Z、Enter生成该字符)。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 ofsys.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 argumentcommand
.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 (由于参数是module名称,因此不能提供文件扩展名(.py
)..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 ofsys.path
.-c
选项一样,当前目录将添加到sys.path
的开头。-I
option can be used to run the script in isolated mode wheresys.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 detailsRaises an auditing event引发具有参数cpython.run_module
with argumentmodule-name
.module-name
的审核事件cpython.run_module
。See also另请参见runpy.run_module()
Equivalent functionality directly available to Python code直接可用于Python代码的等效功能
PEP 338 –
Executing 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 ofsys.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执行script中包含的Python代码,该代码必须是一个文件系统路径(绝对或相对),引用Python文件、包含__main__.py
file, or a zipfile containing a__main__.py
file.__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如果脚本名称直接指向Python文件,则包含该文件的目录将添加到sys.path
, and the file is executed as the__main__
module.sys.path
的开头,并将该文件作为__main__
模块执行。If the script name refers to a directory or zipfile, the script name is added to the start of如果脚本名称引用目录或zipfile,则脚本名称将添加到sys.path
and the__main__.py
file in that location is executed as the__main__
module.sys.path
的开头,并且该位置中的__main__.py
文件将作为__main__
模块执行。-I
option can be used to run the script in isolated mode wheresys.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 argumentfilename
.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
. -i
,sys.argv[0]
是一个空字符串(""
),当前目录将添加到sys.path
的开头。Also, tab-completion and history editing is automatically enabled, if available on your platform (see Readline configuration).此外,如果在您的平台上可用,则会自动启用选项卡完成和历史编辑(请参阅Readline配置)。
See also另请参见
Changed in version 3.4:版本3.4中更改: Automatic enabling of tab-completion and history editing.自动启用选项卡完成和历史编辑。
1.1.2. Generic 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
orbytearray
withstr
orbytes
withint
.bytes
或bytearray
与str
或bytes
与int
时发出警告。Issue an error when the option is given twice (当两次给出该选项时发出错误(-bb)。-bb
).
-
-B
¶
If given, Python won’t try to write如果给定,Python不会尝试在导入源模块时编写.pyc
files on the import of source modules..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
andPYTHONHOME
, that might be set.PYTHON*
环境变量,例如PYTHONPATH
和PYTHONHOME
。
-
-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 whensys.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这也意味着-E和-s。在隔离模式下,sys.path
contains neither the script’s directory nor the user’s site-packages directory.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删除assert语句和任何以__debug__
.__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
。
-
-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)。
-
-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 to0
, since hash randomization is enabled by default.PYTHONHASHSEED
环境变量设置为0
时有效,因为默认情况下启用了哈希随机化。On previous versions of Python, this option turns on hash randomization, so that the在Python的早期版本中,此选项启用散列随机化,因此str和bytes对象的__hash__()
values of str and bytes objects are “salted” with an unpredictable random value.__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
tosys.path
.user site-packages directory
添加到sys.path
。See also另请参见PEP 370 –
Per user site-packages directory每个用户站点包目录
-
-S
¶
Disable the import of the module禁用模块site
and the site-dependent manipulations ofsys.path
that it entails.site
的导入及其所需的sys.path
的站点相关操作。Also disable these manipulations if如果以后显式导入site
is explicitly imported later (callsite.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中更改:Thesite
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默认情况下,Python的警告机制将警告消息打印到sys.stderr
.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 warnThe 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:category字段与警告类别匹配(例如:DeprecationWarning
).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 thewarnings
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 enablefaulthandler
;-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 thetracemalloc
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 thetracemalloc.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 ispython3 -X importtime -c 'import asyncio'
. See alsoPYTHONPROFILEIMPORTTIME
.-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 alsoPYTHONPYCACHEPREFIX
.-X warn_default_encoding
issues aEncodingWarning
when the locale-specific default encoding is used for opening files. See alsoPYTHONWARNDEFAULTENCODING
.
It also allows passing arbitrary values and retrieving them through the它还允许传递任意值并通过sys._xoptions
dictionary.sys._xoptions
字典检索它们。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 logsclose()
exceptions inio.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不应使用的选项¶
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 inprefix/lib/pythonversion
andexec_prefix/lib/pythonversion
, whereprefix
andexec_prefix
are installation-dependent directories, both defaulting to/usr/local
.When
PYTHONHOME
is set to a single directory, its value replaces bothprefix
andexec_prefix
. To specify different values for these, setPYTHONHOME
toprefix:exec_prefix
.
-
PYTHONPATH
¶ Augment the default search path for module files.增加模块文件的默认搜索路径。The format is the same as the shell’sPATH
: one or more directory pathnames separated byos.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
(seePYTHONHOME
above). It is always appended toPYTHONPATH
.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搜索路径可以在Python程序中作为变量sys.path
.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 promptssys.ps1
andsys.ps2
and the hooksys.__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-inbreakpoint()
. 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 ofsys.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这个变量也可以通过Python代码修改,使用os.environ
to force inspect mode on program termination.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如果设置了该值,Python将忽略import
statements.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 theencodingname
and the:errorhandler
parts are optional and have the same meaning as instr.encode()
.For stderr, the
:errorhandler
part is ignored; the handler will always be'backslashreplace'
.Changed in version 3.4:版本3.4中更改: Theencodingname
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 unlessPYTHONLEGACYWINDOWSSTDIO
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
tosys.path
.See also
PEP 370 –
Per user site-packages directory每个用户站点包目录
-
PYTHONUSERBASE
¶ Defines the
user base directory
, which is used to compute the path of theuser site-packages directory
and Distutils installation paths forpython setup.py install --user
.See also
PEP 370 –
Per 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 warnSee 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 forSIGSEGV
,SIGFPE
,SIGABRT
,SIGBUS
andSIGILL
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 themalloc()
function of the C library for all domains (PYMEM_DOMAIN_RAW
,PYMEM_DOMAIN_MEM
,PYMEM_DOMAIN_OBJ
).pymalloc
: use the pymalloc allocator forPYMEM_DOMAIN_MEM
andPYMEM_DOMAIN_OBJ
domains and use themalloc()
function for thePYMEM_DOMAIN_RAW
domain.
Install debug hooks:
debug
: install debug hooks on top of the default memory allocators.malloc_debug
: same asmalloc
but also install debug hooks.pymalloc_debug
: same aspymalloc
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 themalloc()
allocator of the C library, or if Python is configured withoutpymalloc
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
), theLC_ALL
locale override environment variable is also not set, and the current locale reported for theLC_CTYPE
category is either the defaultC
locale, or else the explicitly ASCII-basedPOSIX
locale, then the Python CLI will attempt to configure the following locales for theLC_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 GNUreadline
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 ownlocale.getdefaultlocale()
).Configuring one of these locales (either explicitly or via the above implicit locale coercion) automatically enables the
surrogateescape
error handler forsys.stdin
andsys.stdout
(sys.stderr
continues to usebackslashreplace
as it does in any other locale). This stream handling behavior can be overridden usingPYTHONIOENCODING
as usual.For debugging purposes, setting
PYTHONCOERCECLOCALE=warn
will cause Python to emit warning messages onstderr
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 useASCII
instead ofUTF-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。