blob: d35480255150385c719dd386c83b43d99e07c962 [file] [log] [blame]
Nick Coghlane2ebb2d2006-03-15 11:00:26 +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
Phillip J. Ebyab1d2452006-04-17 20:17:25 +000014try:
15 from imp import get_loader
16except ImportError:
17 from pkgutil import get_loader
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000018
19__all__ = [
20 "run_module",
21]
22
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000023
Nick Coghlan1a42ece2007-08-25 10:50:41 +000024def _run_code(code, run_globals, init_globals=None,
25 mod_name=None, mod_fname=None,
Nick Coghlanef01d822007-12-03 12:55:17 +000026 mod_loader=None, pkg_name=None):
Nick Coghlane471b9b2009-11-07 08:15:01 +000027 """Helper to run code in nominated namespace"""
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000028 if init_globals is not None:
29 run_globals.update(init_globals)
Nick Coghlan56829d52006-07-06 12:53:04 +000030 run_globals.update(__name__ = mod_name,
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000031 __file__ = mod_fname,
Nick Coghlanef01d822007-12-03 12:55:17 +000032 __loader__ = mod_loader,
33 __package__ = pkg_name)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000034 exec code in run_globals
35 return run_globals
36
Nick Coghlan56829d52006-07-06 12:53:04 +000037def _run_module_code(code, init_globals=None,
Nick Coghlan3af0e782007-08-25 04:32:07 +000038 mod_name=None, mod_fname=None,
Nick Coghlanef01d822007-12-03 12:55:17 +000039 mod_loader=None, pkg_name=None):
Nick Coghlane471b9b2009-11-07 08:15:01 +000040 """Helper to run code in new namespace with sys modified"""
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000041 # Set up the top level namespace dictionary
Nick Coghlan1a42ece2007-08-25 10:50:41 +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,
Nick Coghlanef01d822007-12-03 12:55:17 +000053 mod_name, mod_fname,
54 mod_loader, pkg_name)
Nick Coghlan1a42ece2007-08-25 10:50:41 +000055 finally:
56 sys.argv[0] = saved_argv0
Nick Coghlan3af0e782007-08-25 04:32:07 +000057 if restore_module:
58 sys.modules[mod_name] = saved_module
59 else:
60 del sys.modules[mod_name]
Nick Coghlan1a42ece2007-08-25 10:50:41 +000061 # Copy the globals of the temporary module, as they
62 # may be cleared when the temporary module goes away
63 return mod_globals.copy()
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000064
65
Phillip J. Ebyab1d2452006-04-17 20:17:25 +000066# This helper is needed due to a missing component in the PEP 302
67# loader protocol (specifically, "get_filename" is non-standard)
Nick Coghlana2053472008-12-14 10:54:50 +000068# Since we can't introduce new features in maintenance releases,
69# support was added to zipimporter under the name '_get_filename'
Phillip J. Ebyab1d2452006-04-17 20:17:25 +000070def _get_filename(loader, mod_name):
Nick Coghlana2053472008-12-14 10:54:50 +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
Phillip J. Ebyab1d2452006-04-17 20:17:25 +000076
Nick Coghlan1a42ece2007-08-25 10:50:41 +000077# Helper to get the loader, code and filename for a module
78def _get_module_details(mod_name):
Phillip J. Ebyab1d2452006-04-17 20:17:25 +000079 loader = get_loader(mod_name)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000080 if loader is None:
Nick Coghlanae21fc62007-07-23 13:41:45 +000081 raise ImportError("No module named %s" % mod_name)
82 if loader.is_package(mod_name):
Nick Coghland39600e2009-02-08 01:26:34 +000083 if mod_name == "__main__" or mod_name.endswith(".__main__"):
Nick Coghlane471b9b2009-11-07 08:15:01 +000084 raise ImportError("Cannot use package as __main__ module")
Nick Coghland39600e2009-02-08 01:26:34 +000085 try:
86 pkg_main_name = mod_name + ".__main__"
87 return _get_module_details(pkg_main_name)
88 except ImportError, e:
89 raise ImportError(("%s; %r is a package and cannot " +
90 "be directly executed") %(e, mod_name))
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000091 code = loader.get_code(mod_name)
92 if code is None:
Nick Coghlanae21fc62007-07-23 13:41:45 +000093 raise ImportError("No code object available for %s" % mod_name)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +000094 filename = _get_filename(loader, mod_name)
Nick Coghland39600e2009-02-08 01:26:34 +000095 return mod_name, loader, code, filename
Nick Coghlan1a42ece2007-08-25 10:50:41 +000096
97
98# XXX ncoghlan: Should this be documented and made public?
Nick Coghlana14a4e82008-02-22 10:54:06 +000099# (Current thoughts: don't repeat the mistake that lead to its
100# creation when run_module() no longer met the needs of
101# mainmodule.c, but couldn't be changed because it was public)
Nick Coghlane471b9b2009-11-07 08:15:01 +0000102def _run_module_as_main(mod_name, alter_argv=True):
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000103 """Runs the designated module in the __main__ namespace
104
Nick Coghlane471b9b2009-11-07 08:15:01 +0000105 Note that the executed module will have full access to the
106 __main__ namespace. If this is not desirable, the run_module()
107 function sbould be used to run the module code in a fresh namespace.
108
109 At the very least, these variables in __main__ will be overwritten:
110 __name__
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000111 __file__
112 __loader__
Nick Coghlane471b9b2009-11-07 08:15:01 +0000113 __package__
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000114 """
Nick Coghlana14a4e82008-02-22 10:54:06 +0000115 try:
Nick Coghland39600e2009-02-08 01:26:34 +0000116 mod_name, loader, code, fname = _get_module_details(mod_name)
Nick Coghlana14a4e82008-02-22 10:54:06 +0000117 except ImportError as exc:
118 # Try to provide a good error message
119 # for directories, zip files and the -m switch
Nick Coghlane471b9b2009-11-07 08:15:01 +0000120 if alter_argv:
Nick Coghland39600e2009-02-08 01:26:34 +0000121 # For -m switch, just display the exception
Nick Coghlana14a4e82008-02-22 10:54:06 +0000122 info = str(exc)
123 else:
124 # For directories/zipfiles, let the user
125 # know what the code was looking for
126 info = "can't find '__main__.py' in %r" % sys.argv[0]
127 msg = "%s: %s" % (sys.executable, info)
128 sys.exit(msg)
Nick Coghlanef01d822007-12-03 12:55:17 +0000129 pkg_name = mod_name.rpartition('.')[0]
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000130 main_globals = sys.modules["__main__"].__dict__
Nick Coghlane471b9b2009-11-07 08:15:01 +0000131 if alter_argv:
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000132 sys.argv[0] = fname
133 return _run_code(code, main_globals, None,
Nick Coghlanef01d822007-12-03 12:55:17 +0000134 "__main__", fname, loader, pkg_name)
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000135
136def run_module(mod_name, init_globals=None,
137 run_name=None, alter_sys=False):
138 """Execute a module's code without importing it
139
140 Returns the resulting top level namespace dictionary
141 """
Nick Coghland39600e2009-02-08 01:26:34 +0000142 mod_name, loader, code, fname = _get_module_details(mod_name)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000143 if run_name is None:
144 run_name = mod_name
Nick Coghlanef01d822007-12-03 12:55:17 +0000145 pkg_name = mod_name.rpartition('.')[0]
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000146 if alter_sys:
147 return _run_module_code(code, init_globals, run_name,
Nick Coghlanef01d822007-12-03 12:55:17 +0000148 fname, loader, pkg_name)
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000149 else:
150 # Leave the sys module alone
Nick Coghlanef01d822007-12-03 12:55:17 +0000151 return _run_code(code, {}, init_globals, run_name,
152 fname, loader, pkg_name)
Nick Coghlane2ebb2d2006-03-15 11:00:26 +0000153
154
155if __name__ == "__main__":
156 # Run the module specified as the next command line argument
157 if len(sys.argv) < 2:
158 print >> sys.stderr, "No module specified for execution"
159 else:
160 del sys.argv[0] # Make the requested module sys.argv[0]
Nick Coghlan1a42ece2007-08-25 10:50:41 +0000161 _run_module_as_main(sys.argv[0])