diff --git a/Lib/runpy.py b/Lib/runpy.py --- a/Lib/runpy.py +++ b/Lib/runpy.py @@ -102,28 +102,36 @@ def _run_module_code(code, init_globals= def _get_module_details(mod_name): try: spec = importlib.util.find_spec(mod_name) except (ImportError, AttributeError, TypeError, ValueError) as ex: # This hack fixes an impedance mismatch between pkgutil and # 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 + if type(ex) is ImportError: + raise ImportError(msg.format(mod_name, type(ex), ex), + name=ex.name) from ex + else: + raise ImportError(msg.format(mod_name, type(ex), ex)) from ex if spec is None: raise ImportError("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") 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 " + - "be directly executed") %(e, mod_name)) + if e.name is None: + raise ImportError(("%s; %r is a package and cannot " + + "be directly executed") %(e, mod_name)) + else: + raise ImportError(("%s; Error executing package %r") + %(e, mod_name)) loader = spec.loader if loader is None: raise ImportError("%r is a namespace package and cannot be executed" % mod_name) code = loader.get_code(mod_name) if code is None: raise ImportError("No code object available for %s" % mod_name) return mod_name, spec, code