blob: 22a29896d88d7450b2c1191a48692e2acb1ffe8c [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
12import sys
13import imp
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014try:
15 from imp import get_loader
16except ImportError:
17 from pkgutil import get_loader
Thomas Woutersa9773292006-04-21 09:43:23 +000018
19__all__ = [
20 "run_module",
21]
22
Thomas Woutersa9773292006-04-21 09:43:23 +000023
Thomas Woutersed03b412007-08-28 21:37:11 +000024def _run_code(code, run_globals, init_globals=None,
25 mod_name=None, mod_fname=None,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000026 mod_loader=None, pkg_name=None):
Thomas Woutersa9773292006-04-21 09:43:23 +000027 """Helper for _run_module_code"""
28 if init_globals is not None:
29 run_globals.update(init_globals)
30 run_globals.update(__name__ = mod_name,
31 __file__ = mod_fname,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000032 __loader__ = mod_loader,
33 __package__ = pkg_name)
Georg Brandl7cae87c2006-09-06 06:51:57 +000034 exec(code, run_globals)
Thomas Woutersa9773292006-04-21 09:43:23 +000035 return run_globals
36
37def _run_module_code(code, init_globals=None,
Thomas Woutersed03b412007-08-28 21:37:11 +000038 mod_name=None, mod_fname=None,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000039 mod_loader=None, pkg_name=None):
Thomas Woutersa9773292006-04-21 09:43:23 +000040 """Helper for run_module"""
41 # Set up the top level namespace dictionary
Thomas Woutersed03b412007-08-28 21:37:11 +000042 temp_module = imp.new_module(mod_name)
43 mod_globals = temp_module.__dict__
44 # Modify sys.argv[0] and sys.module[mod_name]
45 saved_argv0 = sys.argv[0]
46 restore_module = mod_name in sys.modules
47 if restore_module:
48 saved_module = sys.modules[mod_name]
49 sys.argv[0] = mod_fname
50 sys.modules[mod_name] = temp_module
51 try:
52 _run_code(code, mod_globals, init_globals,
Christian Heimescbf3b5c2007-12-03 21:02:03 +000053 mod_name, mod_fname,
54 mod_loader, pkg_name)
Thomas Woutersed03b412007-08-28 21:37:11 +000055 finally:
56 sys.argv[0] = saved_argv0
57 if restore_module:
58 sys.modules[mod_name] = saved_module
59 else:
60 del sys.modules[mod_name]
61 # Copy the globals of the temporary module, as they
62 # may be cleared when the temporary module goes away
63 return mod_globals.copy()
Thomas Woutersa9773292006-04-21 09:43:23 +000064
65
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000066# This helper is needed due to a missing component in the PEP 302
67# loader protocol (specifically, "get_filename" is non-standard)
Nick Coghlanf088e5e2008-12-14 11:50:48 +000068# Since we can't introduce new features in maintenance releases,
69# support was added to zipimporter under the name '_get_filename'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000070def _get_filename(loader, mod_name):
Nick Coghlanf088e5e2008-12-14 11:50:48 +000071 for attr in ("get_filename", "_get_filename"):
72 meth = getattr(loader, attr, None)
73 if meth is not None:
74 return meth(mod_name)
75 return None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076
Thomas Woutersed03b412007-08-28 21:37:11 +000077# Helper to get the loader, code and filename for a module
78def _get_module_details(mod_name):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079 loader = get_loader(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +000080 if loader is None:
Guido van Rossum806c2462007-08-06 23:33:07 +000081 raise ImportError("No module named %s" % mod_name)
82 if loader.is_package(mod_name):
83 raise ImportError(("%s is a package and cannot " +
84 "be directly executed") % mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +000085 code = loader.get_code(mod_name)
86 if code is None:
Guido van Rossum806c2462007-08-06 23:33:07 +000087 raise ImportError("No code object available for %s" % mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +000088 filename = _get_filename(loader, mod_name)
Thomas Woutersed03b412007-08-28 21:37:11 +000089 return loader, code, filename
90
91
92# XXX ncoghlan: Should this be documented and made public?
Christian Heimesc3f30c42008-02-22 16:37:40 +000093# (Current thoughts: don't repeat the mistake that lead to its
94# creation when run_module() no longer met the needs of
95# mainmodule.c, but couldn't be changed because it was public)
Thomas Woutersed03b412007-08-28 21:37:11 +000096def _run_module_as_main(mod_name, set_argv0=True):
97 """Runs the designated module in the __main__ namespace
98
99 These __*__ magic variables will be overwritten:
100 __file__
101 __loader__
102 """
Christian Heimesc3f30c42008-02-22 16:37:40 +0000103 try:
104 loader, code, fname = _get_module_details(mod_name)
105 except ImportError as exc:
106 # Try to provide a good error message
107 # for directories, zip files and the -m switch
108 if set_argv0:
109 # For -m switch, just disply the exception
110 info = str(exc)
111 else:
112 # For directories/zipfiles, let the user
113 # know what the code was looking for
114 info = "can't find '__main__.py' in %r" % sys.argv[0]
115 msg = "%s: %s" % (sys.executable, info)
116 sys.exit(msg)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000117 pkg_name = mod_name.rpartition('.')[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000118 main_globals = sys.modules["__main__"].__dict__
119 if set_argv0:
120 sys.argv[0] = fname
121 return _run_code(code, main_globals, None,
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000122 "__main__", fname, loader, pkg_name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000123
124def run_module(mod_name, init_globals=None,
125 run_name=None, alter_sys=False):
126 """Execute a module's code without importing it
127
128 Returns the resulting top level namespace dictionary
129 """
130 loader, code, fname = _get_module_details(mod_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000131 if run_name is None:
132 run_name = mod_name
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000133 pkg_name = mod_name.rpartition('.')[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000134 if alter_sys:
135 return _run_module_code(code, init_globals, run_name,
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000136 fname, loader, pkg_name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000137 else:
138 # Leave the sys module alone
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000139 return _run_code(code, {}, init_globals, run_name,
140 fname, loader, pkg_name)
Thomas Woutersa9773292006-04-21 09:43:23 +0000141
142
143if __name__ == "__main__":
144 # Run the module specified as the next command line argument
145 if len(sys.argv) < 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000146 print("No module specified for execution", file=sys.stderr)
Thomas Woutersa9773292006-04-21 09:43:23 +0000147 else:
148 del sys.argv[0] # Make the requested module sys.argv[0]
Thomas Woutersed03b412007-08-28 21:37:11 +0000149 _run_module_as_main(sys.argv[0])