如果您的代码引发运行时异常并且您的完成不起作用,那么您不知道为什么因为没有打印回溯。试试这个非常短的代码来看看我的意思:程序应该在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()
我的问题是:当有错误时如何显示错误? (使用cmd模块时)。
答案 0 :(得分: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(" ")
$ 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内打印回溯可能会弄乱你的终端。
不,你不能轻易崩溃阅读线。