I am using Python 3.5.2 on windows.
I would like to run a python script but guarantee that it will not take more than N seconds. If it does ta
If the parent thread is the root thread, you may want to try os._exit(0)
.
import os
import threading
import time
def may_take_a_long_time(name, wait_time):
print("{} started...".format(name))
time.sleep(wait_time)
print("{} finished!.".format(name))
def kill():
time.sleep(3)
os._exit(0)
kill_thread = threading.Thread(target=kill)
kill_thread.start()
may_take_a_long_time("A", 2)
may_take_a_long_time("B", 2)
may_take_a_long_time("C", 2)
may_take_a_long_time("D", 2)
You can use _thread.interrupt_main (this module is called thread
in Python 2.7):
import time, threading, _thread
def long_running():
while True:
print('Hello')
def stopper(sec):
time.sleep(sec)
print('Exiting...')
_thread.interrupt_main()
threading.Thread(target = stopper, args = (2, )).start()
long_running()