使用cmd python模块时,如何使程序正常崩溃?

ych*_*che 5 python cmd

会发生的是,如果您的代码引发运行时异常并且您的完成不起作用,您就不知道为什么因为没有打印回溯.试试这个非常短的代码来看看我的意思:程序应该在c = 2 +"ddda"上崩溃,显然你要添加一个字符串和一个int,这根本不起作用.但是不是崩溃,而是异常被抓住了,你不知道发生了什么.该程序继续运行,好像什么也没发生.

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()
Run Code Online (Sandbox Code Playgroud)

我的问题是:当有错误时如何显示错误?(使用cmd模块时).

Pav*_*sov 5

不幸的是,完成者中的异常被捕获在黑暗深处的某个地方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(" ")
Run Code Online (Sandbox Code Playgroud)

 

$ 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'
Run Code Online (Sandbox Code Playgroud)

在调试完成器之后删除装饰器,因为从readline内部打印回溯可能会弄乱您的终端.

 

不,你不能轻易崩溃readline.