break/interrupt a time.sleep() in python

后端 未结 6 1484
猫巷女王i
猫巷女王i 2020-12-01 03:30

I need to break from time.sleep() using ctrl c.

While 1:
    time.sleep(60)

In the above code when the control enters time.sleep function a

6条回答
  •  广开言路
    2020-12-01 04:01

    The KeyboardInterrupt exception is raised when a user hits the interrupt key, Ctrl-C. In python this is translated from a SIGINT signal. That means, you can get handle it however you want using the signal module:

    import signal
    
    def handler(signum, frame):
        print("do whatever, like call thread.interrupt_main()")
    
    signal.signal(signal.SIGINT, handler)
    print("Waiting for SIGINT...")
    signal.pause()
    

    That way, you can do whatever you want at the receipt of a keyboard interrupt.

提交回复
热议问题