简体   繁体   中英

Traceback not shown when using runpy in Python 3.4

Running a Python module via runpy will sometimes not show any traceback.

For example, if the module raises an AttributeError , then the result would be this;

$ echo 'import random; random.dsgjdgj' > hello/__init__.py
$ python -m hello
/bin/python: Error while finding spec for 'hello.__main__' 
(<class 'AttributeError'>: 'module' object has no attribute 'dsgjdgj');
'hello' is a package and cannot be directly executed

However if you cause an NameError , the traceback will show correctly;

$ echo 'lalalalal' > hello/__init__.py
$ python -m hello
Traceback (most recent call last):
  File "/usr/lib/python3.4/runpy.py", line 151, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name)
  File "/usr/lib/python3.4/runpy.py", line 118, in _get_module_details
    return _get_module_details(pkg_main_name)
  File "/usr/lib/python3.4/runpy.py", line 104, in _get_module_details
    spec = importlib.util.find_spec(mod_name)
  File "/usr/lib/python3.4/importlib/util.py", line 86, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
  File "/vagrant/server/hello/__init__.py", line 1, in <module>
    lalalalal
NameError: name 'lalalalal' is not defined

I'd like to show a full traceback, regardless of what the error is. I've tried several CLI options, including -v -d with no impact.

It seems to be related to this cpython/Lib/runpy.py :

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

From what I can tell, from ex should ensure that the original traceback is kept in tact and printed via stdout at some stage.

It would appear the source of the problem is;

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)

Any ideas?

这是Python中潜在的错误,已在此处提出。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM