break/interrupt a time.sleep() in python

后端 未结 6 1465
猫巷女王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:06

    The most elegant solution is certainly threading.Event, though if you only need a quick hack, this code works well :

    import time
    
    def main():
        print("It’s time !")
    
    if __name__ == "__main__":
        print("press ctrl-c to stop")
        loop_forever = True
        while loop_forever:
            main()
            try:
                time.sleep(60)
            except KeyboardInterrupt:
                loop_forever = False
    

提交回复
热议问题