标签: 信号处理

  • python捕获ctrl+c中断的两种方法

    1,try…except…

        try:
            while True:
                time.sleep(100)
        except KeyboardInterrupt:
            print('Got signal: SIGINT, shutting down.')
            exit(0)
    

    2, 信号处理

    def handler(signal_received, frame):
        # Handle any cleanup here
        if signal_received == signal.SIGINT:
            print('SIGINT or CTRL-C detected. Exiting gracefully')
            exit(0)
    if __name__ == '__main__':
        signal.signal(signal.SIGINT, handler=handler) # ctlr + c
    

    建议用try…except的方法,通用性强,代码易读性高。

    Views: 61