简体   繁体   English

在KeyboardInterrupt()上捕获回溯

[英]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.

相关问题 在KeyboardInterrupt中删除Traceback语句 - Remove Traceback statement in a KeyboardInterrupt 尝试/除了没有在KeyboardInterrupt上捕获UnboundLocalError - Try/Except not catching UnboundLocalError on KeyboardInterrupt 避免在Python 2.4中意外捕获KeyboardInterrupt和SystemExit - Avoiding accidentally catching KeyboardInterrupt and SystemExit in Python 2.4 Python 2.7:子线程无法捕获KeyboardInterrupt - Python 2.7: Child thread not catching KeyboardInterrupt 尝试环绕的导入并捕获KeyboardInterrupt - Try-surrounded imports and catching KeyboardInterrupt 在程序关闭期间在 Python 中捕获 KeyboardInterrupt - Catching KeyboardInterrupt in Python during program shutdown Python 在使用代码运行器停止时未捕获键盘中断 - Python not catching KeyboardInterrupt when stopping with code runner 停止单击(python 模块)从捕获/处理 KeyboardInterrupt - Stop click (python module) from catching/handling KeyboardInterrupt 在不关闭 Python 中的 Selenium Webdriver 会话的情况下捕获“KeyboardInterrupt” - Catching `KeyboardInterrupt` without closing Selenium Webdriver sessions in Python 在Python中,我可以阻止函数捕获KeyboardInterrupt和SystemExit吗? - In Python, can I prevent a function from catching KeyboardInterrupt and SystemExit?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM