[英]Catching the Traceback on KeyboardInterrupt()
I have a code that I use to stop on Ctrl+C. 我有一个用于在Ctrl + C上停止的代码。 I would like to do some things juste after i did Ctrl+C.
在执行Ctrl + C之后,我想做一些事情。 Therefore I write:
因此我写:
try:
work()
except KeyboardInterrupt:
do_other_stuff()
But I don't see where I did Ctrl+C, as no Traceback prints; 但是我看不到Ctrl + C的执行位置,因为没有回溯打印。 I want to see the usual message
我想查看通常的消息
Traceback (most recent call last):
File "X.py", line 16, in <module>
...
How can I print this? 我该如何打印? I tried to do
我试着做
except KeyboardInterrupt as e:
print str(e)
do_other_stuff()
but it prints nothing. 但它什么也不打印。
import sys, traceback
def func():
try:
work()
except KeyboardInterrupt:
do_something()
traceback.print_exc(file=sys.stdout)
if file
is omitted then the output goes to stderr
. 如果省略
file
,则输出转到stderr
。 for more on traceback... https://docs.python.org/2/library/traceback.html 有关追溯的更多信息... https://docs.python.org/2/library/traceback.html
KeyboardInterrupt
继承自BaseException
,在BaseException
您可以使用traceback.format_exc(e)
获得错误所在的行。
You were close: 您接近:
try:
while True:
x = 1
except KeyboardInterrupt as e:
print 'Here we are, in the error handler!'
raise e
Just make sure you run do_other_stuff()
before you call raise e
. 只要确保您运行
do_other_stuff()
然后再调用raise e
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.