blob: 71c175fe653b1c96fa44b3895bdebefcd07b45a8 [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
15import imp
Nick Coghlan260bd3e2009-11-16 06:49:25 +000016from pkgutil import read_code
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000017try:
18 from imp import get_loader
19except ImportError:
20 from pkgutil import get_loader
Thomas Woutersa9773292006-04-21 09:43:23 +000021
22__all__ = [
Nick Coghlan260bd3e2009-11-16 06:49:25 +000023 "run_module", "run_path",
Thomas Woutersa9773292006-04-21 09:43:23 +000024]
25
Nick Coghlan260bd3e2009-11-16 06:49:25 +000026class _TempModule(object):
27 """Temporarily replace a module in sys.modules with an empty namespace"""
28 def __init__(self, mod_name):
29 self.mod_name = mod_name
30 self.module = imp.new_module(mod_name)
31 self._saved_module = []
32
33 def __enter__(self):
34 mod_name = self.mod_name
35 try:
36 self._saved_module.append(sys.modules[mod_name])
37 except KeyError:
38 pass
39 sys.modules[mod_name] = self.module
40 return self
41
42 def __exit__(self, *args):
43 if self._saved_module:
44 sys.modules[self.mod_name] = self._saved_module[0]
45 else:
46 del sys.modules[self.mod_name]
47 self._saved_module = []
48
49class _ModifiedArgv0(object):
50 def __init__(self, value):
51 self.value = value
52 self._saved_value = self._sentinel = object()
53
54 def __enter__(self):
55 if self._saved_value is not self._sentinel:
56 raise RuntimeError("Already preserving saved value")
57 self._saved_value = sys.argv[0]
58 sys.argv[0] = self.value
59
60 def __exit__(self, *args):
61 self.value = self._sentinel
62 sys.argv[0] = self._saved_value
Thomas Woutersa9773292006-04-21 09:43:23 +000063
Thomas Woutersed03b412007-08-28 21:37:11 +000064def _run_code(code, run_globals, init_globals=None,
65 mod_name=None, mod_fname=None,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000066 mod_loader=None, pkg_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)
70 run_globals.update(__name__ = mod_name,
71 __file__ = mod_fname,
Barry Warsaw28a691b2010-04-17 00:19:56 +000072 __cached__ = None,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000073 __loader__ = mod_loader,
74 __package__ = pkg_name)
Georg Brandl7cae87c2006-09-06 06:51:57 +000075 exec(code, run_globals)
Thomas Woutersa9773292006-04-21 09:43:23 +000076 return run_globals
77
78def _run_module_code(code, init_globals=None,
Thomas Woutersed03b412007-08-28 21:37:11 +000079 mod_name=None, mod_fname=None,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000080 mod_loader=None, pkg_name=None):
Benjamin Petersonf6489f92009-11-25 17:46:26 +000081 """Helper to run code in new namespace with sys modified"""
Nick Coghlan260bd3e2009-11-16 06:49:25 +000082 with _TempModule(mod_name) as temp_module, _ModifiedArgv0(mod_fname):
83 mod_globals = temp_module.module.__dict__
Thomas Woutersed03b412007-08-28 21:37:11 +000084 _run_code(code, mod_globals, init_globals,
Nick Coghlan260bd3e2009-11-16 06:49:25 +000085 mod_name, mod_fname, mod_loader, pkg_name)
Thomas Woutersed03b412007-08-28 21:37:11 +000086 # Copy the globals of the temporary module, as they
87 # may be cleared when the temporary module goes away
88 return mod_globals.copy()
Thomas Woutersa9773292006-04-21 09:43:23 +000089
90
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091# This helper is needed due to a missing component in the PEP 302
92# loader protocol (specifically, "get_filename" is non-standard)
Nick Coghlanf088e5e2008-12-14 11:50:48 +000093# Since we can't introduce new features in maintenance releases,
94# support was added to zipimporter under the name '_get_filename'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000095def _get_filename(loader, mod_name):
Nick Coghlanf088e5e2008-12-14 11:50:48 +000096 for attr in ("get_filename", "_get_filename"):
97 meth = getattr(loader, attr, None)
98 if meth is not None:
Brett Cannone0d88a12012-04-25 20:54:04 -040099 return os.path.abspath(meth(mod_name))
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000100 return None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000101
Thomas Woutersed03b412007-08-28 21:37:11 +0000102# Helper to get the loader, code and filename for a module
103def _get_module_details(mod_name):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000104 loader = get_loader(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000105 if loader is None:
Guido van Rossum806c2462007-08-06 23:33:07 +0000106 raise ImportError("No module named %s" % mod_name)
107 if loader.is_package(mod_name):
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000108 if mod_name == "__main__" or mod_name.endswith(".__main__"):
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000109 raise ImportError("Cannot use package as __main__ module")
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000110 try:
111 pkg_main_name = mod_name + ".__main__"
112 return _get_module_details(pkg_main_name)
113 except ImportError as e:
114 raise ImportError(("%s; %r is a package and cannot " +
115 "be directly executed") %(e, mod_name))
Thomas Woutersa9773292006-04-21 09:43:23 +0000116 code = loader.get_code(mod_name)
117 if code is None:
Guido van Rossum806c2462007-08-06 23:33:07 +0000118 raise ImportError("No code object available for %s" % mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000119 filename = _get_filename(loader, mod_name)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000120 return mod_name, loader, code, filename
Thomas Woutersed03b412007-08-28 21:37:11 +0000121
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000122# XXX ncoghlan: Should this be documented and made public?
123# (Current thoughts: don't repeat the mistake that lead to its
124# creation when run_module() no longer met the needs of
125# mainmodule.c, but couldn't be changed because it was public)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000126def _run_module_as_main(mod_name, alter_argv=True):
Thomas Woutersed03b412007-08-28 21:37:11 +0000127 """Runs the designated module in the __main__ namespace
128
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000129 Note that the executed module will have full access to the
130 __main__ namespace. If this is not desirable, the run_module()
R. David Murray445448c2009-12-20 17:28:31 +0000131 function should be used to run the module code in a fresh namespace.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000132
133 At the very least, these variables in __main__ will be overwritten:
134 __name__
Thomas Woutersed03b412007-08-28 21:37:11 +0000135 __file__
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136 __cached__
Thomas Woutersed03b412007-08-28 21:37:11 +0000137 __loader__
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000138 __package__
Thomas Woutersed03b412007-08-28 21:37:11 +0000139 """
Christian Heimesc3f30c42008-02-22 16:37:40 +0000140 try:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000141 if alter_argv or mod_name != "__main__": # i.e. -m switch
142 mod_name, loader, code, fname = _get_module_details(mod_name)
143 else: # i.e. directory or zipfile execution
144 mod_name, loader, code, fname = _get_main_module_details()
Christian Heimesc3f30c42008-02-22 16:37:40 +0000145 except ImportError as exc:
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000146 # Try to provide a good error message
147 # for directories, zip files and the -m switch
148 if alter_argv:
149 # For -m switch, just display the exception
150 info = str(exc)
151 else:
152 # For directories/zipfiles, let the user
153 # know what the code was looking for
Benjamin Petersone3607952009-11-25 18:38:11 +0000154 info = "can't find '__main__' module in %r" % sys.argv[0]
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000155 msg = "%s: %s" % (sys.executable, info)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000156 sys.exit(msg)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000157 pkg_name = mod_name.rpartition('.')[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000158 main_globals = sys.modules["__main__"].__dict__
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000159 if alter_argv:
Thomas Woutersed03b412007-08-28 21:37:11 +0000160 sys.argv[0] = fname
161 return _run_code(code, main_globals, None,
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000162 "__main__", fname, loader, pkg_name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000163
164def run_module(mod_name, init_globals=None,
165 run_name=None, alter_sys=False):
166 """Execute a module's code without importing it
167
168 Returns the resulting top level namespace dictionary
169 """
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000170 mod_name, loader, code, fname = _get_module_details(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000171 if run_name is None:
172 run_name = mod_name
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000173 pkg_name = mod_name.rpartition('.')[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000174 if alter_sys:
175 return _run_module_code(code, init_globals, run_name,
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000176 fname, loader, pkg_name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000177 else:
178 # Leave the sys module alone
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000179 return _run_code(code, {}, init_globals, run_name,
180 fname, loader, pkg_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000181
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000182def _get_main_module_details():
183 # Helper that gives a nicer error message when attempting to
184 # execute a zipfile or directory by invoking __main__.py
185 main_name = "__main__"
186 try:
187 return _get_module_details(main_name)
188 except ImportError as exc:
189 if main_name in str(exc):
190 raise ImportError("can't find %r module in %r" %
191 (main_name, sys.path[0]))
192 raise
193
Thomas Woutersa9773292006-04-21 09:43:23 +0000194
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000195# XXX (ncoghlan): Perhaps expose the C API function
196# as imp.get_importer instead of reimplementing it in Python?
197def _get_importer(path_name):
198 """Python version of PyImport_GetImporter C API function"""
199 cache = sys.path_importer_cache
200 try:
201 importer = cache[path_name]
202 except KeyError:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000203 for hook in sys.path_hooks:
204 try:
205 importer = hook(path_name)
206 break
207 except ImportError:
208 pass
209 else:
Brett Cannonaa936422012-04-27 15:30:58 -0400210 importer = None
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000211 cache[path_name] = importer
212 return importer
213
214def _get_code_from_file(fname):
215 # Check for a compiled file first
216 with open(fname, "rb") as f:
217 code = read_code(f)
218 if code is None:
219 # That didn't work, so try it as normal source code
Victor Stinner6c471022011-07-04 01:45:39 +0200220 with open(fname, "rb") as f:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000221 code = compile(f.read(), fname, 'exec')
222 return code
223
224def run_path(path_name, init_globals=None, run_name=None):
225 """Execute code located at the specified filesystem location
226
227 Returns the resulting top level namespace dictionary
228
229 The file path may refer directly to a Python script (i.e.
230 one that could be directly executed with execfile) or else
231 it may refer to a zipfile or directory containing a top
232 level __main__.py script.
233 """
234 if run_name is None:
235 run_name = "<run_path>"
236 importer = _get_importer(path_name)
Brett Cannonaa936422012-04-27 15:30:58 -0400237 if isinstance(importer, (type(None), imp.NullImporter)):
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000238 # Not a valid sys.path entry, so run the code directly
239 # execfile() doesn't help as we want to allow compiled files
240 code = _get_code_from_file(path_name)
241 return _run_module_code(code, init_globals, run_name, path_name)
242 else:
243 # Importer is defined for path, so add it to
244 # the start of sys.path
245 sys.path.insert(0, path_name)
246 try:
247 # Here's where things are a little different from the run_module
248 # case. There, we only had to replace the module in sys while the
249 # code was running and doing so was somewhat optional. Here, we
250 # have no choice and we have to remove it even while we read the
251 # code. If we don't do this, a __loader__ attribute in the
252 # existing __main__ module may prevent location of the new module.
253 main_name = "__main__"
254 saved_main = sys.modules[main_name]
255 del sys.modules[main_name]
256 try:
257 mod_name, loader, code, fname = _get_main_module_details()
258 finally:
259 sys.modules[main_name] = saved_main
260 pkg_name = ""
261 with _TempModule(run_name) as temp_module, \
262 _ModifiedArgv0(path_name):
263 mod_globals = temp_module.module.__dict__
264 return _run_code(code, mod_globals, init_globals,
Benjamin Peterson01e39792010-10-13 01:04:36 +0000265 run_name, fname, loader, pkg_name).copy()
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000266 finally:
267 try:
268 sys.path.remove(path_name)
269 except ValueError:
270 pass
271
272
Thomas Woutersa9773292006-04-21 09:43:23 +0000273if __name__ == "__main__":
274 # Run the module specified as the next command line argument
275 if len(sys.argv) < 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000276 print("No module specified for execution", file=sys.stderr)
Thomas Woutersa9773292006-04-21 09:43:23 +0000277 else:
278 del sys.argv[0] # Make the requested module sys.argv[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000279 _run_module_as_main(sys.argv[0])