diff options
Diffstat (limited to 'Lib/runpy.py')
-rw-r--r-- | Lib/runpy.py | 66 |
1 files changed, 40 insertions, 26 deletions
diff --git a/Lib/runpy.py b/Lib/runpy.py index 0bb57d76ce..af6205db49 100644 --- a/Lib/runpy.py +++ b/Lib/runpy.py @@ -58,7 +58,7 @@ class _ModifiedArgv0(object): self.value = self._sentinel sys.argv[0] = self._saved_value -# TODO: Replace these helpers with importlib._bootstrap._SpecMethods +# TODO: Replace these helpers with importlib._bootstrap_external functions. def _run_code(code, run_globals, init_globals=None, mod_name=None, mod_spec=None, pkg_name=None, script_name=None): @@ -99,7 +99,22 @@ def _run_module_code(code, init_globals=None, return mod_globals.copy() # Helper to get the loader, code and filename for a module -def _get_module_details(mod_name): +def _get_module_details(mod_name, error=ImportError): + if mod_name.startswith("."): + raise error("Relative module names not supported") + pkg_name, _, _ = mod_name.rpartition(".") + if pkg_name: + # Try importing the parent to avoid catching initialization errors + try: + __import__(pkg_name) + except ImportError as e: + # If the parent or higher ancestor package is missing, let the + # error be raised by find_spec() below and then be caught. But do + # not allow other errors to be caught. + if e.name is None or (e.name != pkg_name and + not pkg_name.startswith(e.name + ".")): + raise + try: spec = importlib.util.find_spec(mod_name) except (ImportError, AttributeError, TypeError, ValueError) as ex: @@ -107,27 +122,35 @@ def _get_module_details(mod_name): # importlib, where the latter raises other errors for cases where # pkgutil previously raised ImportError msg = "Error while finding spec for {!r} ({}: {})" - raise ImportError(msg.format(mod_name, type(ex), ex)) from ex + raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex if spec is None: - raise ImportError("No module named %s" % mod_name) + raise error("No module named %s" % mod_name) if spec.submodule_search_locations is not None: if mod_name == "__main__" or mod_name.endswith(".__main__"): - raise ImportError("Cannot use package as __main__ module") + raise error("Cannot use package as __main__ module") try: pkg_main_name = mod_name + ".__main__" - return _get_module_details(pkg_main_name) - except ImportError as e: - raise ImportError(("%s; %r is a package and cannot " + + return _get_module_details(pkg_main_name, error) + except error as e: + if mod_name not in sys.modules: + raise # No module loaded; being a package is irrelevant + raise error(("%s; %r is a package and cannot " + "be directly executed") %(e, mod_name)) loader = spec.loader if loader is None: - raise ImportError("%r is a namespace package and cannot be executed" + raise error("%r is a namespace package and cannot be executed" % mod_name) - code = loader.get_code(mod_name) + try: + code = loader.get_code(mod_name) + except ImportError as e: + raise error(format(e)) from e if code is None: - raise ImportError("No code object available for %s" % mod_name) + raise error("No code object available for %s" % mod_name) return mod_name, spec, code +class _Error(Exception): + """Error that _run_module_as_main() should report without a traceback""" + # XXX ncoghlan: Should this be documented and made public? # (Current thoughts: don't repeat the mistake that lead to its # creation when run_module() no longer met the needs of @@ -148,20 +171,11 @@ def _run_module_as_main(mod_name, alter_argv=True): """ try: if alter_argv or mod_name != "__main__": # i.e. -m switch - mod_name, mod_spec, code = _get_module_details(mod_name) + mod_name, mod_spec, code = _get_module_details(mod_name, _Error) else: # i.e. directory or zipfile execution - mod_name, mod_spec, code = _get_main_module_details() - except ImportError as exc: - # Try to provide a good error message - # for directories, zip files and the -m switch - if alter_argv: - # For -m switch, just display the exception - info = str(exc) - else: - # For directories/zipfiles, let the user - # know what the code was looking for - info = "can't find '__main__' module in %r" % sys.argv[0] - msg = "%s: %s" % (sys.executable, info) + mod_name, mod_spec, code = _get_main_module_details(_Error) + except _Error as exc: + msg = "%s: %s" % (sys.executable, exc) sys.exit(msg) main_globals = sys.modules["__main__"].__dict__ if alter_argv: @@ -184,7 +198,7 @@ def run_module(mod_name, init_globals=None, # Leave the sys module alone return _run_code(code, {}, init_globals, run_name, mod_spec) -def _get_main_module_details(): +def _get_main_module_details(error=ImportError): # Helper that gives a nicer error message when attempting to # execute a zipfile or directory by invoking __main__.py # Also moves the standard __main__ out of the way so that the @@ -196,7 +210,7 @@ def _get_main_module_details(): return _get_module_details(main_name) except ImportError as exc: if main_name in str(exc): - raise ImportError("can't find %r module in %r" % + raise error("can't find %r module in %r" % (main_name, sys.path[0])) from exc raise finally: |