Skip to main content
 首页 » 编程设计

python之在 KeyboardInterrupt() 上捕获回溯

2025年05月04日25zhenyulu

我有一个代码,可用于在 Ctrl+C 时停止。我想在我按 Ctrl+C 后做一些事情。因此我写:

try: 
    work() 
except KeyboardInterrupt: 
    do_other_stuff() 

但是我看不到我在哪里按了 Ctrl+C,因为没有 Traceback 打印出来;我想看到通常的消息

    Traceback (most recent call last): 
       File "X.py", line 16, in <module> 
         ... 

如何打印?我试着做

    except KeyboardInterrupt as e: 
       print str(e) 
       do_other_stuff() 

但它什么也不打印。

请您参考如下方法:

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