runpyLocating 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 not None, to mod_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 or mod_name + '.__main__, never run_name).将为实际导入的模块适当设置__spec__(即,__spec__.name将始终为mod_namemod_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 True, then sys.argv[0] is updated with the value of __file__ and sys.modules[__name__] is updated with a temporary module object for the module being executed. 如果提供了参数alter_sys并计算为True,则sys.argv[0]将使用__file__值更新,sys.modules[__name__]将使用正在执行的模块的临时模块对象更新。Both sys.argv[0] and sys.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模块。

See also

The -m option offering equivalent functionality from the command line.-m选项从命令行提供等效的功能。

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 __main__ module (e.g. a zipfile containing a top-level __main__.py file).与提供给CPython命令行的脚本名称一样,提供的路径可以引用Python源文件、编译的字节码文件或包含__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 on sys.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 not None 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 to None.如果提供的路径直接引用脚本文件(无论是作为源文件还是作为预编译字节码),则__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.pathsys.argv[0] is updated with the value of path_name and sys.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 to sys 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 338Executing modules as scripts将模块作为脚本执行

PEP written and implemented by Nick Coghlan.PEP由Nick Coghlan编写和实施。

PEP 366Main module explicit relative imports主模块显式相对导入

PEP written and implemented by Nick Coghlan.PEP由Nick Coghlan编写和实施。

PEP 451A 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()函数