runpy — Locating and executing Python modules¶
Source code:Lib/runpy.py
Therunpy 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 isnot 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 arunpy 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.
Therunpy module provides two functions:
- 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’sglobals dictionary. The module’s code is first located using the standardimport mechanism (refer toPEP 302 for details) and then executed in afresh module namespace.
Themod_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 argumentinit_globals may be used to pre-populatethe module’s globals dictionary before the code is executed.init_globals will not be modified. If any of the special global variablesbelow are defined ininit_globals, 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 torun_name if this optional argument is notNone, tomod_name+'.__main__'if the named module is apackage and to themod_name argument otherwise.__spec__will be set appropriately for theactually importedmodule (that is,__spec__.namewill always bemod_name ormod_name+'.__main__', neverrun_name).__file__,__cached__,__loader__and__package__areset as normal based on the module spec.If the argumentalter_sys is supplied and evaluates to
True,thensys.argv[0]is updated with the value of__file__andsys.modules[__name__]is updated with a temporary module object for themodule being executed. Bothsys.argv[0]andsys.modules[__name__]are restored to their original values before the function returns.Note that this manipulation of
sysis not thread-safe. Other threadsmay see the partially initialised module, as well as the altered list ofarguments. It is recommended that thesysmodule be left alone wheninvoking this function from threaded code.See also
The
-moption offering equivalent functionality from thecommand line.Changed in version 3.1:Added ability to execute packages by looking for a
__main__submodule.Changed in version 3.2:Added
__cached__global variable (seePEP 3147).Changed in version 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.Changed in version 3.12:The setting of
__cached__,__loader__, and__package__are deprecated. SeeModuleSpecfor alternatives.
- runpy.run_path(path_name,init_globals=None,run_name=None)¶
Execute the code at the named filesystem location and return the resultingmodule’s globals dictionary. As with a script name supplied to the CPythoncommand line,file_path may refer to a Python source file, acompiled bytecode file or a valid
sys.pathentry containing a__main__module(e.g. a zipfile containing a top-level__main__.pyfile).For a simple script, the specified code is simply executed in a freshmodule namespace. For a valid
sys.pathentry (typically a zipfile ordirectory), the entry is first added to the beginning ofsys.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 onsys.pathifthere is no such module at the specified location.The optional dictionary argumentinit_globals may be used to pre-populatethe module’s globals dictionary before the code is executed.init_globals will not be modified. If any of the special global variablesbelow are defined ininit_globals, 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 torun_name if this optional argument is notNoneand to'<run_path>'otherwise.Iffile_path directly references a script file (whether as sourceor as precompiled byte code), then
__file__will be set tofile_path, and__spec__,__cached__,__loader__and__package__will all be set toNone.Iffile_path is a reference to a valid
sys.pathentry, then__spec__will be set appropriately for the imported__main__module (that is,__spec__.namewill 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
sysmodule. Firstly,sys.pathmay be altered as described above.sys.argv[0]is updatedwith the value offile_path andsys.modules[__name__]is updatedwith a temporary module object for the module being executed. Allmodifications to items insysare reverted before the functionreturns.Note that, unlike
run_module(), the alterations made tosysare not optional in this function as these adjustments are essential toallowing the execution ofsys.pathentries. 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.See also
Interface options for equivalent functionality on thecommand line (
pythonpath/to/script).Added in version 3.2.
Changed in version 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 validsys.pathentry ratherthan being executed directly.Changed in version 3.12:The setting of
__cached__,__loader__, and__package__are deprecated.
See also
- PEP 338 – Executing modules as scripts
PEP written and implemented by Nick Coghlan.
- PEP 366 – Main module explicit relative imports
PEP written and implemented by Nick Coghlan.
- PEP 451 – A ModuleSpec Type for the Import System
PEP written and implemented by Eric Snow
Command line and environment - CPython command line details
Theimportlib.import_module() function