runpy
— Locating and executing Python modules查找和执行Python模块¶
Source code: Lib/runpy.py
The runpy
module is used to locate and run Python modules without importing them first. runpy
模块用于定位和运行Python模块,而无需先导入它们。Its main use is to implement the 它的主要用途是实现-m
command line switch that allows scripts to be located using the Python module namespace rather than the filesystem.-m
命令行开关,该开关允许使用Python模块名称空间而不是文件系统定位脚本。
Note that this is not a sandbox module - all code is executed in the current process, and any side effects (such as cached imports of other modules) will remain in place after the functions have returned.请注意,这不是一个沙盒模块-所有代码都在当前进程中执行,任何副作用(如其他模块的缓存导入)都将在函数返回后保留。
Furthermore, any functions and classes defined by the executed code are not guaranteed to work correctly after a 此外,在runpy
function has returned. runpy
函数返回后,由执行的代码定义的任何函数和类都不能保证正常工作。If that limitation is not acceptable for a given use case, 如果这个限制对于给定的用例来说是不可接受的,那么importlib
is likely to be a more suitable choice than this module.importlib
可能是比这个模块更合适的选择。
The runpy
module provides two functions:runpy
模块提供两个功能:
-
runpy.
run_module
(mod_name, init_globals=None, run_name=None, alter_sys=False)¶ -
Execute the code of the specified module and return the resulting module globals dictionary.执行指定模块的代码并返回生成的模块全局字典。The module’s code is first located using the standard import mechanism (refer to PEP 302 for details) and then executed in a fresh module namespace.模块的代码首先使用标准导入机制定位(详细信息请参阅PEP 302),然后在新的模块名称空间中执行。The mod_name argument should be an absolute module name.mod_name参数应为绝对模块名称。If the module name refers to a package rather than a normal module, then that package is imported and the如果模块名称引用的是一个包而不是一个普通模块,则导入该包,然后执行该包中的__main__
submodule within that package is then executed and the resulting module globals dictionary returned.__main__
子模块,并返回生成的模块全局字典。The optional dictionary argument init_globals may be used to pre-populate the module’s globals dictionary before the code is executed.可选的字典参数init_globals可以用于在执行代码之前预先填充模块的全局字典。The supplied dictionary will not be modified.不会修改提供的词典。If any of the special global variables below are defined in the supplied dictionary, those definitions are overridden by如果在提供的字典中定义了以下任何特殊的全局变量,则这些定义将被run_module()
.run_module()
覆盖。The special global variables特殊全局变量__name__
,__spec__
,__file__
,__cached__
,__loader__
and__package__
are set in the globals dictionary before the module code is executed (Note that this is a minimal set of variables - other variables may be set implicitly as an interpreter implementation detail).__name__
、__spec__
、__file__
、__cached__
、__loader__
和__package__
在执行模块代码之前在全局字典中设置(注意,这是一组最小的变量-其他变量可以隐式设置为解释器实现细节)。如果此可选参数不是__name__
is set to run_name if this optional argument is notNone
, tomod_name + '.__main__'
if the named module is a package and to the mod_name argument otherwise.None
,则__name__
设置为mod_name + '.__main__'
(如果命名模块是包),否则返回mod_name参数。将为实际导入的模块适当设置__spec__
will be set appropriately for the actually imported module (that is,__spec__.name
will always be mod_name ormod_name + '.__main__
, never run_name).__spec__
(即,__spec__.name
将始终为mod_name或mod_name + '.__main__
,而不是run_name)。__file__
,__cached__
,__loader__
and__package__
are set as normal based on the module spec.__file__
、__cached__
、__loader__
和__package__
根据模块规范设置为正常。If the argument alter_sys is supplied and evaluates to如果提供了参数alter_sys并计算为True
, thensys.argv[0]
is updated with the value of__file__
andsys.modules[__name__]
is updated with a temporary module object for the module being executed.True
,则sys.argv[0]
将使用__file__
值更新,sys.modules[__name__]
将使用正在执行的模块的临时模块对象更新。Both在函数返回之前,sys.argv[0]
andsys.modules[__name__]
are restored to their original values before the function returns.sys.argv[0]
和sys.modules[__name__]
都将恢复为其原始值。Note that this manipulation of注意,对sys
is not thread-safe.sys
的这种操作不是线程安全的。Other threads may see the partially initialised module, as well as the altered list of arguments.其他线程可能会看到部分初始化的模块,以及更改的参数列表。It is recommended that the从线程代码调用此函数时,建议不要使用sys
module be left alone when invoking this function from threaded code.sys
模块。Changed in version 3.1:版本3.1中更改:Added ability to execute packages by looking for a通过查找__main__
submodule.__main__
子模块增加了执行包的能力。Changed in version 3.2:版本3.2中更改:Added添加__cached__
global variable (see PEP 3147).__cached__
全局变量(参见PEP 3147)。Changed in version 3.4:版本3.4中更改:Updated to take advantage of the module spec feature added by PEP 451.更新以利用PEP 451添加的模块规范功能。This allows这允许为以这种方式运行的模块正确设置__cached__
to be set correctly for modules run this way, as well as ensuring the real module name is always accessible as__spec__.name
.__cached__
,并确保真实模块名称始终可以作为__spec__.name
访问。
-
runpy.
run_path
(path_name, init_globals=None, run_name=None)¶ -
Execute the code at the named filesystem location and return the resulting module globals dictionary.在指定的文件系统位置执行代码,并返回生成的模块全局字典。As with a script name supplied to the CPython command line, the supplied path may refer to a Python source file, a compiled bytecode file or a valid sys.path entry containing a与提供给CPython命令行的脚本名称一样,提供的路径可以引用Python源文件、编译的字节码文件或包含__main__
module (e.g. a zipfile containing a top-level__main__.py
file).__main__
模块的有效sys.path
条目(例如,包含顶级__main__.py
文件的zip文件)。For a simple script, the specified code is simply executed in a fresh module namespace.对于简单的脚本,只需在新的模块名称空间中执行指定的代码。For a valid sys.path entry (typically a zipfile or directory), the entry is first added to the beginning of对于有效的sys.path
.sys.path
条目(通常是zip文件或目录),首先将该条目添加到sys.path
的开头。The function then looks for and executes a然后,函数使用更新的路径查找并执行__main__
module using the updated path.__main__
模块。Note that there is no special protection against invoking an existing请注意,如果在指定的位置没有这样的模块,则对调用位于__main__
entry located elsewhere onsys.path
if there is no such module at the specified location.sys.path
上其他位置的现有__main__
条目没有特殊保护。The optional dictionary argument init_globals may be used to pre-populate the module’s globals dictionary before the code is executed.可选的字典参数init_globals可以用于在执行代码之前预先填充模块的全局字典。The supplied dictionary will not be modified.不会修改提供的词典。If any of the special global variables below are defined in the supplied dictionary, those definitions are overridden by如果在提供的字典中定义了以下任何特殊的全局变量,则这些定义将被run_path()
.run_path()
覆盖。The special global variables特殊全局变量__name__
,__spec__
,__file__
,__cached__
,__loader__
and__package__
are set in the globals dictionary before the module code is executed (Note that this is a minimal set of variables - other variables may be set implicitly as an interpreter implementation detail).__name__
、__spec__
、__file__
、__cached__
、__loader__
和__package__
在执行模块代码之前在全局字典中设置(注意,这是一组最小的变量-其他变量可以隐式设置为解释器实现细节)。如果此可选参数不是__name__
is set to run_name if this optional argument is notNone
and to'<run_path>'
otherwise.None
,则__name__
设置为run_name,否则设置为'<run_path>'
。If the supplied path directly references a script file (whether as source or as precompiled byte code), then如果提供的路径直接引用脚本文件(无论是作为源文件还是作为预编译字节码),则__file__
will be set to the supplied path, and__spec__
,__cached__
,__loader__
and__package__
will all be set toNone
.__file__
将设置为提供的路径,__spec__
、__cached__
、__loader__
和__package__
将全部设置为None
。If the supplied path is a reference to a valid sys.path entry, then如果提供的路径是对有效系统路径项的引用,则将为导入的__spec__
will be set appropriately for the imported__main__
module (that is,__spec__.name
will always be__main__
).__main__
模块适当设置__spec__
(即__spec__.name
将始终为__main__
)。__file__
,__cached__
,__loader__
and__package__
will be set as normal based on the module spec.__file__
、__cached__
、__loader__
和__package____包装__将根据模块规范设置为正常。A number of alterations are also made to the还对sys
module.sys
模块进行了一些修改。Firstly,首先,可以如上所述更改sys.path
may be altered as described above.sys.path
。sys.argv[0]
is updated with the value ofpath_name
andsys.modules[__name__]
is updated with a temporary module object for the module being executed.sys.argv[0]
用path_name
的值更新,sys.modules[__name__]
用正在执行的模块的临时模块对象更新。All modifications to items in在函数返回之前,将还原对sys
are reverted before the function returns.sys
中项的所有修改。Note that, unlike请注意,与run_module()
, the alterations made tosys
are not optional in this function as these adjustments are essential to allowing the execution of sys.path entries.run_module()
不同,在该函数中,对sys
所做的更改不是可选的,因为这些调整对于允许执行sys.path条目至关重要。As the thread-safety limitations still apply, use of this function in threaded code should be either serialised with the import lock or delegated to a separate process.由于线程安全限制仍然适用,因此在线程代码中使用该函数应使用导入锁串行化或委托给单独的进程。See also
Interface options for equivalent functionality on the command line (命令行上等效功能的接口选项(python path/to/script
).python path/to/script
)。New in version 3.2.版本3.2中新增。Changed in version 3.4:版本3.4中更改:Updated to take advantage of the module spec feature added by PEP 451.更新以利用PEP 451添加的模块规范功能。This allows这允许在__cached__
to be set correctly in the case where__main__
is imported from a valid sys.path entry rather than being executed directly.__main__
从有效系统路径条目导入而不是直接执行的情况下正确设置__cached__
。
See also另请参见
- PEP 338 –
Executing modules as scripts将模块作为脚本执行 PEP written and implemented by Nick Coghlan.PEP由Nick Coghlan编写和实施。- PEP 366 –
Main module explicit relative imports主模块显式相对导入 PEP written and implemented by Nick Coghlan.PEP由Nick Coghlan编写和实施。- PEP 451 –
A ModuleSpec Type for the Import System导入系统的ModuleSpec类型 PEP written and implemented by Eric Snow由Eric Snow编写和实施的PEP
Command line and environment命令行和环境 - CPython command line detailsCPython命令行详细信息
The importlib.import_module()
functionimportlib.import_module()
函数