簡體   English   中英

在Python 3.4中使用Runpy時未顯示回溯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM