blob: 8adc91e32f319e734bc419d2a9299f767c4b9730 [file] [log] [blame]
Thomas Woutersa9773292006-04-21 09:43:23 +00001"""runpy.py - locating and running Python code using the module namespace
2
3Provides support for locating and running Python scripts using the Python
4module namespace instead of the native filesystem.
5
6This allows Python code to play nicely with non-filesystem based PEP 302
7importers when locating support scripts as well as when importing modules.
8"""
9# Written by Nick Coghlan <ncoghlan at gmail.com>
10# to implement PEP 338 (Executing Modules as Scripts)
11
Brett Cannonaa936422012-04-27 15:30:58 -040012
Thomas Woutersa9773292006-04-21 09:43:23 +000013import sys
Nick Coghlanbe7e49f2012-07-20 23:40:09 +100014import importlib.machinery # importlib first so we can test #15386 via -m
Eric Snow6029e082014-01-25 15:32:46 -070015import importlib.util
jsnkllne243bae2019-11-18 14:11:13 -050016import io
Brett Cannon82d21072013-06-15 14:27:21 -040017import types
Nick Coghlan720c7e22013-12-15 20:33:02 +100018from pkgutil import read_code, get_importer
Thomas Woutersa9773292006-04-21 09:43:23 +000019
20__all__ = [
Nick Coghlan260bd3e2009-11-16 06:49:25 +000021 "run_module", "run_path",
Thomas Woutersa9773292006-04-21 09:43:23 +000022]
23
Nick Coghlan260bd3e2009-11-16 06:49:25 +000024class _TempModule(object):
25 """Temporarily replace a module in sys.modules with an empty namespace"""
26 def __init__(self, mod_name):
27 self.mod_name = mod_name
Brett Cannon82d21072013-06-15 14:27:21 -040028 self.module = types.ModuleType(mod_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000029 self._saved_module = []
30
31 def __enter__(self):
32 mod_name = self.mod_name
33 try:
34 self._saved_module.append(sys.modules[mod_name])
35 except KeyError:
36 pass
37 sys.modules[mod_name] = self.module
38 return self
39
40 def __exit__(self, *args):
41 if self._saved_module:
42 sys.modules[self.mod_name] = self._saved_module[0]
43 else:
44 del sys.modules[self.mod_name]
45 self._saved_module = []
46
47class _ModifiedArgv0(object):
48 def __init__(self, value):
49 self.value = value
50 self._saved_value = self._sentinel = object()
51
52 def __enter__(self):
53 if self._saved_value is not self._sentinel:
54 raise RuntimeError("Already preserving saved value")
55 self._saved_value = sys.argv[0]
56 sys.argv[0] = self.value
57
58 def __exit__(self, *args):
59 self.value = self._sentinel
60 sys.argv[0] = self._saved_value
Thomas Woutersa9773292006-04-21 09:43:23 +000061
Eric Snow32439d62015-05-02 19:15:18 -060062# TODO: Replace these helpers with importlib._bootstrap_external functions.
Thomas Woutersed03b412007-08-28 21:37:11 +000063def _run_code(code, run_globals, init_globals=None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100064 mod_name=None, mod_spec=None,
65 pkg_name=None, script_name=None):
Benjamin Petersonf6489f92009-11-25 17:46:26 +000066 """Helper to run code in nominated namespace"""
Thomas Woutersa9773292006-04-21 09:43:23 +000067 if init_globals is not None:
68 run_globals.update(init_globals)
Nick Coghlan720c7e22013-12-15 20:33:02 +100069 if mod_spec is None:
70 loader = None
71 fname = script_name
72 cached = None
73 else:
74 loader = mod_spec.loader
75 fname = mod_spec.origin
76 cached = mod_spec.cached
77 if pkg_name is None:
78 pkg_name = mod_spec.parent
Thomas Woutersa9773292006-04-21 09:43:23 +000079 run_globals.update(__name__ = mod_name,
Nick Coghlan720c7e22013-12-15 20:33:02 +100080 __file__ = fname,
81 __cached__ = cached,
Nick Coghlan761bb112012-07-14 23:59:22 +100082 __doc__ = None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100083 __loader__ = loader,
84 __package__ = pkg_name,
85 __spec__ = mod_spec)
Georg Brandl7cae87c2006-09-06 06:51:57 +000086 exec(code, run_globals)
Thomas Woutersa9773292006-04-21 09:43:23 +000087 return run_globals
88
89def _run_module_code(code, init_globals=None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100090 mod_name=None, mod_spec=None,
91 pkg_name=None, script_name=None):
Benjamin Petersonf6489f92009-11-25 17:46:26 +000092 """Helper to run code in new namespace with sys modified"""
Nick Coghlan720c7e22013-12-15 20:33:02 +100093 fname = script_name if mod_spec is None else mod_spec.origin
94 with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname):
Nick Coghlan260bd3e2009-11-16 06:49:25 +000095 mod_globals = temp_module.module.__dict__
Thomas Woutersed03b412007-08-28 21:37:11 +000096 _run_code(code, mod_globals, init_globals,
Nick Coghlan720c7e22013-12-15 20:33:02 +100097 mod_name, mod_spec, pkg_name, script_name)
Thomas Woutersed03b412007-08-28 21:37:11 +000098 # Copy the globals of the temporary module, as they
99 # may be cleared when the temporary module goes away
100 return mod_globals.copy()
Thomas Woutersa9773292006-04-21 09:43:23 +0000101
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700102# Helper to get the full name, spec and code for a module
Martin Panter657257e2015-12-03 01:23:10 +0000103def _get_module_details(mod_name, error=ImportError):
Martin Panter7dda4212015-12-10 06:47:06 +0000104 if mod_name.startswith("."):
105 raise error("Relative module names not supported")
106 pkg_name, _, _ = mod_name.rpartition(".")
107 if pkg_name:
108 # Try importing the parent to avoid catching initialization errors
109 try:
110 __import__(pkg_name)
111 except ImportError as e:
112 # If the parent or higher ancestor package is missing, let the
113 # error be raised by find_spec() below and then be caught. But do
114 # not allow other errors to be caught.
115 if e.name is None or (e.name != pkg_name and
116 not pkg_name.startswith(e.name + ".")):
117 raise
Martin Panter9c8aa9b2016-08-21 04:07:58 +0000118 # Warn if the module has already been imported under its normal name
119 existing = sys.modules.get(mod_name)
120 if existing is not None and not hasattr(existing, "__path__"):
121 from warnings import warn
122 msg = "{mod_name!r} found in sys.modules after import of " \
123 "package {pkg_name!r}, but prior to execution of " \
124 "{mod_name!r}; this may result in unpredictable " \
125 "behaviour".format(mod_name=mod_name, pkg_name=pkg_name)
126 warn(RuntimeWarning(msg))
Martin Panter7dda4212015-12-10 06:47:06 +0000127
Nick Coghlan720c7e22013-12-15 20:33:02 +1000128 try:
Eric Snow6029e082014-01-25 15:32:46 -0700129 spec = importlib.util.find_spec(mod_name)
Nick Coghlan720c7e22013-12-15 20:33:02 +1000130 except (ImportError, AttributeError, TypeError, ValueError) as ex:
131 # This hack fixes an impedance mismatch between pkgutil and
132 # importlib, where the latter raises other errors for cases where
133 # pkgutil previously raised ImportError
Martin Panter9c8aa9b2016-08-21 04:07:58 +0000134 msg = "Error while finding module specification for {!r} ({}: {})"
Martin Panter7dda4212015-12-10 06:47:06 +0000135 raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex
Nick Coghlan720c7e22013-12-15 20:33:02 +1000136 if spec is None:
Martin Panter657257e2015-12-03 01:23:10 +0000137 raise error("No module named %s" % mod_name)
Nick Coghlan720c7e22013-12-15 20:33:02 +1000138 if spec.submodule_search_locations is not None:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000139 if mod_name == "__main__" or mod_name.endswith(".__main__"):
Martin Panter657257e2015-12-03 01:23:10 +0000140 raise error("Cannot use package as __main__ module")
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000141 try:
142 pkg_main_name = mod_name + ".__main__"
Martin Panter7dda4212015-12-10 06:47:06 +0000143 return _get_module_details(pkg_main_name, error)
144 except error as e:
Martin Panterdda58432015-12-12 06:58:55 +0000145 if mod_name not in sys.modules:
146 raise # No module loaded; being a package is irrelevant
Martin Panter657257e2015-12-03 01:23:10 +0000147 raise error(("%s; %r is a package and cannot " +
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000148 "be directly executed") %(e, mod_name))
Nick Coghlan720c7e22013-12-15 20:33:02 +1000149 loader = spec.loader
150 if loader is None:
Martin Panter657257e2015-12-03 01:23:10 +0000151 raise error("%r is a namespace package and cannot be executed"
Nick Coghlan720c7e22013-12-15 20:33:02 +1000152 % mod_name)
Martin Panter657257e2015-12-03 01:23:10 +0000153 try:
154 code = loader.get_code(mod_name)
155 except ImportError as e:
156 raise error(format(e)) from e
Thomas Woutersa9773292006-04-21 09:43:23 +0000157 if code is None:
Martin Panter657257e2015-12-03 01:23:10 +0000158 raise error("No code object available for %s" % mod_name)
Nick Coghlan720c7e22013-12-15 20:33:02 +1000159 return mod_name, spec, code
Thomas Woutersed03b412007-08-28 21:37:11 +0000160
Martin Panter657257e2015-12-03 01:23:10 +0000161class _Error(Exception):
162 """Error that _run_module_as_main() should report without a traceback"""
163
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000164# XXX ncoghlan: Should this be documented and made public?
165# (Current thoughts: don't repeat the mistake that lead to its
166# creation when run_module() no longer met the needs of
167# mainmodule.c, but couldn't be changed because it was public)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000168def _run_module_as_main(mod_name, alter_argv=True):
Thomas Woutersed03b412007-08-28 21:37:11 +0000169 """Runs the designated module in the __main__ namespace
170
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000171 Note that the executed module will have full access to the
172 __main__ namespace. If this is not desirable, the run_module()
R. David Murray445448c2009-12-20 17:28:31 +0000173 function should be used to run the module code in a fresh namespace.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000174
175 At the very least, these variables in __main__ will be overwritten:
176 __name__
Thomas Woutersed03b412007-08-28 21:37:11 +0000177 __file__
Barry Warsaw28a691b2010-04-17 00:19:56 +0000178 __cached__
Thomas Woutersed03b412007-08-28 21:37:11 +0000179 __loader__
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000180 __package__
Thomas Woutersed03b412007-08-28 21:37:11 +0000181 """
Christian Heimesc3f30c42008-02-22 16:37:40 +0000182 try:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000183 if alter_argv or mod_name != "__main__": # i.e. -m switch
Martin Panter657257e2015-12-03 01:23:10 +0000184 mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000185 else: # i.e. directory or zipfile execution
Martin Panter657257e2015-12-03 01:23:10 +0000186 mod_name, mod_spec, code = _get_main_module_details(_Error)
187 except _Error as exc:
188 msg = "%s: %s" % (sys.executable, exc)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000189 sys.exit(msg)
Thomas Woutersed03b412007-08-28 21:37:11 +0000190 main_globals = sys.modules["__main__"].__dict__
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000191 if alter_argv:
Nick Coghlan720c7e22013-12-15 20:33:02 +1000192 sys.argv[0] = mod_spec.origin
Thomas Woutersed03b412007-08-28 21:37:11 +0000193 return _run_code(code, main_globals, None,
Nick Coghlan720c7e22013-12-15 20:33:02 +1000194 "__main__", mod_spec)
Thomas Woutersed03b412007-08-28 21:37:11 +0000195
196def run_module(mod_name, init_globals=None,
197 run_name=None, alter_sys=False):
198 """Execute a module's code without importing it
199
200 Returns the resulting top level namespace dictionary
201 """
Nick Coghlan720c7e22013-12-15 20:33:02 +1000202 mod_name, mod_spec, code = _get_module_details(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000203 if run_name is None:
204 run_name = mod_name
Thomas Woutersed03b412007-08-28 21:37:11 +0000205 if alter_sys:
Nick Coghlan720c7e22013-12-15 20:33:02 +1000206 return _run_module_code(code, init_globals, run_name, mod_spec)
Thomas Woutersed03b412007-08-28 21:37:11 +0000207 else:
208 # Leave the sys module alone
Nick Coghlan720c7e22013-12-15 20:33:02 +1000209 return _run_code(code, {}, init_globals, run_name, mod_spec)
Thomas Woutersa9773292006-04-21 09:43:23 +0000210
Martin Panter657257e2015-12-03 01:23:10 +0000211def _get_main_module_details(error=ImportError):
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000212 # Helper that gives a nicer error message when attempting to
213 # execute a zipfile or directory by invoking __main__.py
Nick Coghlan85e729e2012-07-15 18:09:52 +1000214 # Also moves the standard __main__ out of the way so that the
215 # preexisting __loader__ entry doesn't cause issues
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000216 main_name = "__main__"
Nick Coghlan85e729e2012-07-15 18:09:52 +1000217 saved_main = sys.modules[main_name]
218 del sys.modules[main_name]
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000219 try:
220 return _get_module_details(main_name)
221 except ImportError as exc:
222 if main_name in str(exc):
Martin Panter657257e2015-12-03 01:23:10 +0000223 raise error("can't find %r module in %r" %
Nick Coghlan85e729e2012-07-15 18:09:52 +1000224 (main_name, sys.path[0])) from exc
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000225 raise
Nick Coghlan85e729e2012-07-15 18:09:52 +1000226 finally:
227 sys.modules[main_name] = saved_main
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000228
Thomas Woutersa9773292006-04-21 09:43:23 +0000229
Nick Coghlan85e729e2012-07-15 18:09:52 +1000230def _get_code_from_file(run_name, fname):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000231 # Check for a compiled file first
jsnkllne243bae2019-11-18 14:11:13 -0500232 with io.open_code(fname) as f:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000233 code = read_code(f)
234 if code is None:
235 # That didn't work, so try it as normal source code
jsnkllne243bae2019-11-18 14:11:13 -0500236 with io.open_code(fname) as f:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000237 code = compile(f.read(), fname, 'exec')
Nick Coghlan720c7e22013-12-15 20:33:02 +1000238 return code, fname
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000239
240def run_path(path_name, init_globals=None, run_name=None):
241 """Execute code located at the specified filesystem location
242
243 Returns the resulting top level namespace dictionary
244
245 The file path may refer directly to a Python script (i.e.
246 one that could be directly executed with execfile) or else
247 it may refer to a zipfile or directory containing a top
248 level __main__.py script.
249 """
250 if run_name is None:
251 run_name = "<run_path>"
Nick Coghlan761bb112012-07-14 23:59:22 +1000252 pkg_name = run_name.rpartition(".")[0]
Nick Coghlan85e729e2012-07-15 18:09:52 +1000253 importer = get_importer(path_name)
Brett Cannone4f41de2013-06-16 13:13:40 -0400254 # Trying to avoid importing imp so as to not consume the deprecation warning.
255 is_NullImporter = False
256 if type(importer).__module__ == 'imp':
257 if type(importer).__name__ == 'NullImporter':
258 is_NullImporter = True
259 if isinstance(importer, type(None)) or is_NullImporter:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000260 # Not a valid sys.path entry, so run the code directly
261 # execfile() doesn't help as we want to allow compiled files
Nick Coghlan720c7e22013-12-15 20:33:02 +1000262 code, fname = _get_code_from_file(run_name, path_name)
263 return _run_module_code(code, init_globals, run_name,
264 pkg_name=pkg_name, script_name=fname)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000265 else:
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700266 # Finder is defined for path, so add it to
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000267 # the start of sys.path
268 sys.path.insert(0, path_name)
269 try:
270 # Here's where things are a little different from the run_module
271 # case. There, we only had to replace the module in sys while the
272 # code was running and doing so was somewhat optional. Here, we
273 # have no choice and we have to remove it even while we read the
274 # code. If we don't do this, a __loader__ attribute in the
275 # existing __main__ module may prevent location of the new module.
Nick Coghlan720c7e22013-12-15 20:33:02 +1000276 mod_name, mod_spec, code = _get_main_module_details()
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000277 with _TempModule(run_name) as temp_module, \
278 _ModifiedArgv0(path_name):
279 mod_globals = temp_module.module.__dict__
280 return _run_code(code, mod_globals, init_globals,
Nick Coghlan720c7e22013-12-15 20:33:02 +1000281 run_name, mod_spec, pkg_name).copy()
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000282 finally:
283 try:
284 sys.path.remove(path_name)
285 except ValueError:
286 pass
287
288
Thomas Woutersa9773292006-04-21 09:43:23 +0000289if __name__ == "__main__":
290 # Run the module specified as the next command line argument
291 if len(sys.argv) < 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000292 print("No module specified for execution", file=sys.stderr)
Thomas Woutersa9773292006-04-21 09:43:23 +0000293 else:
294 del sys.argv[0] # Make the requested module sys.argv[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000295 _run_module_as_main(sys.argv[0])