首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python 3.4中使用runpy时未显示回溯

在Python 3.4中使用runpy时未显示回溯
EN

Stack Overflow用户
提问于 2015-11-23 22:19:01
回答 1查看 399关注 0票数 1

通过runpy运行Python模块有时不会显示任何回溯。

例如,如果模块引发一个AttributeError,那么结果将是这样;

代码语言:javascript
复制
$ 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,回溯将正确显示;

代码语言:javascript
复制
$ 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有关

代码语言:javascript
复制
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应该确保原始的回溯保持得当,并在某个阶段通过标准输出打印出来。

问题的根源似乎是;

代码语言:javascript
复制
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)

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2015-11-23 22:53:34

这是Python中的一个潜在错误,已在here中提出。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33873243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档