Sorry for the (possible) misleading title, I struggled a bit to find a correct way of presenting things.
I have the following problem. I'm about to send some scripts running on a server, and I want to avoid breaking it with scripts that might be running too long.
Imagine I have a function foo(args) that returns a tuple tup. I wish for the following behavior :
- if the execution time of
foo(args)exceeds a valuetimeout, I want to return[timeout,(,)] - otherwise, I want to return
[execution_time, tup]
I am aware of this How to limit execution time of a function call?_ and especially the answer of Ariel Cabib introducing the run_with_limited_time procedure, as well as the existence of Queues, but I didn't manage to find a proper way to make them working to return the tuples as indicated above.
So far, my code would work like this :
from multiprocessing import Process, Queue
import time
def run_with_limited_time(func, args, kwargs, time): # as defined in the linked question above by Ariel Cabib
"""Runs a function with time limit
:param func: The function to run
:param args: The functions args, given as tuple
:param kwargs: The functions keywords, given as dict
:param time: The time limit in seconds
:return: True if the function ended successfully. False if it was terminated.
"""
p = Process(target=func, args=args, kwargs=kwargs)
p.start()
p.join(time)
if p.is_alive():
p.terminate()
return False
return True
q= Queue()
def foo(args):
t=time.time()
# doing stuff
t = time.time()-t
q.put([t,tup])
if run_with_limited_time(foo, args,{},timeout):
result = q.get()
else:
result = [timeout,(,)]
Unfortunately, I cannot get it to work, the final q.get() seems to be lost in a infinite recursive loop.
I must also say that if I only want to return the execution time (forgetting about tup), it works perfectly :
q= Queue()
def foo(args):
t=time.time()
# doing stuff
t = time.time()-t
q.put(t)
if run_with_limited_time(foo, args,{},timeout):
result = q.get()
else:
result = timeout
Does anyone have an idea ? I'm not particularly attached to the run_with_limited_time function as far as the expected behavior can occur. Thanks!