[英]Traceback not shown when using runpy in Python 3.4
通过runpy
运行Python模块有时不会显示任何回溯。
例如,如果模块引发AttributeError
,那么结果将是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
但是,如果导致NameError
,则回溯将正确显示;
$ 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
无论错误是什么,我都希望显示完整的追溯。 我尝试了几个CLI选项,包括-v
-d
没有影响。
它似乎与此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 ex
可以确保原始回溯保持完整并在某个阶段通过stdout打印。
看来问题的根源是:
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)
有任何想法吗?
这是Python中潜在的错误,已在此处提出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.