如何使用cmd Python模块使我的程序崩溃?

5

发生的情况是,如果你的代码引发运行时异常,并且你的完成不起作用,那么你就不知道为什么,因为traceback没有被打印。尝试运行此非常简短的代码,看看我是什么意思:程序应该在c = 2 +“ddda”这一行崩溃,很明显你正在将一个字符串和一个整数相加,这根本行不通。但是,异常被捕获了,你完全不知道发生了什么。程序继续运行,好像什么都没有发生一样。

import cmd

class App(cmd.Cmd):
    def complete_foo(self,*arg):
        # Uncommenting this line will silently crash the progrm
        # making it hard to debug.
        # Is there a way to force the program to crash ?
        c = 2 + "ddda"
        return "d dzpo idz dza dpaoi".split(" ")

    def do_foo(self,*args):
        print "foo"
App().cmdloop()

我的问题是:如何在使用cmd模块时显示错误信息?

еҰӮжһңд»Јз ҒжІЎжңүеңЁеӨ„зҗҶй”ҷиҜҜзҡ„tryеқ—еҶ…иў«и°ғз”ЁпјҢе®ғеә”иҜҘеҒңжӯўе№¶жҳҫзӨәй”ҷиҜҜе’ҢеӣһжәҜдҝЎжҒҜгҖӮ - Barmar
1个回答

5

很不幸,completers 触发的异常被捕获在 readline 深处的某个地方。你可以尝试以下方法:

...
import cmd
import traceback

def log_exceptions(fun):
    def wrapped(*a, **kw):
        try:
            return fun(*a, **kw)
        except Exception:
            print traceback.format_exc()
            raise

    return wrapped

class App(cmd.Cmd):
    @log_exceptions
    def complete_foo(self,*arg):
        # Uncommenting this line will silently crash the progrm
        # making it hard to debug.
        # Is there a way to force the program to crash ?
        c = 2 + "ddda"
        return "d dzpo idz dza dpaoi".split(" ")

 

$ python c.py
(Cmd) foo Traceback (most recent call last):
  File "c.py", line 7, in wrapped
    return fun(*a, **kw)
  File "c.py", line 20, in complete_foo
    c = 2 + "ddda"
TypeError: unsupported operand type(s) for +: 'int' and 'str'

在调试完成后,请删除修饰符,因为从readline内部打印traceback可能会破坏您的终端。

 

不,您不能轻易崩溃readline。


谢谢。我喜欢你的解决方案。我在cmd模块中搜索了try/catch块,但没有发现任何可疑的东西。你关于readline的解释似乎是一个合理的线索,而装饰器则是一个实用的解决方案。再次感谢。 - ychaouche
另外,如果只想打印回溯信息,traceback.print_exc()是另一种简写方式。 - ychaouche
它会打印到stderr,而readline似乎也会抑制它。 - Pavel Anossov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接