runpy —- Locating and executing Python modules

Source code:Lib/runpy.py


The runpy module is used to locate and run Python modules withoutimporting them first. Its main use is to implement the -m commandline switch that allows scripts to be located using the Python modulenamespace rather than the filesystem.

Note that this is not a sandbox module - all code is executed in thecurrent process, and any side effects (such as cached imports of othermodules) will remain in place after the functions have returned.

Furthermore, any functions and classes defined by the executed code are notguaranteed to work correctly after a runpy function has returned.If that limitation is not acceptable for a given use case, importlibis likely to be a more suitable choice than this module.

The runpy module provides two functions:

  • runpy.runmodule(_mod_name, init_globals=None, run_name=None, alter_sys=False)
  • Execute the code of the specified module and return the resulting moduleglobals dictionary. The module's code is first located using the standardimport mechanism (refer to PEP 302 for details) and then executed in afresh module namespace.

The mod_name argument should be an absolute module name.If the module name refers to a package rather than a normalmodule, then that package is imported and the main submodule withinthat package is then executed and the resulting module globals dictionaryreturned.

The optional dictionary argument init_globals may be used to pre-populatethe module's globals dictionary before the code is executed. The supplieddictionary will not be modified. If any of the special global variablesbelow are defined in the supplied dictionary, those definitions areoverridden by run_module().

The special global variables name, spec, file,cached, loader and package are set in the globalsdictionary before the module code is executed (Note that this is aminimal set of variables - other variables may be set implicitly as aninterpreter implementation detail).

name is set to run_name if this optional argument is notNone, to modname + '.main' if the named module is apackage and to the _mod_name argument otherwise.

spec will be set appropriately for the actually importedmodule (that is, spec.name will always be mod_name ormodname + '.main, never _run_name).

file, cached, loader and package areset as normal based on the module spec.

If the argument alter_sys is supplied and evaluates to True,then sys.argv[0] is updated with the value of file andsys.modules[name] is updated with a temporary module object for themodule being executed. Both sys.argv[0] and sys.modules[name]are restored to their original values before the function returns.

Note that this manipulation of sys is not thread-safe. Other threadsmay see the partially initialised module, as well as the altered list ofarguments. It is recommended that the sys module be left alone wheninvoking this function from threaded code.

参见

The -m option offering equivalent functionality from thecommand line.

在 3.1 版更改: Added ability to execute packages by looking for a main submodule.

在 3.2 版更改: Added cached global variable (see PEP 3147).

在 3.4 版更改: Updated to take advantage of the module spec feature added byPEP 451. This allows cached to be set correctly for modulesrun this way, as well as ensuring the real module name is alwaysaccessible as spec.name.

  • runpy.runpath(_file_path, init_globals=None, run_name=None)
  • Execute the code at the named filesystem location and return the resultingmodule globals dictionary. As with a script name supplied to the CPythoncommand line, the supplied path may refer to a Python source file, acompiled bytecode file or a valid sys.path entry containing a mainmodule (e.g. a zipfile containing a top-level main.py file).

For a simple script, the specified code is simply executed in a freshmodule namespace. For a valid sys.path entry (typically a zipfile ordirectory), the entry is first added to the beginning of sys.path. Thefunction then looks for and executes a main module using theupdated path. Note that there is no special protection against invokingan existing main entry located elsewhere on sys.path ifthere is no such module at the specified location.

The optional dictionary argument init_globals may be used to pre-populatethe module's globals dictionary before the code is executed. The supplieddictionary will not be modified. If any of the special global variablesbelow are defined in the supplied dictionary, those definitions areoverridden by run_path().

The special global variables name, spec, file,cached, loader and package are set in the globalsdictionary before the module code is executed (Note that this is aminimal set of variables - other variables may be set implicitly as aninterpreter implementation detail).

name is set to run_name if this optional argument is notNone and to '<run_path>' otherwise.

If the supplied path directly references a script file (whether as sourceor as precompiled byte code), then file will be set to thesupplied path, and spec, cached, loader andpackage will all be set to None.

If the supplied path is a reference to a valid sys.path entry, thenspec will be set appropriately for the imported mainmodule (that is, spec.name will always be main).file, cached, loader and package will beset as normal based on the module spec.

A number of alterations are also made to the sys module. Firstly,sys.path may be altered as described above. sys.argv[0] is updatedwith the value of filepath and sys.modules[_name] is updatedwith a temporary module object for the module being executed. Allmodifications to items in sys are reverted before the functionreturns.

Note that, unlike run_module(), the alterations made to sysare not optional in this function as these adjustments are essential toallowing the execution of sys.path entries. As the thread-safetylimitations still apply, use of this function in threaded code should beeither serialised with the import lock or delegated to a separate process.

参见

接口选项 for equivalent functionality on thecommand line (python path/to/script).

3.2 新版功能.

在 3.4 版更改: Updated to take advantage of the module spec feature added byPEP 451. This allows cached to be set correctly in thecase where main is imported from a valid sys.path entry ratherthan being executed directly.

参见

  • PEP 338 — 将模块作为脚本执行
  • PEP 由 Nick Coghlan 撰写并实现。

  • PEP 366 — Main module explicit relative imports

  • PEP 由 Nick Coghlan 撰写并实现。

  • PEP 451 — A ModuleSpec Type for the Import System

  • PEP written and implemented by Eric Snow

命令行与环境 - CPython command line details

The importlib.import_module() function