runpy
--- 定位並執行 Python 模組¶
原始碼: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,importlib
is 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__.name
will 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
sys
is not thread-safe. Other threadsmay see the partially initialised module, as well as the altered list ofarguments. It is recommended that thesys
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 (seePEP 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
.在 3.12 版的變更:The setting of
__cached__
,__loader__
, and__package__
are deprecated. SeeModuleSpec
for 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.path
entry containing a__main__
module(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 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.path
ifthere 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 notNone
and 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.path
entry, then__spec__
will be set appropriately for the imported__main__
module (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 offile_path andsys.modules[__name__]
is updatedwith a temporary module object for the module being executed. Allmodifications to items insys
are reverted before the functionreturns.Note that, unlike
run_module()
, the alterations made tosys
are not optional in this function as these adjustments are essential toallowing the execution ofsys.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 (
pythonpath/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 validsys.path
entry ratherthan being executed directly.在 3.12 版的變更:The setting of
__cached__
,__loader__
, and__package__
are deprecated.
也參考
- 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
命令列與環境 - CPython command line details
Theimportlib.import_module()
function