| 1 |
"""runpy.py - locating and running Python code using the module namespace |
| 2 |
|
| 3 |
Provides support for locating and running Python scripts using the Python |
| 4 |
module namespace instead of the native filesystem. |
| 5 |
|
| 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. |
| 8 |
""" |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
import sys |
| 14 |
import importlib.machinery |
| 15 |
import importlib.util |
| 16 |
import io |
| 17 |
import os |
| 18 |
|
| 19 |
__all__ = [ |
| 20 |
"run_module", "run_path", |
| 21 |
] |
| 22 |
|
| 23 |
|
| 24 |
ModuleType = type(sys) |
| 25 |
|
| 26 |
class _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 = ModuleType(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 |
|
| 49 |
class _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 |
| 63 |
|
| 64 |
|
| 65 |
def _run_code(code, run_globals, init_globals=None, |
| 66 |
mod_name=None, mod_spec=None, |
| 67 |
pkg_name=None, script_name=None): |
| 68 |
"""Helper to run code in nominated namespace""" |
| 69 |
if init_globals is not None: |
| 70 |
run_globals.update(init_globals) |
| 71 |
if mod_spec is None: |
| 72 |
loader = None |
| 73 |
fname = script_name |
| 74 |
cached = None |
| 75 |
else: |
| 76 |
loader = mod_spec.loader |
| 77 |
fname = mod_spec.origin |
| 78 |
cached = mod_spec.cached |
| 79 |
if pkg_name is None: |
| 80 |
pkg_name = mod_spec.parent |
| 81 |
run_globals.update(__name__ = mod_name, |
| 82 |
__file__ = fname, |
| 83 |
__cached__ = cached, |
| 84 |
__doc__ = None, |
| 85 |
__loader__ = loader, |
| 86 |
__package__ = pkg_name, |
| 87 |
__spec__ = mod_spec) |
| 88 |
exec(code, run_globals) |
| 89 |
return run_globals |
| 90 |
|
| 91 |
def _run_module_code(code, init_globals=None, |
| 92 |
mod_name=None, mod_spec=None, |
| 93 |
pkg_name=None, script_name=None): |
| 94 |
"""Helper to run code in new namespace with sys modified""" |
| 95 |
fname = script_name if mod_spec is None else mod_spec.origin |
| 96 |
with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname): |
| 97 |
mod_globals = temp_module.module.__dict__ |
| 98 |
_run_code(code, mod_globals, init_globals, |
| 99 |
mod_name, mod_spec, pkg_name, script_name) |
| 100 |
|
| 101 |
|
| 102 |
return mod_globals.copy() |
| 103 |
|
| 104 |
|
| 105 |
def _get_module_details(mod_name, error=ImportError): |
| 106 |
if mod_name.startswith("."): |
| 107 |
raise error("Relative module names not supported") |
| 108 |
pkg_name, _, _ = mod_name.rpartition(".") |
| 109 |
if pkg_name: |
| 110 |
|
| 111 |
try: |
| 112 |
__import__(pkg_name) |
| 113 |
except ImportError as e: |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
if e.name is None or (e.name != pkg_name and |
| 118 |
not pkg_name.startswith(e.name + ".")): |
| 119 |
raise |
| 120 |
|
| 121 |
existing = sys.modules.get(mod_name) |
| 122 |
if existing is not None and not hasattr(existing, "__path__"): |
| 123 |
from warnings import warn |
| 124 |
msg = "{mod_name!r} found in sys.modules after import of " \ |
| 125 |
"package {pkg_name!r}, but prior to execution of " \ |
| 126 |
"{mod_name!r}; this may result in unpredictable " \ |
| 127 |
"behaviour".format(mod_name=mod_name, pkg_name=pkg_name) |
| 128 |
warn(RuntimeWarning(msg)) |
| 129 |
|
| 130 |
try: |
| 131 |
spec = importlib.util.find_spec(mod_name) |
| 132 |
except (ImportError, AttributeError, TypeError, ValueError) as ex: |
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
msg = "Error while finding module specification for {!r} ({}: {})" |
| 137 |
if mod_name.endswith(".py"): |
| 138 |
msg += (f". Try using '{mod_name[:-3]}' instead of " |
| 139 |
f"'{mod_name}' as the module name.") |
| 140 |
raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex |
| 141 |
if spec is None: |
| 142 |
if mod_name == "pip": |
| 143 |
mod_name += (' (to install pip, you need to run once' |
| 144 |
' "%s -m ensurepip")' % (sys.executable,)) |
| 145 |
raise error("No module named %s" % mod_name) |
| 146 |
if spec.submodule_search_locations is not None: |
| 147 |
if mod_name == "__main__" or mod_name.endswith(".__main__"): |
| 148 |
raise error("Cannot use package as __main__ module") |
| 149 |
try: |
| 150 |
pkg_main_name = mod_name + ".__main__" |
| 151 |
return _get_module_details(pkg_main_name, error) |
| 152 |
except error as e: |
| 153 |
if mod_name not in sys.modules: |
| 154 |
raise |
| 155 |
raise error(("%s; %r is a package and cannot " + |
| 156 |
"be directly executed") %(e, mod_name)) |
| 157 |
loader = spec.loader |
| 158 |
if loader is None: |
| 159 |
raise error("%r is a namespace package and cannot be executed" |
| 160 |
% mod_name) |
| 161 |
try: |
| 162 |
code = loader.get_code(mod_name) |
| 163 |
except ImportError as e: |
| 164 |
raise error(format(e)) from e |
| 165 |
if code is None: |
| 166 |
raise error("No code object available for %s" % mod_name) |
| 167 |
return mod_name, spec, code |
| 168 |
|
| 169 |
class _Error(Exception): |
| 170 |
"""Error that _run_module_as_main() should report without a traceback""" |
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
def _run_module_as_main(mod_name, alter_argv=True): |
| 177 |
"""Runs the designated module in the __main__ namespace |
| 178 |
|
| 179 |
Note that the executed module will have full access to the |
| 180 |
__main__ namespace. If this is not desirable, the run_module() |
| 181 |
function should be used to run the module code in a fresh namespace. |
| 182 |
|
| 183 |
At the very least, these variables in __main__ will be overwritten: |
| 184 |
__name__ |
| 185 |
__file__ |
| 186 |
__cached__ |
| 187 |
__loader__ |
| 188 |
__package__ |
| 189 |
""" |
| 190 |
try: |
| 191 |
if alter_argv or mod_name != "__main__": |
| 192 |
mod_name, mod_spec, code = _get_module_details(mod_name, _Error) |
| 193 |
else: |
| 194 |
mod_name, mod_spec, code = _get_main_module_details(_Error) |
| 195 |
except _Error as exc: |
| 196 |
msg = "%s: %s" % (sys.executable, exc) |
| 197 |
sys.exit(msg) |
| 198 |
main_globals = sys.modules["__main__"].__dict__ |
| 199 |
if alter_argv: |
| 200 |
sys.argv[0] = mod_spec.origin |
| 201 |
return _run_code(code, main_globals, None, |
| 202 |
"__main__", mod_spec) |
| 203 |
|
| 204 |
def run_module(mod_name, init_globals=None, |
| 205 |
run_name=None, alter_sys=False): |
| 206 |
"""Execute a module's code without importing it. |
| 207 |
|
| 208 |
mod_name -- an absolute module name or package name. |
| 209 |
|
| 210 |
Optional arguments: |
| 211 |
init_globals -- dictionary used to pre-populate the module’s |
| 212 |
globals dictionary before the code is executed. |
| 213 |
|
| 214 |
run_name -- if not None, this will be used for setting __name__; |
| 215 |
otherwise, __name__ will be set to mod_name + '__main__' if the |
| 216 |
named module is a package and to just mod_name otherwise. |
| 217 |
|
| 218 |
alter_sys -- if True, sys.argv[0] is updated with the value of |
| 219 |
__file__ and sys.modules[__name__] is updated with a temporary |
| 220 |
module object for the module being executed. Both are |
| 221 |
restored to their original values before the function returns. |
| 222 |
|
| 223 |
Returns the resulting module globals dictionary. |
| 224 |
""" |
| 225 |
mod_name, mod_spec, code = _get_module_details(mod_name) |
| 226 |
if run_name is None: |
| 227 |
run_name = mod_name |
| 228 |
if alter_sys: |
| 229 |
return _run_module_code(code, init_globals, run_name, mod_spec) |
| 230 |
else: |
| 231 |
|
| 232 |
return _run_code(code, {}, init_globals, run_name, mod_spec) |
| 233 |
|
| 234 |
def _get_main_module_details(error=ImportError): |
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
main_name = "__main__" |
| 240 |
saved_main = sys.modules[main_name] |
| 241 |
del sys.modules[main_name] |
| 242 |
try: |
| 243 |
return _get_module_details(main_name) |
| 244 |
except ImportError as exc: |
| 245 |
if main_name in str(exc): |
| 246 |
raise error("can't find %r module in %r" % |
| 247 |
(main_name, sys.path[0])) from exc |
| 248 |
raise |
| 249 |
finally: |
| 250 |
sys.modules[main_name] = saved_main |
| 251 |
|
| 252 |
|
| 253 |
def _get_code_from_file(run_name, fname): |
| 254 |
|
| 255 |
from pkgutil import read_code |
| 256 |
decoded_path = os.path.abspath(os.fsdecode(fname)) |
| 257 |
with io.open_code(decoded_path) as f: |
| 258 |
code = read_code(f) |
| 259 |
if code is None: |
| 260 |
|
| 261 |
with io.open_code(decoded_path) as f: |
| 262 |
code = compile(f.read(), fname, 'exec') |
| 263 |
return code, fname |
| 264 |
|
| 265 |
def run_path(path_name, init_globals=None, run_name=None): |
| 266 |
"""Execute code located at the specified filesystem location. |
| 267 |
|
| 268 |
path_name -- filesystem location of a Python script, zipfile, |
| 269 |
or directory containing a top level __main__.py script. |
| 270 |
|
| 271 |
Optional arguments: |
| 272 |
init_globals -- dictionary used to pre-populate the module’s |
| 273 |
globals dictionary before the code is executed. |
| 274 |
|
| 275 |
run_name -- if not None, this will be used to set __name__; |
| 276 |
otherwise, '<run_path>' will be used for __name__. |
| 277 |
|
| 278 |
Returns the resulting module globals dictionary. |
| 279 |
""" |
| 280 |
if run_name is None: |
| 281 |
run_name = "<run_path>" |
| 282 |
pkg_name = run_name.rpartition(".")[0] |
| 283 |
from pkgutil import get_importer |
| 284 |
importer = get_importer(path_name) |
| 285 |
|
| 286 |
is_NullImporter = False |
| 287 |
if type(importer).__module__ == 'imp': |
| 288 |
if type(importer).__name__ == 'NullImporter': |
| 289 |
is_NullImporter = True |
| 290 |
if isinstance(importer, type(None)) or is_NullImporter: |
| 291 |
|
| 292 |
|
| 293 |
code, fname = _get_code_from_file(run_name, path_name) |
| 294 |
return _run_module_code(code, init_globals, run_name, |
| 295 |
pkg_name=pkg_name, script_name=fname) |
| 296 |
else: |
| 297 |
|
| 298 |
|
| 299 |
sys.path.insert(0, path_name) |
| 300 |
try: |
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
mod_name, mod_spec, code = _get_main_module_details() |
| 308 |
with _TempModule(run_name) as temp_module, \ |
| 309 |
_ModifiedArgv0(path_name): |
| 310 |
mod_globals = temp_module.module.__dict__ |
| 311 |
return _run_code(code, mod_globals, init_globals, |
| 312 |
run_name, mod_spec, pkg_name).copy() |
| 313 |
finally: |
| 314 |
try: |
| 315 |
sys.path.remove(path_name) |
| 316 |
except ValueError: |
| 317 |
pass |
| 318 |
|
| 319 |
|
| 320 |
if __name__ == "__main__": |
| 321 |
|
| 322 |
if len(sys.argv) < 2: |
| 323 |
print("No module specified for execution", file=sys.stderr) |
| 324 |
else: |
| 325 |
del sys.argv[0] |
| 326 |
_run_module_as_main(sys.argv[0]) |