3
Contributors
2
Replies
65
Views
3 Years
Discussion Span
Last Post by Gribouillis
0

you may use the Timer class, from the threading module :

import sys, threading

threading.Timer(5.0, lambda : sys.exit(0)).start()

will exit your program after 5 seconds

Edited by CrazyDieter

1

will exit your program after 5 seconds

This fails, but using os._exit(0) works, instead of sys.exit(0).

In my linux system, the following also works, which is very nice

import thread
import threading

threading.Timer(2.0, lambda : thread.interrupt_main()).start()

try:
    while True:
        print("stopme")
except KeyboardInterrupt:
    print("We're interrupted: performing cleanup action.")

""" my output:
...
stopme
stopme
stopme
stopme
stopme
We're interrupted: performing cleanup action.
$
"""

The nice thing is that we only plan to raise an exception in the main thread after a certain time instead of exiting directly. This is very pythonic.

Edited by Gribouillis

Votes + Comments
you're right, I prefer this way too
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.