我有一个在Ctrl+C上停止的代码。我想在做Ctrl+C之后做一些事情。因此我写:
try:
work()
except KeyboardInterrupt:
do_other_stuff()但我看不出我做了什么Ctrl+C,因为没有回溯打印;我想看看通常的信息
Traceback (most recent call last):
File "X.py", line 16, in <module>
...我怎么打印这个?我试着做
except KeyboardInterrupt as e:
print str(e)
do_other_stuff()但它什么也没印。
发布于 2016-07-01 12:21:09
import sys, traceback
def func():
try:
work()
except KeyboardInterrupt:
do_something()
traceback.print_exc(file=sys.stdout)如果省略了file,那么输出将转到stderr。关于追踪的更多信息..。https://docs.python.org/2/library/traceback.html
发布于 2016-07-01 12:15:44
你们很亲密:
try:
while True:
x = 1
except KeyboardInterrupt as e:
print 'Here we are, in the error handler!'
raise e只需确保在调用do_other_stuff()之前运行raise e即可。
发布于 2016-07-01 12:19:36
KeyboardInterrupt从BaseException继承,在BaseException中,您可以使用traceback.format_exc(e)获得错误的行。
https://stackoverflow.com/questions/38145111
复制相似问题