1 """runpy.py - locating and running Python code using the module namespace
3 Provides support for locating and running Python scripts using the Python
4 module namespace instead of the native filesystem.
6 This allows Python code to play nicely with non-filesystem based PEP 302
7 importers when locating support scripts as well as when importing modules.
9 # Written by Nick Coghlan <ncoghlan at gmail.com>
10 # to implement PEP 338 (Executing Modules as Scripts)
15 from imp
import get_loader
17 from pkgutil
import get_loader
24 def _run_code(code
, run_globals
, init_globals
=None,
25 mod_name
=None, mod_fname
=None,
26 mod_loader
=None, pkg_name
=None):
27 """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
,
32 __loader__
= mod_loader
,
33 __package__
= pkg_name
)
34 exec code
in run_globals
37 def _run_module_code(code
, init_globals
=None,
38 mod_name
=None, mod_fname
=None,
39 mod_loader
=None, pkg_name
=None):
40 """Helper for run_module"""
41 # Set up the top level namespace dictionary
42 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
48 saved_module
= sys
.modules
[mod_name
]
49 sys
.argv
[0] = mod_fname
50 sys
.modules
[mod_name
] = temp_module
52 _run_code(code
, mod_globals
, init_globals
,
56 sys
.argv
[0] = saved_argv0
58 sys
.modules
[mod_name
] = saved_module
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()
66 # This helper is needed due to a missing component in the PEP 302
67 # loader protocol (specifically, "get_filename" is non-standard)
68 # Since we can't introduce new features in maintenance releases,
69 # support was added to zipimporter under the name '_get_filename'
70 def _get_filename(loader
, mod_name
):
71 for attr
in ("get_filename", "_get_filename"):
72 meth
= getattr(loader
, attr
, None)
77 # Helper to get the loader, code and filename for a module
78 def _get_module_details(mod_name
):
79 loader
= get_loader(mod_name
)
81 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
)
85 code
= loader
.get_code(mod_name
)
87 raise ImportError("No code object available for %s" % mod_name
)
88 filename
= _get_filename(loader
, mod_name
)
89 return loader
, code
, filename
92 # XXX ncoghlan: Should this be documented and made public?
93 # (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)
96 def _run_module_as_main(mod_name
, set_argv0
=True):
97 """Runs the designated module in the __main__ namespace
99 These __*__ magic variables will be overwritten:
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
109 # For -m switch, just disply the exception
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
)
117 pkg_name
= mod_name
.rpartition('.')[0]
118 main_globals
= sys
.modules
["__main__"].__dict
__
121 return _run_code(code
, main_globals
, None,
122 "__main__", fname
, loader
, pkg_name
)
124 def run_module(mod_name
, init_globals
=None,
125 run_name
=None, alter_sys
=False):
126 """Execute a module's code without importing it
128 Returns the resulting top level namespace dictionary
130 loader
, code
, fname
= _get_module_details(mod_name
)
133 pkg_name
= mod_name
.rpartition('.')[0]
135 return _run_module_code(code
, init_globals
, run_name
,
136 fname
, loader
, pkg_name
)
138 # Leave the sys module alone
139 return _run_code(code
, {}, init_globals
, run_name
,
140 fname
, loader
, pkg_name
)
143 if __name__
== "__main__":
144 # Run the module specified as the next command line argument
145 if len(sys
.argv
) < 2:
146 print >> sys
.stderr
, "No module specified for execution"
148 del sys
.argv
[0] # Make the requested module sys.argv[0]
149 _run_module_as_main(sys
.argv
[0])