I have a class A with a function foo() that logs information for an infinite time. I would like to execute this function for 30 sec, retrieving these logs. For the recovery of the logs, I base myself on this article, the logs being realized at the C level.
So I realized, in addition to the code of the previous article, this portion of code, allowing to stop the execution of the function after 30 seconds.
if __name__ == '__main__':
f = io.BytesIO()
with stdout_redirector(f):
p = multiprocessing.Process(target=A.foo, name="myfunc")
p.start()
# Cleanup
p.join(30)
if p.is_alive():
# Terminate foo
p.terminate()
p.join()
data = f.getvalue().decode('utf-8')
This works fine as is. However, I can't get this portion of the code into a fastAPI endpoint. Indeed, no matter what I try, errors around the multiprocessing appear. Either the endpoint returns nothing, or a Pickle error appears... I don't know what to do!
Here I use multiprocessing only to stop foo() after a while; maybe there is another way to avoid problems with fastAPI. Does anyone have a way to fix my problem?
EDIT #1
Based on Brandt's suggestion, the following function was done (Using windows, I can't use signals.):
@timeout_decorator.timeout(30, use_signals=False)
def run_func(func):
f = io.BytesIO()
with stdout_redirector(f):
func()
return f.getvalue().decode('utf-8')
And the following endpoint :
@app.get('/foo')
def get_foo():
data = run_func(A.foo)
return {'data' : data}
but the EOFError: Ran out of input
is triggered by thetimeout_decorator module.