通过runpy运行Python模块有时不会显示任何回溯。
例如,如果模块引发一个AttributeError,那么结果将是这样;
$ 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我想要显示一个完整的回溯,不管错误是什么。我尝试了几个命令行界面选项,包括-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应该确保原始的回溯保持得当,并在某个阶段通过标准输出打印出来。
问题的根源似乎是;
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)有什么想法吗?
发布于 2015-11-23 22:53:34
这是Python中的一个潜在错误,已在here中提出。
https://stackoverflow.com/questions/33873243
复制相似问题