如何在使用cmd模块时让我的程序正确崩溃?

5 投票
1 回答
1191 浏览
提问于 2025-04-17 18:28

发生的情况是,如果你的代码在运行时出现了错误,而你的程序没有正常结束,你就不知道发生了什么,因为错误信息没有被显示出来。试试这段很短的代码,你就明白我说的意思了:程序应该在这一行崩溃,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模块的时候)。

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 里面打印错误信息可能会搞乱你的终端显示。

 

不,你不能轻易让 readline 崩溃。

撰写回答