blob: c98af19af4e3a88803bda80087f1d4613221b402 [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
Brett Cannon82d21072013-06-15 14:27:21 -040016import types
Nick Coghlan720c7e22013-12-15 20:33:02 +100017from pkgutil import read_code, get_importer
Thomas Woutersa9773292006-04-21 09:43:23 +000018
19__all__ = [
Nick Coghlan260bd3e2009-11-16 06:49:25 +000020 "run_module", "run_path",
Thomas Woutersa9773292006-04-21 09:43:23 +000021]
22
Nick Coghlan260bd3e2009-11-16 06:49:25 +000023class _TempModule(object):
24 """Temporarily replace a module in sys.modules with an empty namespace"""
25 def __init__(self, mod_name):
26 self.mod_name = mod_name
Brett Cannon82d21072013-06-15 14:27:21 -040027 self.module = types.ModuleType(mod_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000028 self._saved_module = []
29
30 def __enter__(self):
31 mod_name = self.mod_name
32 try:
33 self._saved_module.append(sys.modules[mod_name])
34 except KeyError:
35 pass
36 sys.modules[mod_name] = self.module
37 return self
38
39 def __exit__(self, *args):
40 if self._saved_module:
41 sys.modules[self.mod_name] = self._saved_module[0]
42 else:
43 del sys.modules[self.mod_name]
44 self._saved_module = []
45
46class _ModifiedArgv0(object):
47 def __init__(self, value):
48 self.value = value
49 self._saved_value = self._sentinel = object()
50
51 def __enter__(self):
52 if self._saved_value is not self._sentinel:
53 raise RuntimeError("Already preserving saved value")
54 self._saved_value = sys.argv[0]
55 sys.argv[0] = self.value
56
57 def __exit__(self, *args):
58 self.value = self._sentinel
59 sys.argv[0] = self._saved_value
Thomas Woutersa9773292006-04-21 09:43:23 +000060
Eric Snow32439d62015-05-02 19:15:18 -060061# TODO: Replace these helpers with importlib._bootstrap_external functions.
Thomas Woutersed03b412007-08-28 21:37:11 +000062def _run_code(code, run_globals, init_globals=None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100063 mod_name=None, mod_spec=None,
64 pkg_name=None, script_name=None):
Benjamin Petersonf6489f92009-11-25 17:46:26 +000065 """Helper to run code in nominated namespace"""
Thomas Woutersa9773292006-04-21 09:43:23 +000066 if init_globals is not None:
67 run_globals.update(init_globals)
Nick Coghlan720c7e22013-12-15 20:33:02 +100068 if mod_spec is None:
69 loader = None
70 fname = script_name
71 cached = None
72 else:
73 loader = mod_spec.loader
74 fname = mod_spec.origin
75 cached = mod_spec.cached
76 if pkg_name is None:
77 pkg_name = mod_spec.parent
Thomas Woutersa9773292006-04-21 09:43:23 +000078 run_globals.update(__name__ = mod_name,
Nick Coghlan720c7e22013-12-15 20:33:02 +100079 __file__ = fname,
80 __cached__ = cached,
Nick Coghlan761bb112012-07-14 23:59:22 +100081 __doc__ = None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100082 __loader__ = loader,
83 __package__ = pkg_name,
84 __spec__ = mod_spec)
Georg Brandl7cae87c2006-09-06 06:51:57 +000085 exec(code, run_globals)
Thomas Woutersa9773292006-04-21 09:43:23 +000086 return run_globals
87
88def _run_module_code(code, init_globals=None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100089 mod_name=None, mod_spec=None,
90 pkg_name=None, script_name=None):
Benjamin Petersonf6489f92009-11-25 17:46:26 +000091 """Helper to run code in new namespace with sys modified"""
Nick Coghlan720c7e22013-12-15 20:33:02 +100092 fname = script_name if mod_spec is None else mod_spec.origin
93 with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname):
Nick Coghlan260bd3e2009-11-16 06:49:25 +000094 mod_globals = temp_module.module.__dict__
Thomas Woutersed03b412007-08-28 21:37:11 +000095 _run_code(code, mod_globals, init_globals,
Nick Coghlan720c7e22013-12-15 20:33:02 +100096 mod_name, mod_spec, pkg_name, script_name)
Thomas Woutersed03b412007-08-28 21:37:11 +000097 # Copy the globals of the temporary module, as they
98 # may be cleared when the temporary module goes away
99 return mod_globals.copy()
Thomas Woutersa9773292006-04-21 09:43:23 +0000100
Eric Snow6029e082014-01-25 15:32:46 -0700101# Helper to get the loader, code and filename for a module
Martin Panter657257e2015-12-03 01:23:10 +0000102def _get_module_details(mod_name, error=ImportError):
Martin Panter7dda4212015-12-10 06:47:06 +0000103 if mod_name.startswith("."):
104 raise error("Relative module names not supported")
105 pkg_name, _, _ = mod_name.rpartition(".")
106 if pkg_name:
107 # Try importing the parent to avoid catching initialization errors
108 try:
109 __import__(pkg_name)
110 except ImportError as e:
111 # If the parent or higher ancestor package is missing, let the
112 # error be raised by find_spec() below and then be caught. But do
113 # not allow other errors to be caught.
114 if e.name is None or (e.name != pkg_name and
115 not pkg_name.startswith(e.name + ".")):
116 raise
117
Nick Coghlan720c7e22013-12-15 20:33:02 +1000118 try:
Eric Snow6029e082014-01-25 15:32:46 -0700119 spec = importlib.util.find_spec(mod_name)
Nick Coghlan720c7e22013-12-15 20:33:02 +1000120 except (ImportError, AttributeError, TypeError, ValueError) as ex:
121 # This hack fixes an impedance mismatch between pkgutil and
122 # importlib, where the latter raises other errors for cases where
123 # pkgutil previously raised ImportError
124 msg = "Error while finding spec for {!r} ({}: {})"
Martin Panter7dda4212015-12-10 06:47:06 +0000125 raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex
Nick Coghlan720c7e22013-12-15 20:33:02 +1000126 if spec is None:
Martin Panter657257e2015-12-03 01:23:10 +0000127 raise error("No module named %s" % mod_name)
Nick Coghlan720c7e22013-12-15 20:33:02 +1000128 if spec.submodule_search_locations is not None:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000129 if mod_name == "__main__" or mod_name.endswith(".__main__"):
Martin Panter657257e2015-12-03 01:23:10 +0000130 raise error("Cannot use package as __main__ module")
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000131 try:
132 pkg_main_name = mod_name + ".__main__"
Martin Panter7dda4212015-12-10 06:47:06 +0000133 return _get_module_details(pkg_main_name, error)
134 except error as e:
Martin Panter657257e2015-12-03 01:23:10 +0000135 raise error(("%s; %r is a package and cannot " +
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000136 "be directly executed") %(e, mod_name))
Nick Coghlan720c7e22013-12-15 20:33:02 +1000137 loader = spec.loader
138 if loader is None:
Martin Panter657257e2015-12-03 01:23:10 +0000139 raise error("%r is a namespace package and cannot be executed"
Nick Coghlan720c7e22013-12-15 20:33:02 +1000140 % mod_name)
Martin Panter657257e2015-12-03 01:23:10 +0000141 try:
142 code = loader.get_code(mod_name)
143 except ImportError as e:
144 raise error(format(e)) from e
Thomas Woutersa9773292006-04-21 09:43:23 +0000145 if code is None:
Martin Panter657257e2015-12-03 01:23:10 +0000146 raise error("No code object available for %s" % mod_name)
Nick Coghlan720c7e22013-12-15 20:33:02 +1000147 return mod_name, spec, code
Thomas Woutersed03b412007-08-28 21:37:11 +0000148
Martin Panter657257e2015-12-03 01:23:10 +0000149class _Error(Exception):
150 """Error that _run_module_as_main() should report without a traceback"""
151
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000152# XXX ncoghlan: Should this be documented and made public?
153# (Current thoughts: don't repeat the mistake that lead to its
154# creation when run_module() no longer met the needs of
155# mainmodule.c, but couldn't be changed because it was public)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000156def _run_module_as_main(mod_name, alter_argv=True):
Thomas Woutersed03b412007-08-28 21:37:11 +0000157 """Runs the designated module in the __main__ namespace
158
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000159 Note that the executed module will have full access to the
160 __main__ namespace. If this is not desirable, the run_module()
R. David Murray445448c2009-12-20 17:28:31 +0000161 function should be used to run the module code in a fresh namespace.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000162
163 At the very least, these variables in __main__ will be overwritten:
164 __name__
Thomas Woutersed03b412007-08-28 21:37:11 +0000165 __file__
Barry Warsaw28a691b2010-04-17 00:19:56 +0000166 __cached__
Thomas Woutersed03b412007-08-28 21:37:11 +0000167 __loader__
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000168 __package__
Thomas Woutersed03b412007-08-28 21:37:11 +0000169 """
Christian Heimesc3f30c42008-02-22 16:37:40 +0000170 try:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000171 if alter_argv or mod_name != "__main__": # i.e. -m switch
Martin Panter657257e2015-12-03 01:23:10 +0000172 mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000173 else: # i.e. directory or zipfile execution
Martin Panter657257e2015-12-03 01:23:10 +0000174 mod_name, mod_spec, code = _get_main_module_details(_Error)
175 except _Error as exc:
176 msg = "%s: %s" % (sys.executable, exc)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000177 sys.exit(msg)
Thomas Woutersed03b412007-08-28 21:37:11 +0000178 main_globals = sys.modules["__main__"].__dict__
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000179 if alter_argv:
Nick Coghlan720c7e22013-12-15 20:33:02 +1000180 sys.argv[0] = mod_spec.origin
Thomas Woutersed03b412007-08-28 21:37:11 +0000181 return _run_code(code, main_globals, None,
Nick Coghlan720c7e22013-12-15 20:33:02 +1000182 "__main__", mod_spec)
Thomas Woutersed03b412007-08-28 21:37:11 +0000183
184def run_module(mod_name, init_globals=None,
185 run_name=None, alter_sys=False):
186 """Execute a module's code without importing it
187
188 Returns the resulting top level namespace dictionary
189 """
Nick Coghlan720c7e22013-12-15 20:33:02 +1000190 mod_name, mod_spec, code = _get_module_details(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000191 if run_name is None:
192 run_name = mod_name
Thomas Woutersed03b412007-08-28 21:37:11 +0000193 if alter_sys:
Nick Coghlan720c7e22013-12-15 20:33:02 +1000194 return _run_module_code(code, init_globals, run_name, mod_spec)
Thomas Woutersed03b412007-08-28 21:37:11 +0000195 else:
196 # Leave the sys module alone
Nick Coghlan720c7e22013-12-15 20:33:02 +1000197 return _run_code(code, {}, init_globals, run_name, mod_spec)
Thomas Woutersa9773292006-04-21 09:43:23 +0000198
Martin Panter657257e2015-12-03 01:23:10 +0000199def _get_main_module_details(error=ImportError):
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000200 # Helper that gives a nicer error message when attempting to
201 # execute a zipfile or directory by invoking __main__.py
Nick Coghlan85e729e2012-07-15 18:09:52 +1000202 # Also moves the standard __main__ out of the way so that the
203 # preexisting __loader__ entry doesn't cause issues
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000204 main_name = "__main__"
Nick Coghlan85e729e2012-07-15 18:09:52 +1000205 saved_main = sys.modules[main_name]
206 del sys.modules[main_name]
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000207 try:
208 return _get_module_details(main_name)
209 except ImportError as exc:
210 if main_name in str(exc):
Martin Panter657257e2015-12-03 01:23:10 +0000211 raise error("can't find %r module in %r" %
Nick Coghlan85e729e2012-07-15 18:09:52 +1000212 (main_name, sys.path[0])) from exc
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000213 raise
Nick Coghlan85e729e2012-07-15 18:09:52 +1000214 finally:
215 sys.modules[main_name] = saved_main
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000216
Thomas Woutersa9773292006-04-21 09:43:23 +0000217
Nick Coghlan85e729e2012-07-15 18:09:52 +1000218def _get_code_from_file(run_name, fname):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000219 # Check for a compiled file first
220 with open(fname, "rb") as f:
221 code = read_code(f)
222 if code is None:
223 # That didn't work, so try it as normal source code
Victor Stinner6c471022011-07-04 01:45:39 +0200224 with open(fname, "rb") as f:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000225 code = compile(f.read(), fname, 'exec')
Nick Coghlan720c7e22013-12-15 20:33:02 +1000226 return code, fname
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000227
228def run_path(path_name, init_globals=None, run_name=None):
229 """Execute code located at the specified filesystem location
230
231 Returns the resulting top level namespace dictionary
232
233 The file path may refer directly to a Python script (i.e.
234 one that could be directly executed with execfile) or else
235 it may refer to a zipfile or directory containing a top
236 level __main__.py script.
237 """
238 if run_name is None:
239 run_name = "<run_path>"
Nick Coghlan761bb112012-07-14 23:59:22 +1000240 pkg_name = run_name.rpartition(".")[0]
Nick Coghlan85e729e2012-07-15 18:09:52 +1000241 importer = get_importer(path_name)
Brett Cannone4f41de2013-06-16 13:13:40 -0400242 # Trying to avoid importing imp so as to not consume the deprecation warning.
243 is_NullImporter = False
244 if type(importer).__module__ == 'imp':
245 if type(importer).__name__ == 'NullImporter':
246 is_NullImporter = True
247 if isinstance(importer, type(None)) or is_NullImporter:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000248 # Not a valid sys.path entry, so run the code directly
249 # execfile() doesn't help as we want to allow compiled files
Nick Coghlan720c7e22013-12-15 20:33:02 +1000250 code, fname = _get_code_from_file(run_name, path_name)
251 return _run_module_code(code, init_globals, run_name,
252 pkg_name=pkg_name, script_name=fname)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000253 else:
254 # Importer is defined for path, so add it to
255 # the start of sys.path
256 sys.path.insert(0, path_name)
257 try:
258 # Here's where things are a little different from the run_module
259 # case. There, we only had to replace the module in sys while the
260 # code was running and doing so was somewhat optional. Here, we
261 # have no choice and we have to remove it even while we read the
262 # code. If we don't do this, a __loader__ attribute in the
263 # existing __main__ module may prevent location of the new module.
Nick Coghlan720c7e22013-12-15 20:33:02 +1000264 mod_name, mod_spec, code = _get_main_module_details()
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000265 with _TempModule(run_name) as temp_module, \
266 _ModifiedArgv0(path_name):
267 mod_globals = temp_module.module.__dict__
268 return _run_code(code, mod_globals, init_globals,
Nick Coghlan720c7e22013-12-15 20:33:02 +1000269 run_name, mod_spec, pkg_name).copy()
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000270 finally:
271 try:
272 sys.path.remove(path_name)
273 except ValueError:
274 pass
275
276
Thomas Woutersa9773292006-04-21 09:43:23 +0000277if __name__ == "__main__":
278 # Run the module specified as the next command line argument
279 if len(sys.argv) < 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000280 print("No module specified for execution", file=sys.stderr)
Thomas Woutersa9773292006-04-21 09:43:23 +0000281 else:
282 del sys.argv[0] # Make the requested module sys.argv[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000283 _run_module_as_main(sys.argv[0])