Debian Codegraph @

Doc/library/runpy.rst

raw
1 :mod:`!runpy` --- Locating and executing Python modules
2 =======================================================
3
4 .. module:: runpy
5 :synopsis: Locate and run Python modules without importing them first.
6
7 .. moduleauthor:: Nick Coghlan <[email protected]>
8
9 **Source code:** :source:`Lib/runpy.py`
10
11 --------------
12
13 The :mod:`!runpy` module is used to locate and run Python modules without
14 importing them first. Its main use is to implement the :option:`-m` command
15 line switch that allows scripts to be located using the Python module
16 namespace rather than the filesystem.
17
18 Note that this is *not* a sandbox module - all code is executed in the
19 current process, and any side effects (such as cached imports of other
20 modules) will remain in place after the functions have returned.
21
22 Furthermore, any functions and classes defined by the executed code are not
23 guaranteed to work correctly after a :mod:`!runpy` function has returned.
24 If that limitation is not acceptable for a given use case, :mod:`importlib`
25 is likely to be a more suitable choice than this module.
26
27 The :mod:`!runpy` module provides two functions:
28
29
30 .. function:: run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)
31
32 .. index::
33 pair: module; __main__
34
35 Execute the code of the specified module and return the resulting module's
36 globals dictionary. The module's code is first located using the standard
37 import mechanism (refer to :pep:`302` for details) and then executed in a
38 fresh module namespace.
39
40 The *mod_name* argument should be an absolute module name.
41 If the module name refers to a package rather than a normal
42 module, then that package is imported and the :mod:`__main__` submodule within
43 that package is then executed and the resulting module globals dictionary
44 returned.
45
46 The optional dictionary argument *init_globals* may be used to pre-populate
47 the module's globals dictionary before the code is executed.
48 *init_globals* will not be modified. If any of the special global variables
49 below are defined in *init_globals*, those definitions are
50 overridden by :func:`run_module`.
51
52 The special global variables ``__name__``, ``__spec__``, ``__file__``,
53 ``__cached__``, ``__loader__`` and ``__package__`` are set in the globals
54 dictionary before the module code is executed. (Note that this is a
55 minimal set of variables - other variables may be set implicitly as an
56 interpreter implementation detail.)
57
58 ``__name__`` is set to *run_name* if this optional argument is not
59 :const:`None`, to ``mod_name + '.__main__'`` if the named module is a
60 package and to the *mod_name* argument otherwise.
61
62 ``__spec__`` will be set appropriately for the *actually* imported
63 module (that is, ``__spec__.name`` will always be *mod_name* or
64 ``mod_name + '.__main__'``, never *run_name*).
65
66 ``__file__``, ``__cached__``, ``__loader__`` and ``__package__`` are
67 :ref:`set as normal <import-mod-attrs>` based on the module spec.
68
69 If the argument *alter_sys* is supplied and evaluates to :const:`True`,
70 then ``sys.argv[0]`` is updated with the value of ``__file__`` and
71 ``sys.modules[__name__]`` is updated with a temporary module object for the
72 module being executed. Both ``sys.argv[0]`` and ``sys.modules[__name__]``
73 are restored to their original values before the function returns.
74
75 Note that this manipulation of :mod:`sys` is not thread-safe. Other threads
76 may see the partially initialised module, as well as the altered list of
77 arguments. It is recommended that the ``sys`` module be left alone when
78 invoking this function from threaded code.
79
80 .. seealso::
81 The :option:`-m` option offering equivalent functionality from the
82 command line.
83
84 .. versionchanged:: 3.1
85 Added ability to execute packages by looking for a :mod:`__main__` submodule.
86
87 .. versionchanged:: 3.2
88 Added ``__cached__`` global variable (see :pep:`3147`).
89
90 .. versionchanged:: 3.4
91 Updated to take advantage of the module spec feature added by
92 :pep:`451`. This allows ``__cached__`` to be set correctly for modules
93 run this way, as well as ensuring the real module name is always
94 accessible as ``__spec__.name``.
95
96 .. versionchanged:: 3.12
97 The setting of ``__cached__``, ``__loader__``, and
98 ``__package__`` are deprecated. See
99 :class:`~importlib.machinery.ModuleSpec` for alternatives.
100
101 .. function:: run_path(path_name, init_globals=None, run_name=None)
102
103 .. index::
104 pair: module; __main__
105
106 Execute the code at the named filesystem location and return the resulting
107 module's globals dictionary. As with a script name supplied to the CPython
108 command line, *file_path* may refer to a Python source file, a
109 compiled bytecode file or a valid :data:`sys.path` entry containing a
110 :mod:`__main__` module
111 (e.g. a zipfile containing a top-level :file:`__main__.py` file).
112
113 For a simple script, the specified code is simply executed in a fresh
114 module namespace. For a valid :data:`sys.path` entry (typically a zipfile or
115 directory), the entry is first added to the beginning of ``sys.path``. The
116 function then looks for and executes a :mod:`__main__` module using the
117 updated path. Note that there is no special protection against invoking
118 an existing ``__main__`` entry located elsewhere on ``sys.path`` if
119 there is no such module at the specified location.
120
121 The optional dictionary argument *init_globals* may be used to pre-populate
122 the module's globals dictionary before the code is executed.
123 *init_globals* will not be modified. If any of the special global variables
124 below are defined in *init_globals*, those definitions are
125 overridden by :func:`run_path`.
126
127 The special global variables ``__name__``, ``__spec__``, ``__file__``,
128 ``__cached__``, ``__loader__`` and ``__package__`` are set in the globals
129 dictionary before the module code is executed. (Note that this is a
130 minimal set of variables - other variables may be set implicitly as an
131 interpreter implementation detail.)
132
133 ``__name__`` is set to *run_name* if this optional argument is not
134 :const:`None` and to ``'<run_path>'`` otherwise.
135
136 If *file_path* directly references a script file (whether as source
137 or as precompiled byte code), then ``__file__`` will be set to
138 *file_path*, and ``__spec__``, ``__cached__``, ``__loader__`` and
139 ``__package__`` will all be set to :const:`None`.
140
141 If *file_path* is a reference to a valid :data:`sys.path` entry, then
142 ``__spec__`` will be set appropriately for the imported :mod:`__main__`
143 module (that is, ``__spec__.name`` will always be ``__main__``).
144 ``__file__``, ``__cached__``, ``__loader__`` and ``__package__`` will be
145 :ref:`set as normal <import-mod-attrs>` based on the module spec.
146
147 A number of alterations are also made to the :mod:`sys` module. Firstly,
148 :data:`sys.path` may be altered as described above. ``sys.argv[0]`` is updated
149 with the value of *file_path* and ``sys.modules[__name__]`` is updated
150 with a temporary module object for the module being executed. All
151 modifications to items in :mod:`sys` are reverted before the function
152 returns.
153
154 Note that, unlike :func:`run_module`, the alterations made to :mod:`sys`
155 are not optional in this function as these adjustments are essential to
156 allowing the execution of :data:`sys.path` entries. As the thread-safety
157 limitations still apply, use of this function in threaded code should be
158 either serialised with the import lock or delegated to a separate process.
159
160 .. seealso::
161 :ref:`using-on-interface-options` for equivalent functionality on the
162 command line (``python path/to/script``).
163
164 .. versionadded:: 3.2
165
166 .. versionchanged:: 3.4
167 Updated to take advantage of the module spec feature added by
168 :pep:`451`. This allows ``__cached__`` to be set correctly in the
169 case where ``__main__`` is imported from a valid :data:`sys.path` entry rather
170 than being executed directly.
171
172 .. versionchanged:: 3.12
173 The setting of ``__cached__``, ``__loader__``, and
174 ``__package__`` are deprecated.
175
176 .. seealso::
177
178 :pep:`338` -- Executing modules as scripts
179 PEP written and implemented by Nick Coghlan.
180
181 :pep:`366` -- Main module explicit relative imports
182 PEP written and implemented by Nick Coghlan.
183
184 :pep:`451` -- A ModuleSpec Type for the Import System
185 PEP written and implemented by Eric Snow
186
187 :ref:`using-on-general` - CPython command line details
188
189 The :func:`importlib.import_module` function