End python code after 60 seconds

后端 未结 5 1213
甜味超标
甜味超标 2021-01-15 04:14

Below there is some fully functioning code.

I am planning to execute this code through command line, however I would like it to end after 60 seconds.

Does an

5条回答
  •  一整个雨季
    2021-01-15 04:44

    Try this out:

    import os
    import time
    from datetime import datetime
    from threading import Timer
    
    def exitfunc():
        print "Exit Time", datetime.now()
        os._exit(0)
    
    Timer(5, exitfunc).start() # exit in 5 seconds
    
    while True: # infinite loop, replace it with your code that you want to interrupt
        print "Current Time", datetime.now()
        time.sleep(1)
    

    There are some more examples in this StackOverflow question: Executing periodic actions in Python

    I think the use of os._exit(0) is discouraged, but I'm not sure. Something about this doesn't feel kosher. It works, though.

提交回复
热议问题