ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](unix.xhtml "2. 在Unix平台中使用Python") | - [上一页](index.xhtml "安装和使用 Python") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [安装和使用 Python](index.xhtml) » - $('.inline-search').show(0); | # 1. 命令行与环境 CPython 解析器会扫描命令行与环境用于获取各种设置信息。 **CPython implementation detail:** 其他实现的命令行方案可能有所不同。 更多相关资源请参阅 [其他实现](../reference/introduction.xhtml#implementations)。 ## 1.1. 命令行 对 Python 发起调用时,你可以指定以下的任意选项: ``` python [-bBdEhiIOqsSuvVWx?] [-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`](../library/sys.xhtml#sys.argv "sys.argv") -- 请注意其中首个元素即第零项 (`sys.argv[0]`) 会是一个表示程序源的字符串。 `-c`` <command>`执行 *command* 中的 Python 代码。 *command* 可以为一条或以换行符分隔的多条语句,其中前导空格像在普通模块代码中一样具有作用。 如果给出此选项,[`sys.argv`](../library/sys.xhtml#sys.argv "sys.argv") 的首个元素将为 `"-c"` 并且当前目录将被加入 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 的开头(以允许该目录中的模块作为最高层级模块被导入)。 `-m`` <module-name>`在 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 中搜索指定名称的模块并将其内容作为 [`__main__`](../library/__main__.xhtml#module-__main__ "__main__: The environment where the top-level script is run.") 模块来执行。 由于该参数为 *module* 名称,你不应给出文件扩展名 (`.py`)。 模块名称应为绝对有效的 Python 模块名称,但具体实现可能并不总是强制要求这一点(例如它可能允许你使用包含连字符的名称)。 包名称(包括命名空间包)也允许使用。 当所提供的是包名称而非普通模块名称时,解释器将把 `<pkg>.__main__` 作为主模块来执行。 此行为特意被设计为与作为脚本参数传递给解释器的目录和 zip 文件的处理方式类似。 注解 此选项不适用于内置模块和以 C 编写的扩展模块,因为它们并没有对应的 Python 模块文件。 但是它仍然适用于预编译的模块,即使没有可用的初始源文件。 如果给出此选项,[`sys.argv`](../library/sys.xhtml#sys.argv "sys.argv") 的首个元素将为模块文件的完整路径 (在定位模块文件期间,首个元素将设为 `"-m"`)。 与 [`-c`](#cmdoption-c) 选项一样,当前目录将被加入 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 的开头。 许多标准库模块都包含作为脚本执行时会被发起调用的代码。 其中的一个例子是 [`timeit`](../library/timeit.xhtml#module-timeit "timeit: Measure the execution time of small code snippets.") 模块: ``` python -mtimeit -s 'setup here' 'benchmarked code here' python -mtimeit -h # for details ``` 参见 [`runpy.run_module()`](../library/runpy.xhtml#runpy.run_module "runpy.run_module")Python 代码可以直接使用的等效功能 [**PEP 338**](https://www.python.org/dev/peps/pep-0338) \[https://www.python.org/dev/peps/pep-0338\] -- 将模块作为脚本执行 在 3.1 版更改: 提供包名称来运行 `__main__` 子模块。 在 3.4 版更改: 同样支持命名空间包 `-`从标准输入 ([`sys.stdin`](../library/sys.xhtml#sys.stdin "sys.stdin")) 读取命令。 如果标准输入为一个终端,则使用 [`-i`](#cmdoption-i)。 如果给出此选项,[`sys.argv`](../library/sys.xhtml#sys.argv "sys.argv") 的首个元素将为 `"-"` 并且当前目录将被加入 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 的开头。 `<script>`执行 *script* 中的 Python 代码,该参数应为一个(绝对或相对)文件系统路径,指向某个 Python 文件、包含 `__main__.py` 文件的目录,或包含 `__main__.py` 文件的 zip 文件。 如果给出此选项,[`sys.argv`](../library/sys.xhtml#sys.argv "sys.argv") 的首个元素将为在命令行中指定的脚本名称。 如果脚本名称直接指向一个 Python 文件,则包含该文件的目录将被加入 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 的开头,并且该文件会被作为 [`__main__`](../library/__main__.xhtml#module-__main__ "__main__: The environment where the top-level script is run.") 模块来执行。 如果脚本名称指向一个目录或 zip 文件,则脚本名称将被加入 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 的开头,并且该位置中的 `__main__.py` 文件会被作为 [`__main__`](../library/__main__.xhtml#module-__main__ "__main__: The environment where the top-level script is run.") 模块来执行。 参见 [`runpy.run_path()`](../library/runpy.xhtml#runpy.run_path "runpy.run_path")Python 代码可以直接使用的等效功能 如果没有给出接口选项,则使用 [`-i`](#cmdoption-i),`sys.argv[0]` 将为空字符串 (`""`),并且当前目录会被加入 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 的开头。 此外,tab 补全和历史编辑会自动启用,如果你的系统平台支持此功能的话 (参见 [Readline configuration](../library/site.xhtml#rlcompleter-config))。 参见 [调用解释器](../tutorial/interpreter.xhtml#tut-invoking) 在 3.4 版更改: 自动启用 tab 补全和历史编辑。 ### 1.1.2. 通用选项 `-?````-h````--help```打印全部命令行选项的简短描述。 `-V````--version```打印 Python 版本号并退出。 示例输出信息如下: ``` Python 3.7.0b2+ ``` 如果重复给出,则打印有关构建的更多信息,例如: ``` Python 3.7.0b2+ (3.7:0c076caaa8, Sep 22 2018, 12:04:24) [GCC 6.2.0 20161005] ``` 3\.6 新版功能: `-VV` 选项。 ### 1.1.3. 其他选项 `-b```在将 [`bytes`](../library/stdtypes.xhtml#bytes "bytes") 或 [`bytearray`](../library/stdtypes.xhtml#bytearray "bytearray") 与 [`str`](../library/stdtypes.xhtml#str "str") 或是将 [`bytes`](../library/stdtypes.xhtml#bytes "bytes") 与 [`int`](../library/functions.xhtml#int "int") 比较时发出警告。 如果重复给出该选项 (`-bb`) 则会引发错误。 在 3.5 版更改: 影响 [`bytes`](../library/stdtypes.xhtml#bytes "bytes") 与 [`int`](../library/functions.xhtml#int "int") 的比较。 `-B```如果给出此选项,Python 将不会试图在导入源模块时写入 `.pyc` 文件。 另请参阅 [`PYTHONDONTWRITEBYTECODE`](#envvar-PYTHONDONTWRITEBYTECODE)。 `--check-hash-based-pycs`` default|always|never`控制基于哈希值的 `.pyc` 文件的验证行为。 参见 [已缓存字节码的失效](../reference/import.xhtml#pyc-invalidation)。 当设为 `default` 时,已选定和未选定的基于哈希值的字节码缓存文件将根据其默认语义进行验证。 当设为 `always` 时,所有基于哈希值的 `.pyc` 文件,不论是已选定还是未选定的都将根据其对应的源文件进行验证。 当设为 `never` 时,基于哈希值的 `.pyc` 文件将不会根据其对应的源文件进行验证。 基于时间戳的 `.pyc` 文件的语义不会受此选项影响。 `-d```开启解析器调试输出(限专家使用,依赖于编译选项)。 另请参阅 [`PYTHONDEBUG`](#envvar-PYTHONDEBUG)。 `-E```忽略所有 `PYTHON*` 环境变量,例如可能已设置的 [`PYTHONPATH`](#envvar-PYTHONPATH) 和 [`PYTHONHOME`](#envvar-PYTHONHOME)。 `-i```当有脚本被作为首个参数传入或使用了 [`-c`](#cmdoption-c) 选项时,在执行脚本或命令之后进入交互模式,即使是在 [`sys.stdin`](../library/sys.xhtml#sys.stdin "sys.stdin") 并不是一个终端的时候。 [`PYTHONSTARTUP`](#envvar-PYTHONSTARTUP) 文件不会被读取。 这一选项的用处是在脚本引发异常时检查全局变量或者栈跟踪。 另请参阅 [`PYTHONINSPECT`](#envvar-PYTHONINSPECT)。 `-I```在隔离模式下运行 Python。 这将同时应用 -E 和 -s。 在隔离模式下 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 既不包含脚本所在目录也不包含用户的 site-packages 目录。 所有 `PYTHON*` 环境变量也会被忽略。 还可以施加更进一步的限制以防止用户注入恶意代码。 3\.4 新版功能. `-O```移除 assert 语句以及任何以 [`__debug__`](../library/constants.xhtml#__debug__ "__debug__") 的值作为条件的代码。 通过在 `.pyc` 扩展名之前添加 `.opt-1` 来扩充已编译文件 ([bytecode](../glossary.xhtml#term-bytecode)) 的文件名 (参见 [**PEP 488**](https://www.python.org/dev/peps/pep-0488) \[https://www.python.org/dev/peps/pep-0488\])。 另请参阅 [`PYTHONOPTIMIZE`](#envvar-PYTHONOPTIMIZE)。 在 3.5 版更改: 依据 [**PEP 488**](https://www.python.org/dev/peps/pep-0488) \[https://www.python.org/dev/peps/pep-0488\] 修改 `.pyc` 文件名。 `-OO```在启用 [`-O`](#cmdoption-o) 的同时丢弃文档字符串。 通过在 `.pyc` 扩展名之前添加 `.opt-2` 来扩展已编译文件 ([bytecode](../glossary.xhtml#term-bytecode)) 的文件名 (参见 [**PEP 488**](https://www.python.org/dev/peps/pep-0488) \[https://www.python.org/dev/peps/pep-0488\])。 在 3.5 版更改: 依据 [**PEP 488**](https://www.python.org/dev/peps/pep-0488) \[https://www.python.org/dev/peps/pep-0488\] 修改 `.pyc` 文件名。 `-q```即使在交互模式下也不显示版权和版本信息。 3\.2 新版功能. `-R```开启哈希随机化。 此选项权 [`PYTHONHASHSEED`](#envvar-PYTHONHASHSEED) 环境变量设置为 `0` 时起作用,因为哈希随机化是默认启用的。 在先前的 Python 版本中,此选项会开启哈希随机化,这样 str, bytes 和 datetime 的 [`__hash__()`](../reference/datamodel.xhtml#object.__hash__ "object.__hash__") 值将会使用一个不可预测的随机值来“加盐”。 虽然它们在单个 Python 进程中会保持不变,但在重复发起的 Python 调用之间则是不可预测的。 哈希随机化旨在针对由精心选择的输入引起的拒绝服务攻击提供防护,这种输入利用了构造 dict 在最坏情况下的性能即 O(n^2) 复杂度。 详情请参阅 <http://www.ocert.org/advisories/ocert-2011-003.html>。 [`PYTHONHASHSEED`](#envvar-PYTHONHASHSEED) 允许你为哈希种子密码设置一个固定值。 在 3.7 版更改: 此选项不会再被忽略。 3\.2.3 新版功能. `-s```不要将 [`用户 site-packages 目录`](../library/site.xhtml#site.USER_SITE "site.USER_SITE") 添加到 [`sys.path`](../library/sys.xhtml#sys.path "sys.path")。 参见 [**PEP 370**](https://www.python.org/dev/peps/pep-0370) \[https://www.python.org/dev/peps/pep-0370\] -- 分用户的 site-packages 目录 `-S```禁用 [`site`](../library/site.xhtml#module-site "site: Module responsible for site-specific configuration.") 的导入及其所附带的基于站点对 [`sys.path`](../library/sys.xhtml#sys.path "sys.path") 的操作。 如果 [`site`](../library/site.xhtml#module-site "site: Module responsible for site-specific configuration.") 会在稍后被显式地导入也会禁用这些操作 (如果你希望触发它们则应调用 [`site.main()`](../library/site.xhtml#site.main "site.main"))。 `-u```强制 stdout 和 stderr 流不使用缓冲。 此选项对 stdin 流无影响。 另请参阅 [`PYTHONUNBUFFERED`](#envvar-PYTHONUNBUFFERED)。 在 3.7 版更改: stdout 和 stderr 流在文本层现在不使用缓冲。 `-v```每当一个模块被初始化时打印一条信息,显示其加载位置(文件名或内置模块)。 当重复给出时 (`-vv`),为搜索模块时所检查的每个文件都打印一条消息。 此外还提供退出时有关模块清理的信息A。 另请参阅 [`PYTHONVERBOSE`](#envvar-PYTHONVERBOSE)。 `-W`` arg`警告控制。 Python 的警告机制在默认情况下会向 [`sys.stderr`](../library/sys.xhtml#sys.stderr "sys.stderr") 打印警告消息。 典型的警告消息具有如下形式: ``` file:line: category: message ``` 默认情况下,每个警告都对于其发生所在的每个源行都会打印一次。 此选项可控制警告打印的频繁程度。 可以给出多个 [`-W`](#cmdoption-w) 选项;当某个警告能与多个选项匹配时,将执行最后一个匹配选项的操作。 无效的 [`-W`](#cmdoption-w) 选项将被忽略(但是,在发出第一个警告时会打印有关无效选项的警告消息)。 警告也可以使用 [`PYTHONWARNINGS`](#envvar-PYTHONWARNINGS) 环境变量以及使用 [`warnings`](../library/warnings.xhtml#module-warnings "warnings: Issue warning messages and control their disposition.") 模块在 Python 程序内部进行控制。 最简单的设置是将某个特定操作无条件地应用于进程所发出所有警告 (即使是在默认情况下会忽略的那些警告): ``` -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 ``` 操作名称可以根据需要进行缩写 (例如 `-Wi`, `-Wd`, `-Wa`, `-We`),解释器将会把它们解析为适当的操作名称。 请参阅 [The Warnings Filter](../library/warnings.xhtml#warning-filter) 和 [Describing Warning Filters](../library/warnings.xhtml#describing-warning-filters) 了解更多细节。 `-x```跳过源中第一行,以允许使用非 Unix 形式的 `#!cmd`。 这适用于 DOS 专属的破解操作。 `-X```保留用于各种具体实现专属的选项。 CPython 目前定义了下列可用的值: - `-X faulthandler` 启用 [`faulthandler`](../library/faulthandler.xhtml#module-faulthandler "faulthandler: Dump the Python traceback."); - `-X showrefcount` 当程序结束或在交互解释器中的每条语句之后输出总引用计数和已使用内存块计数。 此选项仅在调试版本中有效。 - `-X tracemalloc` 使用 [`tracemalloc`](../library/tracemalloc.xhtml#module-tracemalloc "tracemalloc: Trace memory allocations.") 模块启动对 Python 内存分配的跟踪。 默认情况下,只有最近的帧会保存在跟踪的回溯信息中。 使用 `-X tracemalloc=NFRAME` 以启动限定回溯 *NFRAME* 帧的跟踪。 请参阅 [`tracemalloc.start()`](../library/tracemalloc.xhtml#tracemalloc.start "tracemalloc.start") 了解详情。 - `-X showalloccount` 当程序结束时输出每种类型的已分配对象的总数。 此选项仅当 Python 在定义了 `COUNT_ALLOCS` 后构建时才会生效。 - `-X importtime` 显示每次导入耗费的时间。 它会显示模块名称,累计时间(包括嵌套的导入)和自身时间(排除嵌套的导入)。 请注意它的输出在多线程应用程序中可能会出错。 典型用法如 `python3 -X importtime -c 'import asyncio'`。 另请参阅 [`PYTHONPROFILEIMPORTTIME`](#envvar-PYTHONPROFILEIMPORTTIME)。 - `-X dev`: 启用 CPython 的“开发模式”,引入额外的运行时检测,这些检测因开销过大而无法默认启用。 如果代码是正确的则它不会比默认输出更详细:新增警告只会在发现问题时才会发出。 开发模式的作用效果: - 添加 `default` 警告过滤器,即 [`-W`](#cmdoption-w)`default`。 - 在内存分配器上安装调试钩子:参见 [`PyMem_SetupDebugHooks()`](../c-api/memory.xhtml#c.PyMem_SetupDebugHooks "PyMem_SetupDebugHooks") C 函数。 - 启用 [`faulthandler`](../library/faulthandler.xhtml#module-faulthandler "faulthandler: Dump the Python traceback.") 模块以在发生崩溃时转储 Python 回溯信息。 - 启用 [asyncio 调试模式](../library/asyncio-dev.xhtml#asyncio-debug-mode)。 - 将 [`sys.flags`](../library/sys.xhtml#sys.flags "sys.flags") 的 `dev_mode` 属性设为 `True` - `-X utf8` 为操作系统接口启用 UTF-8 模式,覆盖默认的区域感知模式。 `-X utf8=0` 显式地禁用 UTF-8 模式(即使在它应当被自动激活的时候)。 请参阅 [`PYTHONUTF8`](#envvar-PYTHONUTF8) 了解详情。 它还允许传入任意值并通过 [`sys._xoptions`](../library/sys.xhtml#sys._xoptions "sys._xoptions") 字典来提取这些值。 在 3.2 版更改: 增加了 [`-X`](#id5) 选项。 3\.3 新版功能: `-X faulthandler` 选项。 3\.4 新版功能: `-X showrefcount` 与 `-X tracemalloc` 选项。 3\.6 新版功能: `-X showalloccount` 选项。 3\.7 新版功能: `-X importtime`, `-X dev` 与 `-X utf8` 选项。 ### 1.1.4. 不应当使用的选项 `-J```保留给 [Jython](http://www.jython.org/) \[http://www.jython.org/\] 使用。 ## 1.2. 环境变量 这些环境变量会影响 Python 的行为,它们是在命令行开关之前被处理的,但 -E 或 -I 除外。 根据约定,当存在冲突时命令行开关会覆盖环境变量的设置。 `PYTHONHOME`更改标准 Python 库的位置。 默认情况下库是在 `prefix/lib/pythonversion` 和 `exec_prefix/lib/pythonversion` 中搜索,其中 `prefix` 和 `exec_prefix` 是由安装位置确定的目录,默认都位于 `/usr/local`。 当 [`PYTHONHOME`](#envvar-PYTHONHOME) 被设为单个目录时,它的值会同时替代 `prefix` 和 `exec_prefix`。 要为两者指定不同的值,请将 [`PYTHONHOME`](#envvar-PYTHONHOME) 设为 `prefix:exec_prefix`。 `PYTHONPATH`增加模块文件默认搜索路径。 所用格式与终端的 `PATH` 相同:一个或多个由 [`os.pathsep`](../library/os.xhtml#os.pathsep "os.pathsep") 分隔的目录路径名称(例如 Unix 上用冒号而在 Windows 上用分号)。 默认忽略不存在的目录。 除了普通目录之外,单个 [`PYTHONPATH`](#envvar-PYTHONPATH) 条目可以引用包含纯Python模块的zip文件(源代码或编译形式)。无法从zip文件导入扩展模块。 The default search path is installation dependent, but generally begins with `prefix/lib/pythonversion` (see [`PYTHONHOME`](#envvar-PYTHONHOME) above). It is *always* appended to [`PYTHONPATH`](#envvar-PYTHONPATH). An additional directory will be inserted in the search path in front of [`PYTHONPATH`](#envvar-PYTHONPATH) as described above under [接口选项](#using-on-interface-options). The search path can be manipulated from within a Python program as the variable [`sys.path`](../library/sys.xhtml#sys.path "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`](../library/sys.xhtml#sys.ps1 "sys.ps1") and [`sys.ps2`](../library/sys.xhtml#sys.ps2 "sys.ps2") and the hook [`sys.__interactivehook__`](../library/sys.xhtml#sys.__interactivehook__ "sys.__interactivehook__") in this file. `PYTHONOPTIMIZE`If this is set to a non-empty string it is equivalent to specifying the [`-O`](#cmdoption-o) option. If set to an integer, it is equivalent to specifying [`-O`](#cmdoption-o) multiple times. `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()`](../library/sys.xhtml#sys.breakpointhook "sys.breakpointhook") which itself is called by built-in [`breakpoint()`](../library/functions.xhtml#breakpoint "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()`](../library/sys.xhtml#sys.breakpointhook "sys.breakpointhook")to do nothing but return immediately. 3\.7 新版功能. `PYTHONDEBUG`If this is set to a non-empty string it is equivalent to specifying the [`-d`](#cmdoption-d) option. If set to an integer, it is equivalent to specifying [`-d`](#cmdoption-d) multiple times. `PYTHONINSPECT`If this is set to a non-empty string it is equivalent to specifying the [`-i`](#cmdoption-i) option. This variable can also be modified by Python code using [`os.environ`](../library/os.xhtml#os.environ "os.environ")to force inspect mode on program termination. `PYTHONUNBUFFERED`If this is set to a non-empty string it is equivalent to specifying the [`-u`](#cmdoption-u) option. `PYTHONVERBOSE`If this is set to a non-empty string it is equivalent to specifying the [`-v`](#id4) option. If set to an integer, it is equivalent to specifying [`-v`](#id4) multiple times. `PYTHONCASEOK`If this is set, Python ignores case in [`import`](../reference/simple_stmts.xhtml#import) statements. This only works on Windows and OS X. `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`](#id1) option. `PYTHONHASHSEED`If this variable is not set or set to `random`, a random value is used to seed the hashes of str, bytes and datetime objects. If [`PYTHONHASHSEED`](#envvar-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. The integer must be a decimal number in the range \[0,4294967295\]. Specifying the value 0 will disable hash randomization. 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()`](../library/stdtypes.xhtml#str.encode "str.encode"). For stderr, the `:errorhandler` part is ignored; the handler will always be `'backslashreplace'`. 在 3.4 版更改: “encodingname” 部分现在是可选的。 在 3.6 版更改: On Windows, the encoding specified by this variable is ignored for interactive console buffers unless [`PYTHONLEGACYWINDOWSSTDIO`](#envvar-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`](../library/site.xhtml#site.USER_SITE "site.USER_SITE") to [`sys.path`](../library/sys.xhtml#sys.path "sys.path"). 参见 [**PEP 370**](https://www.python.org/dev/peps/pep-0370) \[https://www.python.org/dev/peps/pep-0370\] -- 分用户的 site-packages 目录 `PYTHONUSERBASE`Defines the [`user base directory`](../library/site.xhtml#site.USER_BASE "site.USER_BASE"), which is used to compute the path of the [`user site-packages directory`](../library/site.xhtml#site.USER_SITE "site.USER_SITE")and [Distutils installation paths](../install/index.xhtml#inst-alt-install-user) for `python setup.py install --user`. 参见 [**PEP 370**](https://www.python.org/dev/peps/pep-0370) \[https://www.python.org/dev/peps/pep-0370\] -- 分用户的 site-packages 目录 `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. Only works on Mac OS X. `PYTHONWARNINGS`This is equivalent to the [`-W`](#cmdoption-w) option. If set to a comma separated string, it is equivalent to specifying [`-W`](#cmdoption-w) multiple times, with filters later in the list taking precedence over those earlier in the list. 最简单的设置是将某个特定操作无条件地应用于进程所发出所有警告 (即使是在默认情况下会忽略的那些警告): ``` 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 ``` 请参阅 [The Warnings Filter](../library/warnings.xhtml#warning-filter) 和 [Describing Warning Filters](../library/warnings.xhtml#describing-warning-filters) 了解更多细节。 `PYTHONFAULTHANDLER`If this environment variable is set to a non-empty string, [`faulthandler.enable()`](../library/faulthandler.xhtml#faulthandler.enable "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`](#id5)`faulthandler` option. 3\.3 新版功能. `PYTHONTRACEMALLOC`If this environment variable is set to a non-empty string, start tracing Python memory allocations using the [`tracemalloc`](../library/tracemalloc.xhtml#module-tracemalloc "tracemalloc: Trace memory allocations.") module. 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. See the [`tracemalloc.start()`](../library/tracemalloc.xhtml#tracemalloc.start "tracemalloc.start") for more information. 3\.4 新版功能. `PYTHONPROFILEIMPORTTIME`If this environment variable is set to a non-empty string, Python will show how long each import takes. This is exactly equivalent to setting `-X importtime` on the command line. 3\.7 新版功能. `PYTHONASYNCIODEBUG`If this environment variable is set to a non-empty string, enable the [debug mode](../library/asyncio-dev.xhtml#asyncio-debug-mode) of the [`asyncio`](../library/asyncio.xhtml#module-asyncio "asyncio: Asynchronous I/O.") module. 3\.4 新版功能. `PYTHONMALLOC`Set the Python memory allocators and/or install debug hooks. Set the family of memory allocators used by Python: - `default`: 使用 [default memory allocators](../c-api/memory.xhtml#default-memory-allocators). - `malloc`: use the `malloc()` function of the C library for all domains ([`PYMEM_DOMAIN_RAW`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_RAW "PYMEM_DOMAIN_RAW"), [`PYMEM_DOMAIN_MEM`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM"), [`PYMEM_DOMAIN_OBJ`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ")). - `pymalloc`: use the [pymalloc allocator](../c-api/memory.xhtml#pymalloc) for [`PYMEM_DOMAIN_MEM`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM") and [`PYMEM_DOMAIN_OBJ`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ") domains and use the `malloc()` function for the [`PYMEM_DOMAIN_RAW`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_RAW "PYMEM_DOMAIN_RAW") domain. 安装调试钩子: - `debug`: install debug hooks on top of the [default memory allocators](../c-api/memory.xhtml#default-memory-allocators). - `malloc_debug`: same as `malloc` but also install debug hooks - `pymalloc_debug`: same as `pymalloc` but also install debug hooks See the [default memory allocators](../c-api/memory.xhtml#default-memory-allocators) and the [`PyMem_SetupDebugHooks()`](../c-api/memory.xhtml#c.PyMem_SetupDebugHooks "PyMem_SetupDebugHooks") function (install debug hooks on Python memory allocators). 在 3.7 版更改: Added the `"default"` allocator. 3\.6 新版功能. `PYTHONMALLOCSTATS`If set to a non-empty string, Python will print statistics of the [pymalloc memory allocator](../c-api/memory.xhtml#pymalloc) every time a new pymalloc object arena is created, and on shutdown. This variable is ignored if the [`PYTHONMALLOC`](#envvar-PYTHONMALLOC) environment variable is used to force the `malloc()` allocator of the C library, or if Python is configured without `pymalloc` support. 在 3.6 版更改: This variable can now also be used on Python compiled in release mode. It now has no effect if set to an empty string. `PYTHONLEGACYWINDOWSFSENCODING`If set to a non-empty string, the default filesystem encoding and errors mode will revert to their pre-3.6 values of 'mbcs' and 'replace', respectively. Otherwise, the new defaults 'utf-8' and 'surrogatepass' are used. This may also be enabled at runtime with [`sys._enablelegacywindowsfsencoding()`](../library/sys.xhtml#sys._enablelegacywindowsfsencoding "sys._enablelegacywindowsfsencoding"). [可用性](../library/intro.xhtml#availability): Windows。 3\.6 新版功能: 有关更多详细信息,请参阅 [**PEP 529**](https://www.python.org/dev/peps/pep-0529) \[https://www.python.org/dev/peps/pep-0529\]。 `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. This variable is ignored if the standard streams are redirected (to files or pipes) rather than referring to console buffers. [可用性](../library/intro.xhtml#availability): Windows。 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. 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()`](../library/locale.xhtml#locale.getdefaultlocale "locale.getdefaultlocale")). Configuring one of these locales (either explicitly or via the above implicit locale coercion) automatically enables the `surrogateescape`[error handler](../library/codecs.xhtml#error-handlers) for [`sys.stdin`](../library/sys.xhtml#sys.stdin "sys.stdin") and [`sys.stdout`](../library/sys.xhtml#sys.stdout "sys.stdout") ([`sys.stderr`](../library/sys.xhtml#sys.stderr "sys.stderr") continues to use `backslashreplace`as it does in any other locale). This stream handling behavior can be overridden using [`PYTHONIOENCODING`](#envvar-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`](#envvar-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](../library/intro.xhtml#availability): \*nix. 3\.7 新版功能: See [**PEP 538**](https://www.python.org/dev/peps/pep-0538) \[https://www.python.org/dev/peps/pep-0538\] for more details. `PYTHONDEVMODE`If this environment variable is set to a non-empty string, enable the CPython "development mode". See the [`-X`](#id5)`dev` option. 3\.7 新版功能. `PYTHONUTF8`If set to `1`, enables the interpreter's UTF-8 mode, where `UTF-8` is used as the text encoding for system interfaces, regardless of the current locale setting. This means that: > - [`sys.getfilesystemencoding()`](../library/sys.xhtml#sys.getfilesystemencoding "sys.getfilesystemencoding") returns `'UTF-8'` (the locale encoding is ignored). > - [`locale.getpreferredencoding()`](../library/locale.xhtml#locale.getpreferredencoding "locale.getpreferredencoding") returns `'UTF-8'` (the locale encoding is ignored, and the function's `do_setlocale` parameter has no effect). > - [`sys.stdin`](../library/sys.xhtml#sys.stdin "sys.stdin"), [`sys.stdout`](../library/sys.xhtml#sys.stdout "sys.stdout"), and [`sys.stderr`](../library/sys.xhtml#sys.stderr "sys.stderr") all use UTF-8 as their text encoding, with the `surrogateescape`[error handler](../library/codecs.xhtml#error-handlers) being enabled for [`sys.stdin`](../library/sys.xhtml#sys.stdin "sys.stdin")and [`sys.stdout`](../library/sys.xhtml#sys.stdout "sys.stdout") ([`sys.stderr`](../library/sys.xhtml#sys.stderr "sys.stderr") continues to use `backslashreplace` as it does in the default locale-aware mode) As a consequence of the changes in those lower level APIs, other higher level APIs also exhibit different default behaviours: > - Command line arguments, environment variables and filenames are decoded to text using the UTF-8 encoding. > - [`os.fsdecode()`](../library/os.xhtml#os.fsdecode "os.fsdecode") and [`os.fsencode()`](../library/os.xhtml#os.fsencode "os.fsencode") use the UTF-8 encoding. > - [`open()`](../library/functions.xhtml#open "open"), [`io.open()`](../library/io.xhtml#io.open "io.open"), and [`codecs.open()`](../library/codecs.xhtml#codecs.open "codecs.open") use the UTF-8 encoding by default. However, they still use the strict error handler by default so that attempting to open a binary file in text mode is likely to raise an exception rather than producing nonsense data. Note that the standard stream settings in UTF-8 mode can be overridden by [`PYTHONIOENCODING`](#envvar-PYTHONIOENCODING) (just as they can be in the default locale-aware mode). 如果设置为“0”,则解释器以其默认的区域识别模式运行。 设置任何其他非空字符串会在解释器初始化期间导致错误。 如果根本未设置此环境变量,则解释器默认使用当前区域设置,*除非* 当前区域被标识为基于 ASCII 的旧式区域设置(如 [`PYTHONCOERCECLOCALE`](#envvar-PYTHONCOERCECLOCALE) 所述),并且区域强制转换被禁用或失败。 在此类旧式区域设置中,解释器将默认启用 UTF-8 模式,除非显式地指定不这样做。 也可以使用 [`-X`](#id5)`utf8` 选项。 [Availability](../library/intro.xhtml#availability): \*nix. 3\.7 新版功能: 有关更多详细信息,请参阅 [**PEP 540**](https://www.python.org/dev/peps/pep-0540) \[https://www.python.org/dev/peps/pep-0540\] 。 ### 1.2.1. 调试模式变量 设置这些变量只会在Python的调试版本中产生影响,也就是说,如果Python配置了 `--with-pydebug` 构建选项。 `PYTHONTHREADDEBUG`如果设置,Python将打印线程调试信息。 `PYTHONDUMPREFS`如果设置,Python在关闭解释器,及转储对象和引用计数后仍将保持活动。 ### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](unix.xhtml "2. 在Unix平台中使用Python") | - [上一页](index.xhtml "安装和使用 Python") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [安装和使用 Python](index.xhtml) » - $('.inline-search').show(0); | © [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。