Python in javascript (Brython) execute function with timeout

185 views Asked by At

I'm trying to execute a python function with a timeout, I've found some good ideas on stackoverflow but they don't seem to work for me as I'm executing the python function from javascript (using Brython) and multithreading/sleep don't work well (no sleep function in javascript). Any idea relatively easy to implement that would allow me to terminate a function if its execution takes more than 10s (see logic below):

def function_to_execute:
    print("function executing")

time_out=10
exec(function_to_execute)
time_function_started=time()
if time()>(time_function_startedtime_out) and function_to_execute not complete: (simplified for clarity)
    function_to_execute.terminate()

Thanks,

1

There are 1 answers

1
danangjoyoo On

The solution that I know is by using 2 thread worker and kill it. one worker for running the function, another one for maintain the running time.

I think you can use python-worker (link)

import time
from worker import worker

@worker
def run_with_limit(worker_object, timeout):
    time.sleep(timeout)
    worker_object.abort()

@worker
def my_controlled_function(a, b, c):
   ...

## then you can run it

run_with_limit(my_controlled_function(1, 2, 3), timeout=10)

if you dont want to use time.sleep you have an alternative like this

@worker
def run_with_limit(worker_object, timeout):
    while 1:
        if worker_object.work_time >= 10:
            worker_object.abort()
            break