How do I capture SIGINT in Python?

前端 未结 12 1782
长发绾君心
长发绾君心 2020-11-21 22:54

I\'m working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C sign

12条回答
  •  生来不讨喜
    2020-11-21 23:20

    Personally, I couldn't use try/except KeyboardInterrupt because I was using standard socket (IPC) mode which is blocking. So the SIGINT was cueued, but came only after receiving data on the socket.

    Setting a signal handler behaves the same.

    On the other hand, this only works for an actual terminal. Other starting environments might not accept Ctrl+C, or pre-handle the signal.

    Also, there are "Exceptions" and "BaseExceptions" in Python, which differ in the sense that interpreter needs to exit cleanly itself, so some exceptions have a higher priority than others (Exceptions is derived from BaseException)

提交回复
热议问题