End python code after 60 seconds

后端 未结 5 1303
甜味超标
甜味超标 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:29

    Use signal.ALARM to get notified after a specified time.

    import signal, os
    
    def handler(signum, frame):
        print '60 seconds passed, exiting'
        cleanup_and_exit_your_code()
    
    # Set the signal handler and a 60-second alarm
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(60)
    
    run_your_code()
    

    From your example it is not obvious what the code will exactly do, how it will run and what kind of loop it will iterate. But you can easily implement the ALARM signal to get notified after the timeout has expired.

提交回复
热议问题