Movatterモバイル変換


[0]ホーム

URL:


Navigation

30.5.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 moduleglobals dictionary. The module’s code is first located using the standardimport mechanism (refer toPEP 302 for details) and then executed in afresh module namespace.

If the supplied 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. The supplieddictionary will not be modified. If any of the special global variablesbelow are defined in the supplied dictionary, those definitions areoverridden byrun_module().

The special global variables__name__,__file__,__cached__,__loader__and__package__ are set in the globals dictionary before the modulecode is executed (Note that this is a minimal set of variables - othervariables may be set implicitly as an interpreter 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.

__file__ is set to the name provided by the module loader. If theloader does not make filename information available, this variable is settoNone.

__cached__ will be set toNone.

__loader__ is set to thePEP 302 module loader used to retrieve thecode for the module (This loader may be a wrapper around the standardimport mechanism).

__package__ is set tomod_name if the named module is a package andtomod_name.rpartition('.')[0] otherwise.

If the argumentalter_sys is supplied and evaluates toTrue,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 ofsys 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.

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).

runpy.run_path(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__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. The supplieddictionary will not be modified. If any of the special global variablesbelow are defined in the supplied dictionary, those definitions areoverridden byrun_path().

The special global variables__name__,__file__,__loader__and__package__ are set in the globals dictionary before the modulecode is executed (Note that this is a minimal set of variables - othervariables may be set implicitly as an interpreter implementation detail).

__name__ is set torun_name if this optional argument is notNone and to'<run_path>' otherwise.

__file__ is set to the name provided by the module loader. If theloader does not make filename information available, this variable is settoNone. For a simple script, this will be set tofile_path.

__loader__ is set to thePEP 302 module loader used to retrieve thecode for the module (This loader may be a wrapper around the standardimport mechanism). For a simple script, this will be set toNone.

__package__ is set to__name__.rpartition('.')[0].

A number of alterations are also made to thesys 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, unlikerun_module(), the alterations made tosysare 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.

New in version 3.2.

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.

Command line and environment - CPython command line details

Theimportlib.import_module() function

Previous topic

30.4.modulefinder — Find modules used by a script

Next topic

30.6.importlib – The implementation ofimport

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp