I read a lot of posts about using threads, subprocesses, etc. A lot seems complicated for what I'm trying to do ...
All I want to do is stop the function after X time.
def big_loop(bob): x = bob start = time.time() while True: print time.time()-start
This function is an endless loop that never throws any errors or exceptions, period. I'm not sure about the difference between "commands, shells, subprocesses, threads, etc." And this function, so I am having problems managing subprocesses.
I found this code here and tried it, but as you can see, it continues to print after 10 seconds:
import time import threading import subprocess as sub import time class RunCmd(threading.Thread): def __init__(self, cmd, timeout): threading.Thread.__init__(self) self.cmd = cmd self.timeout = timeout def run(self): self.p = sub.Popen(self.cmd) self.p.wait() def Run(self): self.start() self.join(self.timeout) if self.is_alive(): self.p.terminate() self.join() def big_loop(bob): x = bob start = time.time() while True: print time.time()-start RunCmd(big_loop('jimijojo'), 10).Run()
In what a simple way this function can be killed. As you can see in my attempt above, it does not end after 20 seconds and just continues ...
*** OH too, I read about using the alarm, but I'm on the windows, so I can’t use the alarm function. (python 2.7)
** suppose that an "infinitely executing function" cannot be changed or changed without infinity, if I could change the function, well, I would just change it to infinity, right?
Here are some similar questions that I couldn’t move through my code to work with my simple function: Perhaps you can?
Python: kill or terminate a subprocess when timeout
replacing signal.alarm on Windows [Python]
Ok, I tried to get the answer, it works. But how can I use it if I delete the if __name__ == "__main__":
? When I delete this statement, the cycle never ends as before.
import multiprocessing import Queue import time def infinite_loop_function(bob): var = bob start = time.time() while True: time.sleep(1) print time.time()-start print 'this statement will never print' def wrapper(queue, bob): result = infinite_loop_function(bob) queue.put(result) queue.close()