【翻译了解部分官方usingDOC】COMMAND LINE AND ENVIRONMENT ABOUT USE PYTHON(关于使用PYTHON的命令行和环境)

 COMMAND LINE AND ENVIRONMENT(命令行和环境)

The CPython interpreter scans the command line and the environment for various settings.
CPython解释器扫描命令行和环境中的各种设置。
 
CPython implementation detail: Other implementations’ command line schemes may differ.
See implementations for further resources.

CPython实现细节:其他实现的命令行方案可能不同。
参见实现以获得更多的参考资料。

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设备的标准输入调用时,它提示输入命令并执行它们,直到执行。
 
  • When called with a file name argument or with a file as standard input, it reads and executes a script from that fifile.
    当使用fifile名称参数或文件作为标准输入调用时,它将读取并执行来自该fifile的脚本。
 
  • 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.
          Here command may contain multiple statements separated by newlines.
     Leading whitespace is signifificant in Python statements!
    当使用-c命令调用时,它将执行作为命令给出的Python语句。
    这里的命令可以包含多个由换行分隔的语句。
    在Python语句中,前导空格非常重要!
 
  • When called with -m module-name, the given module is located on the Python module path and executed as a script.
    当使用-m模块名调用时,给定的模块位于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 fifirst element, subscript zero (sys.argv[0]), is a string reflecting the program’s source.
一个接口选项将终止解释器使用的选项列表,所有连续的参数都将在sys.argc中结束——注意,第一个元素下标0 (sys.argv[0])是一个回流程序源代码的字符串。
 
-c <command>
  Execute the Python code in command. command can be one or more statements separated by newlines, with signifificant leading whitespace as in normal module code. 
  在命令中执行Python代码。命令可以是一个或多个用换行符分隔的语句,如普通模块代码中那样,以有意义的空格开头。
  
  If this option is given, the fifirst element of sys.argv will be "-c" and the current directory will be added to the start of sys.
  如果给出这个选项,则sys的第一个元素。argv将是“-c”,当前目录将添加到sys的开始。
  
  path (allowing modules in that directory to be imported as top level modules).
  路径(允许将该目录中的模块导入为顶级模块)。
  
  Raises an auditing event cpython.run_command with argument command.
     使用参数命令引发审计事件cpython.run。
-m <module-name>
  Search sys.path for the named module and execute its contents as the __main__ module.
  为命名模块搜索sys.path,并将其内容作为主模块执行。
  
  Since the argument is a module name, you must not give a fifile extension (.py).
  因为参数是一个模块名,所以不能给出fifile扩展名(.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.
  这种行为与处理作为脚本参数传递给解释器的目录和zipfile类似。

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

  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.
  引发具有参数模块名的审计事件cpython.run_module。
  
  See also:
  runpy.run_module() Equivalent functionality directly available to Python code
  runpy.run_module()可直接用于Python代码的等效功能

 

  PEP 338 – Executing modules as scripts
  PEP 338 – 将模块作为脚本执行
  
  Changed in version 3.1: Supply the package name to run a __main__ submodule.
  3.1版本中的变化:提供包名来运行一个_main__子模块。
 
  Changed in version 3.4: namespace packages are also supported
  3.4版本中的变化:还支持名称空间包
  -
  Read commands from standard input (sys.stdin). If standard input is a terminal, -i is implied.
  从标准输入(sys.stdin)读取命令。如果标准输入是终端,则使用-i。
  If this option is given, the fifirst 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 fifile.
  执行脚本中包含的Python代码,它必须是一个文件系统路径(绝对的或相对的),该路径要么引用Python 文件,要么引用包含一个__main__. py文件的目录,要么引用包含一个__mian__. 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的第一个元素。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.
  使用参数文件名引发审计事件cpython.run_file。
 
See also:
runpy.run_path() Equivalent functionality directly available to Python code
runpy.run_path()是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 rlcompleter-confifig).
此外,如果您的平台上有选项卡完成和历史记录编辑功能,那么它们将自动启用(请参阅rlcompleter-confifig)。
See also:
tut-invoking
Changed in version 3.4: Automatic enabling of tab-completion and history editing
3.4版本的变化:自动启用tab完成和历史记录编辑

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. Example output could be:
  打印Python版本号并退出。示例输出可以是:
  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: The -VV option.
  3.6新版本:-VV选项。

1.1.3 Miscellaneous options(杂项选项)

-b
  Issue a warning when comparing bytes or bytearray with str or bytes with int. Issue an error when the option is given twice (-bb).
  在比较字节或字节数组与str或字节与int时发出警告。在给出两次选项时发出错误(-bb)。

  Changed in version 3.5: Affects comparisons of bytes with int.
  版本3.5中的变化:影响字节与int的比较。
-B
  If given, Python won’t try to write .pyc files on the import of source modules.
  如果给定,Python将不会尝试在源模块的导入上编写.pyc文件。
  See also PYTHONDONTWRITEBYTECODE.
--check-hash-based-pycs default|always|never
  Control the validation behavior of hash-based .pyc files.
  控制基于哈希的.pyc 文件的验证行为。
  See pyc-invalidation.
  看pyc-invalidation。
  When set to default, checked and unchecked hash-based bytecode cache files are validated according to their default semantics.
  将其设置为默认值时,将根据默认语义验证已检查和未检查的基于散列的字节码缓存文件。
  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*环境变量,例如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 when sys.stdin does not appear to be a terminal.
  当脚本作为第一个参数传递或使用-c选项时,在执行脚本或命令后进入交互模式,即使在sys时也是如此。stdin似乎不是一个终端
  The PYTHONSTARTUP fifile is not read.
  未读取PYTHONSTARTUP fifile。
  This can be useful to inspect global variables or a stack trace when a script raises an exception.
  这对于在脚本引发异常时检查全局变量或堆栈跟踪非常有用。
  See also PYTHONINSPECT.
-I
  Run Python in isolated mode. This also implies -E and -s.
  以隔离模式运行Python。这也意味着-E和-s。
  In isolated mode sys.path contains neither the script’s directory nor the user’s site-packages directory.
  在隔离模式下。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.
-O
  Remove assert statements and any code conditional on the value of __debug__.
  删除断言语句和任何以_debug__的值为条件的代码。
  Augment the filename for compiled (bytecode) files by adding .
  通过 添加 Augment 的 文件名 compiled (bytecode) 文件 。
  opt-1 before the .pyc extension (see PEP 488).
  opt-1在.pyc扩展之前(参见PEP 488)。
  See also PYTHONOPTIMIZE.
  Changed in version 3.5: Modify .pyc filenames according to PEP 488.
  版本3.5中的更改:根据PEP 488修改.pyc 文件名。

-OO
  Do -O and also discard docstrings. 
  执行-O并丢弃文档字符串。
  Augment the fifilename for compiled (bytecode) fifiles by adding .opt-2 before the .pyc extension (see PEP 488).
  通过在.pyc扩展名之前添加.opt-2来增加已编译(字节码)fifile的文件名(参见PEP 488)。
  Changed in version 3.5: Modify .pyc filenames according to PEP 488.
  版本3.5中的更改:根据PEP 488修改.pyc文件名。
-q
  Don’t display the copyright and version messages even in interactive mode.
  即使在交互模式下也不要显示版权和版本信息。
  New in version 3.2.
-R
  Turn on hash randomization.
  打开哈希随机化。
  This option only has an effffect 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__()值就被“添加”了一个不可预测的随机值。
  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(n^2) complexity.
  哈希随机化的目的是防止由精心选择的输入导致的拒绝服务,这些输入利用了dict结构最坏情况下的性能,复杂度为O(n^2)。
  See advisories/ocert-2011-003.htmlor details.
  PYTHONHASHSEED allows you to set a fixed value for the hash seed secret.
  PYTHONHASHSEED允许您为散列种子机密设置一个固定的值。
  Changed in version 3.7: The option is no longer ignored.
  版本3.7中的变化:该选项不再被忽略。
  New in version 3.2.3.
-s
  Don’t add the user site-packages directory to sys.path.
  不要将用户站点-包目录添加到sys.path。
  See also:
  PEP 370 – Per user site-packages directory 
-S
  Disable the import of the module site and the site-dependent manipulations of sys.path that it entails.

  禁用模块站点的导入和sys的站点相关操作。它所包含的路径。

  Also disable these manipulations if site is explicitly imported later (call site.main() if you want them to betriggered).

  如果以后要显式导入站点,还要禁用这些操作( 如果希望触发这些操作,请调用site.main() )。

-u
  Force the stdout and stderr streams to be unbuffered.
  强制取消对stdout和stderr流的缓冲。
  This option has no effffect on the stdin stream.
  此选项对stdin流没有影响。
  See also PYTHONUNBUFFERED.
  Changed in version 3.7: The text layer of the stdout and stderr streams now is unbuffered.
  版本3.7的变化:stdout和stderr流的文本层现在不缓冲了。
-v
  Print a message each time a module is initialized, showing the place (fifilename or built-in module) from which it is loaded.
  每次模块初始化时打印一条消息,显示加载它的位置(fifilename或内置模块)。
    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.
  还提供有关退出时模块清理的信息。
  See also PYTHONVERBOSE.
-W arg
  Warning control. Python’s warning machinery by default prints warning messages to sys.stderr.
  预警控制。Python的警告机制默认将警告消息打印到sys.stderr。

  A typical warning message has the following form:
  典型的警告信息有以下形式:
  file:line: category: message
  
  By default, each warning is printed once for each source line where it occurs.
  默认情况下,对于出现的每个源代码行,每个警告只打印一次。
  This option controls how often warnings are printed.
  此选项控制打印警告的频率。
  
  Multiple -W options may 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 fifirst 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环境变量和在Python程序中使用Warnings模块来控制警告。
  
  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 (e.g. -Wi, -Wd, -Wa, -We) and the interpreter will resolve them to the appropriate action name.
  操作名可以根据需要缩写(例如-Wi、-Wd、-Wa、-We),解释器将解析它们为适当的操作名。
  
  See warning-filter and describing-warning-filters for more details.
  有关详细信息,请参见警告过滤器和描述警告过滤器。
-x
  Skip the fifirst line of the source, allowing use of non-Unix forms of #!cmd.
  跳过源代码的第5行,允许使用非unix形式的#!cmd。
  This is intended for a DOS specifific hack only.
  这是专为一个DOS特定的黑客。
-X
  Reserved for various implementation-specifific options.
  预留给各种实现特定的选项。
  CPython currently defifines the following possible values:
  CPython目前挑战以下可能的值:
  • -X fault handler to enable fault handler;
    -X故障处理程序以启用故障处理程序;
  • -X showrefcount to output the total reference count and number of used memory blocks when the program fifinishes or after each statement in the interactive interpreter.
    This only works on debug builds.

    -X showrefcount在交互式解释器中输出程序结束时或每条语句结束后的总引用计数和使用的内存块数。
    这只适用于调试构建。

  • -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 tracemalloc使用tracemalloc模块开始跟踪Python内存分配。
    默认情况下,仅将最近的帧存储在跟踪的回溯中。
    使用-X tracemalloc=NFRAME使用NFRAME的回溯限制开始跟踪。
    有关更多信息,请参见tracemallock .start()。

  • -X showalloccount to output the total count of allocated objects for each type when the program finishes.
    This only works when Python was built with COUNT_ALLOCS defifined.

    -X showalloccount输出程序结束时为每种类型分配的对象的总数。
    这只适用于在构建Python时使用COUNT_ALLOCS挑战的情况。

  • -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 multithreaded application.
    Typical usage is python3 -X importtime -c 'import asyncio'.
    See also PYTHONPROFILEIMPORTTIME.

    -X importtime来显示每个导入需要多长时间。
    它显示模块名、累计时间(包括嵌套导入)和自我时间(不包括嵌套导入)。
    Note 它 的 输出 可能 被 打破 multithreaded 此 规则
    典型的用法是python3 -X importtime -c 'import asyncio'。
    也看到PYTHONPROFILEIMPORTTIME。

  • -X dev: enable CPython’s “development mode”, introducing additional runtime checks which are too expensive to be enabled by default.
    It should not be more verbose than the default if the code is correct: new warnings are only emitted when an issue is detected.
    Effect of the developer mode:

    -X dev: 启用 CPython’s “development mode”, 引入 额外 的 运行 时 检查 , 这 太 expensive default. 启用
    如果代码正确,它不应该比默认的更详细:只有在检测到问题时才会发出新的警告。
    开发模式的效果:

    – Add default warning fifilter, as -W default.
    – Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function.
    – Enable the faulthandler module to dump the Python traceback on a crash.
    – Enable asyncio debug mode.
    – Set the dev_mode attribute of sys.flags to True.
    – io.IOBase destructor logs close() exceptions.
    

    -添加默认的警告fifilter,作为- w的默认值。
    -在内存分配器上安装调试钩子:参见PyMem_SetupDebugHooks() C函数。
    -启用faulthandler模块在崩溃时转储Python回溯。
    -启用异步调试模式。
    -设置sys.path的dev_mode属性为True。
    - io.IOBase析构函数记录close()异常。

  • -X utf8 enables UTF-8 mode for operating system interfaces, overriding the default locale-aware mode.
    -X utf8支持操作系统接口的UTF-8模式,覆盖默认的本地语言环境感知模式。
  • -X utf8=0 explicitly disables UTF-8 mode (even when it would otherwise activate automatically).
    See PYTHONUTF8 for more details.

    -X utf8=0显式禁用UTF-8模式(即使它会自动激活)。
    有关更多细节,请参见PYTHONUTF8。

  • -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 pycache_prefix=PATH允许将.pyc文件写入以给定目录为根的并行树,而不是写入代码树。
    也看到PYTHONPYCACHEPREFIX。

  It also allows passing arbitrary values and retrieving them through the sys._xoptions dictionary.
  

  它还允许通过sys._xoptions字典传递任意值并检索它们。

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

  New in version 3.3: The -X faulthandler option.
  New in version 3.4: The -X showrefcount and -X tracemalloc options.
  New in version 3.6: The -X showalloccount option.
  New in version 3.7: The -X importtime, -X dev and -X utf8 options.
  New in version 3.8: The -X pycache_prefix option. The -X dev option now logs close() exceptions in io.IOBase destructor.


 本文档其他详细内容,请参见:using.pdf
 
posted @ 2020-04-15 17:57  厸清扬  阅读(258)  评论(0编辑  收藏  举报