blob: dc08f4eae921938ca69bcab8a392ba3d08dadeec [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
Brett Cannone0d88a12012-04-25 20:54:04 -040013import os
Thomas Woutersa9773292006-04-21 09:43:23 +000014import sys
Nick Coghlanbe7e49f2012-07-20 23:40:09 +100015import importlib.machinery # importlib first so we can test #15386 via -m
Brett Cannon82d21072013-06-15 14:27:21 -040016import types
Nick Coghlan720c7e22013-12-15 20:33:02 +100017from importlib import find_spec
18from importlib.util import spec_from_loader
19from pkgutil import read_code, get_importer
Thomas Woutersa9773292006-04-21 09:43:23 +000020
21__all__ = [
Nick Coghlan260bd3e2009-11-16 06:49:25 +000022 "run_module", "run_path",
Thomas Woutersa9773292006-04-21 09:43:23 +000023]
24
Nick Coghlan260bd3e2009-11-16 06:49:25 +000025class _TempModule(object):
26 """Temporarily replace a module in sys.modules with an empty namespace"""
27 def __init__(self, mod_name):
28 self.mod_name = mod_name
Brett Cannon82d21072013-06-15 14:27:21 -040029 self.module = types.ModuleType(mod_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +000030 self._saved_module = []
31
32 def __enter__(self):
33 mod_name = self.mod_name
34 try:
35 self._saved_module.append(sys.modules[mod_name])
36 except KeyError:
37 pass
38 sys.modules[mod_name] = self.module
39 return self
40
41 def __exit__(self, *args):
42 if self._saved_module:
43 sys.modules[self.mod_name] = self._saved_module[0]
44 else:
45 del sys.modules[self.mod_name]
46 self._saved_module = []
47
48class _ModifiedArgv0(object):
49 def __init__(self, value):
50 self.value = value
51 self._saved_value = self._sentinel = object()
52
53 def __enter__(self):
54 if self._saved_value is not self._sentinel:
55 raise RuntimeError("Already preserving saved value")
56 self._saved_value = sys.argv[0]
57 sys.argv[0] = self.value
58
59 def __exit__(self, *args):
60 self.value = self._sentinel
61 sys.argv[0] = self._saved_value
Thomas Woutersa9773292006-04-21 09:43:23 +000062
Nick Coghlan720c7e22013-12-15 20:33:02 +100063# TODO: Replace these helpers with importlib._bootstrap._SpecMethods
Thomas Woutersed03b412007-08-28 21:37:11 +000064def _run_code(code, run_globals, init_globals=None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100065 mod_name=None, mod_spec=None,
66 pkg_name=None, script_name=None):
Benjamin Petersonf6489f92009-11-25 17:46:26 +000067 """Helper to run code in nominated namespace"""
Thomas Woutersa9773292006-04-21 09:43:23 +000068 if init_globals is not None:
69 run_globals.update(init_globals)
Nick Coghlan720c7e22013-12-15 20:33:02 +100070 if mod_spec is None:
71 loader = None
72 fname = script_name
73 cached = None
74 else:
75 loader = mod_spec.loader
76 fname = mod_spec.origin
77 cached = mod_spec.cached
78 if pkg_name is None:
79 pkg_name = mod_spec.parent
Thomas Woutersa9773292006-04-21 09:43:23 +000080 run_globals.update(__name__ = mod_name,
Nick Coghlan720c7e22013-12-15 20:33:02 +100081 __file__ = fname,
82 __cached__ = cached,
Nick Coghlan761bb112012-07-14 23:59:22 +100083 __doc__ = None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100084 __loader__ = loader,
85 __package__ = pkg_name,
86 __spec__ = mod_spec)
Georg Brandl7cae87c2006-09-06 06:51:57 +000087 exec(code, run_globals)
Thomas Woutersa9773292006-04-21 09:43:23 +000088 return run_globals
89
90def _run_module_code(code, init_globals=None,
Nick Coghlan720c7e22013-12-15 20:33:02 +100091 mod_name=None, mod_spec=None,
92 pkg_name=None, script_name=None):
Benjamin Petersonf6489f92009-11-25 17:46:26 +000093 """Helper to run code in new namespace with sys modified"""
Nick Coghlan720c7e22013-12-15 20:33:02 +100094 fname = script_name if mod_spec is None else mod_spec.origin
95 with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname):
Nick Coghlan260bd3e2009-11-16 06:49:25 +000096 mod_globals = temp_module.module.__dict__
Thomas Woutersed03b412007-08-28 21:37:11 +000097 _run_code(code, mod_globals, init_globals,
Nick Coghlan720c7e22013-12-15 20:33:02 +100098 mod_name, mod_spec, pkg_name, script_name)
Thomas Woutersed03b412007-08-28 21:37:11 +000099 # Copy the globals of the temporary module, as they
100 # may be cleared when the temporary module goes away
101 return mod_globals.copy()
Thomas Woutersa9773292006-04-21 09:43:23 +0000102
103
Nick Coghlan720c7e22013-12-15 20:33:02 +1000104def _fixed_find_spec(mod_name):
105 # find_spec has the same annoying behaviour as find_loader did (it
106 # fails to work properly for dotted names), so this is a fixed version
107 # ala pkgutil.get_loader
108 if mod_name.startswith('.'):
109 msg = "Relative module name {!r} not supported".format(mod_name)
110 raise ImportError(msg)
111 path = None
112 pkg_name = mod_name.rpartition(".")[0]
113 if pkg_name:
114 pkg = importlib.import_module(pkg_name)
115 path = getattr(pkg, "__path__", None)
116 if path is None:
117 return None
118 try:
119 return importlib.find_spec(mod_name, path)
120 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} ({}: {})"
125 raise ImportError(msg.format(mod_name, type(ex), ex)) from ex
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000126
Thomas Woutersed03b412007-08-28 21:37:11 +0000127# Helper to get the loader, code and filename for a module
128def _get_module_details(mod_name):
Nick Coghlan720c7e22013-12-15 20:33:02 +1000129 spec = _fixed_find_spec(mod_name)
130 if spec is None:
Guido van Rossum806c2462007-08-06 23:33:07 +0000131 raise ImportError("No module named %s" % mod_name)
Nick Coghlan720c7e22013-12-15 20:33:02 +1000132 if spec.submodule_search_locations is not None:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000133 if mod_name == "__main__" or mod_name.endswith(".__main__"):
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000134 raise ImportError("Cannot use package as __main__ module")
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000135 try:
136 pkg_main_name = mod_name + ".__main__"
137 return _get_module_details(pkg_main_name)
138 except ImportError as e:
139 raise ImportError(("%s; %r is a package and cannot " +
140 "be directly executed") %(e, mod_name))
Nick Coghlan720c7e22013-12-15 20:33:02 +1000141 loader = spec.loader
142 if loader is None:
143 raise ImportError("%r is a namespace package and cannot be executed"
144 % mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000145 code = loader.get_code(mod_name)
146 if code is None:
Guido van Rossum806c2462007-08-06 23:33:07 +0000147 raise ImportError("No code object available for %s" % mod_name)
Nick Coghlan720c7e22013-12-15 20:33:02 +1000148 return mod_name, spec, code
Thomas Woutersed03b412007-08-28 21:37:11 +0000149
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000150# XXX ncoghlan: Should this be documented and made public?
151# (Current thoughts: don't repeat the mistake that lead to its
152# creation when run_module() no longer met the needs of
153# mainmodule.c, but couldn't be changed because it was public)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000154def _run_module_as_main(mod_name, alter_argv=True):
Thomas Woutersed03b412007-08-28 21:37:11 +0000155 """Runs the designated module in the __main__ namespace
156
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000157 Note that the executed module will have full access to the
158 __main__ namespace. If this is not desirable, the run_module()
R. David Murray445448c2009-12-20 17:28:31 +0000159 function should be used to run the module code in a fresh namespace.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000160
161 At the very least, these variables in __main__ will be overwritten:
162 __name__
Thomas Woutersed03b412007-08-28 21:37:11 +0000163 __file__
Barry Warsaw28a691b2010-04-17 00:19:56 +0000164 __cached__
Thomas Woutersed03b412007-08-28 21:37:11 +0000165 __loader__
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000166 __package__
Thomas Woutersed03b412007-08-28 21:37:11 +0000167 """
Christian Heimesc3f30c42008-02-22 16:37:40 +0000168 try:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000169 if alter_argv or mod_name != "__main__": # i.e. -m switch
Nick Coghlan720c7e22013-12-15 20:33:02 +1000170 mod_name, mod_spec, code = _get_module_details(mod_name)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000171 else: # i.e. directory or zipfile execution
Nick Coghlan720c7e22013-12-15 20:33:02 +1000172 mod_name, mod_spec, code = _get_main_module_details()
Christian Heimesc3f30c42008-02-22 16:37:40 +0000173 except ImportError as exc:
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000174 # Try to provide a good error message
175 # for directories, zip files and the -m switch
176 if alter_argv:
177 # For -m switch, just display the exception
178 info = str(exc)
179 else:
180 # For directories/zipfiles, let the user
181 # know what the code was looking for
Benjamin Petersone3607952009-11-25 18:38:11 +0000182 info = "can't find '__main__' module in %r" % sys.argv[0]
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000183 msg = "%s: %s" % (sys.executable, info)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000184 sys.exit(msg)
Thomas Woutersed03b412007-08-28 21:37:11 +0000185 main_globals = sys.modules["__main__"].__dict__
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000186 if alter_argv:
Nick Coghlan720c7e22013-12-15 20:33:02 +1000187 sys.argv[0] = mod_spec.origin
Thomas Woutersed03b412007-08-28 21:37:11 +0000188 return _run_code(code, main_globals, None,
Nick Coghlan720c7e22013-12-15 20:33:02 +1000189 "__main__", mod_spec)
Thomas Woutersed03b412007-08-28 21:37:11 +0000190
191def run_module(mod_name, init_globals=None,
192 run_name=None, alter_sys=False):
193 """Execute a module's code without importing it
194
195 Returns the resulting top level namespace dictionary
196 """
Nick Coghlan720c7e22013-12-15 20:33:02 +1000197 mod_name, mod_spec, code = _get_module_details(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000198 if run_name is None:
199 run_name = mod_name
Thomas Woutersed03b412007-08-28 21:37:11 +0000200 if alter_sys:
Nick Coghlan720c7e22013-12-15 20:33:02 +1000201 return _run_module_code(code, init_globals, run_name, mod_spec)
Thomas Woutersed03b412007-08-28 21:37:11 +0000202 else:
203 # Leave the sys module alone
Nick Coghlan720c7e22013-12-15 20:33:02 +1000204 return _run_code(code, {}, init_globals, run_name, mod_spec)
Thomas Woutersa9773292006-04-21 09:43:23 +0000205
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000206def _get_main_module_details():
207 # Helper that gives a nicer error message when attempting to
208 # execute a zipfile or directory by invoking __main__.py
Nick Coghlan85e729e2012-07-15 18:09:52 +1000209 # Also moves the standard __main__ out of the way so that the
210 # preexisting __loader__ entry doesn't cause issues
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000211 main_name = "__main__"
Nick Coghlan85e729e2012-07-15 18:09:52 +1000212 saved_main = sys.modules[main_name]
213 del sys.modules[main_name]
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000214 try:
215 return _get_module_details(main_name)
216 except ImportError as exc:
217 if main_name in str(exc):
218 raise ImportError("can't find %r module in %r" %
Nick Coghlan85e729e2012-07-15 18:09:52 +1000219 (main_name, sys.path[0])) from exc
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000220 raise
Nick Coghlan85e729e2012-07-15 18:09:52 +1000221 finally:
222 sys.modules[main_name] = saved_main
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000223
Thomas Woutersa9773292006-04-21 09:43:23 +0000224
Nick Coghlan85e729e2012-07-15 18:09:52 +1000225def _get_code_from_file(run_name, fname):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000226 # Check for a compiled file first
227 with open(fname, "rb") as f:
228 code = read_code(f)
229 if code is None:
230 # That didn't work, so try it as normal source code
Victor Stinner6c471022011-07-04 01:45:39 +0200231 with open(fname, "rb") as f:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000232 code = compile(f.read(), fname, 'exec')
Nick Coghlan720c7e22013-12-15 20:33:02 +1000233 return code, fname
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000234
235def run_path(path_name, init_globals=None, run_name=None):
236 """Execute code located at the specified filesystem location
237
238 Returns the resulting top level namespace dictionary
239
240 The file path may refer directly to a Python script (i.e.
241 one that could be directly executed with execfile) or else
242 it may refer to a zipfile or directory containing a top
243 level __main__.py script.
244 """
245 if run_name is None:
246 run_name = "<run_path>"
Nick Coghlan761bb112012-07-14 23:59:22 +1000247 pkg_name = run_name.rpartition(".")[0]
Nick Coghlan85e729e2012-07-15 18:09:52 +1000248 importer = get_importer(path_name)
Brett Cannone4f41de2013-06-16 13:13:40 -0400249 # Trying to avoid importing imp so as to not consume the deprecation warning.
250 is_NullImporter = False
251 if type(importer).__module__ == 'imp':
252 if type(importer).__name__ == 'NullImporter':
253 is_NullImporter = True
254 if isinstance(importer, type(None)) or is_NullImporter:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000255 # Not a valid sys.path entry, so run the code directly
256 # execfile() doesn't help as we want to allow compiled files
Nick Coghlan720c7e22013-12-15 20:33:02 +1000257 code, fname = _get_code_from_file(run_name, path_name)
258 return _run_module_code(code, init_globals, run_name,
259 pkg_name=pkg_name, script_name=fname)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000260 else:
261 # Importer is defined for path, so add it to
262 # the start of sys.path
263 sys.path.insert(0, path_name)
264 try:
265 # Here's where things are a little different from the run_module
266 # case. There, we only had to replace the module in sys while the
267 # code was running and doing so was somewhat optional. Here, we
268 # have no choice and we have to remove it even while we read the
269 # code. If we don't do this, a __loader__ attribute in the
270 # existing __main__ module may prevent location of the new module.
Nick Coghlan720c7e22013-12-15 20:33:02 +1000271 mod_name, mod_spec, code = _get_main_module_details()
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000272 with _TempModule(run_name) as temp_module, \
273 _ModifiedArgv0(path_name):
274 mod_globals = temp_module.module.__dict__
275 return _run_code(code, mod_globals, init_globals,
Nick Coghlan720c7e22013-12-15 20:33:02 +1000276 run_name, mod_spec, pkg_name).copy()
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000277 finally:
278 try:
279 sys.path.remove(path_name)
280 except ValueError:
281 pass
282
283
Thomas Woutersa9773292006-04-21 09:43:23 +0000284if __name__ == "__main__":
285 # Run the module specified as the next command line argument
286 if len(sys.argv) < 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000287 print("No module specified for execution", file=sys.stderr)
Thomas Woutersa9773292006-04-21 09:43:23 +0000288 else:
289 del sys.argv[0] # Make the requested module sys.argv[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000290 _run_module_as_main(sys.argv[0])