博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 捕获全局的 KeyboardInterrupt 异常
阅读量:4228 次
发布时间:2019-05-26

本文共 1496 字,大约阅读时间需要 4 分钟。

当然,像下面这种情况。

你要是把所有代码像下面那样都放到 try, except 的情况,就当我什么也没说。

import timedef main():    print('before ...')    time.sleep(10)    print('after ...')if __name__ == '__main__':    try:        main()    except KeyboardInterrupt:        print('\nKeyboardInterrupt ...')    print('the end')
root@master ~/w/python3_learning# python3 test.py before ...^CKeyboardInterrupt ...the end

一般情况下,程序运行过程当中要执行的代码量会比较大,一般用户执行 Ctrl + C 程序就报错 KeyboardInterrupt 停止了。

import timedef main():    print('before ...')    time.sleep(10)    print('after ...')if __name__ == '__main__':    main()    print('the end')
root@master ~/w/python3_learning# python3 test.py before ...^CTraceback (most recent call last):  File "test.py", line 11, in 
main() File "test.py", line 6, in main time.sleep(10)KeyboardInterrupt

但是有时候,我们希望用户在 Ctrl + C 之后再继续执行一些清理操作。

import sysimport timedef suppress_keyboard_interrupt_message():    old_excepthook = sys.excepthook    def new_hook(exctype, value, traceback):        if exctype != KeyboardInterrupt:            old_excepthook(exctype, value, traceback)        else:            print('\nKeyboardInterrupt ...')            print('do something after Interrupt ...')    sys.excepthook = new_hookdef main():    print('before ...')    time.sleep(10)    print('after ...')if __name__ == '__main__':    suppress_keyboard_interrupt_message()    main()    print('the end')
root@master ~/w/python3_learning# python3 test.py before ...^CKeyboardInterrupt ...do something after Interrupt ...

转载地址:http://zsjqi.baihongyu.com/

你可能感兴趣的文章
Inside XSLT
查看>>
Python & XML
查看>>
Java Cryptography
查看>>
J2EE Best Practices: Java Design Patterns, Automation, and Performance
查看>>
Mastering AspectJ: Aspect-Oriented Programming in Java
查看>>
Mastering Jakarta Struts
查看>>
Java and XSLT
查看>>
Learning PHP 5
查看>>
Building Java Enterprise Applications Volume I: Architecture
查看>>
Microsoft SQL Server 2000 Weekend Crash Course
查看>>
Struts: The Complete Reference
查看>>
Complex IT Project Management: 16 Steps to Success
查看>>
Project Risk Management Guidelines : Managing Risk in Large Projects and Complex Procurements
查看>>
SQL for Microsoft Access
查看>>
Visual Basic 2005 Express: Now Playing
查看>>
Jakarta Struts Cookbook
查看>>
AspectJ Cookbook
查看>>
IntelliJ IDEA in Action
查看>>
HTML Professional Projects
查看>>
Python Cookbook, Second Edition
查看>>