Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(29617)

Unified Diff: Lib/runpy.py

Issue 14285: Traceback wrong on ImportError while executing a package
Patch Set: Created 3 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « Doc/using/cmdline.rst ('k') | Lib/test/test_cmd_line_script.py » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
--- a/Lib/runpy.py Thu Dec 03 22:27:31 2015 +0200
+++ b/Lib/runpy.py Sun Dec 06 23:23:35 2015 +0000
@@ -100,6 +100,22 @@
# Helper to get the loader, code and filename for a module
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 err:
+ # If the parent or higher ancestor package is missing, this is an
+ # error that we may want to catch. But do not allow other errors
+ # to be caught.
+ if err.name is None or (err.name != pkg_name and
+ not pkg_name.startswith(err.name + ".")):
+ raise
+ raise error(format(err))
+
try:
spec = importlib.util.find_spec(mod_name)
except (ImportError, AttributeError, TypeError, ValueError) as ex:
@@ -107,17 +123,16 @@
# importlib, where the latter raises other errors for cases where
# pkgutil previously raised ImportError
msg = "Error while finding spec for {!r} ({}: {})"
- raise error(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 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 error("Cannot use package as __main__ module")
- __import__(mod_name) # Do not catch exceptions initializing package
try:
pkg_main_name = mod_name + ".__main__"
- return _get_module_details(pkg_main_name)
- except ImportError as e:
+ return _get_module_details(pkg_main_name, error)
+ except error as e:
raise error(("%s; %r is a package and cannot " +
"be directly executed") %(e, mod_name))
loader = spec.loader
« no previous file with comments | « Doc/using/cmdline.rst ('k') | Lib/test/test_cmd_line_script.py » ('j') | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+