I'm using sympy in my web-based project.
Specifically, I need to calculate integral.
However, I need to limit time and interrupt function.
Code, that I use.
import multiprocessing
class RunableProcessing(multiprocessing.Process):
def __init__(self, func, *args, **kwargs):
self.queue = multiprocessing.Queue(maxsize=1)
args = (func,) + args
multiprocessing.Process.__init__(self, target=self.run_func, args=args, kwargs=kwargs)
def run_func(self, func, *args, **kwargs):
try:
result = func(*args, **kwargs)
self.queue.put((True, result))
except Exception as e:
self.queue.put((False, e))
def done(self):
return self.queue.full()
def result(self):
return self.queue.get()
def timeout(seconds, func, *args, **kwargs):
proc = RunableProcessing(func, *args, **kwargs)
proc.start()
proc.join(seconds)
if proc.is_alive():
proc.terminate()
raise TimeoutException
success, result = proc.result()
if success:
return result
else:
raise result
And here is simple part for integration
def wrapper(f,var):
#do stuff
def int_wrapper(f, var):
return f.integrate(var)
try:
sol = timeout(10, wrapper, f, var)
except TimeoutException:
print('timeout')
try:
sol = timeout(10, int_wrapper, f, var)
except Exception:
pass
However, there is weird thing.
I use django and when I access page for example with function x, it correctly outputs x^2/2, but when I access same page withour reloading server and wrapper raises timeout, for example, on f=sin(x)**120, integrate incorrrectly outputs x sin(x)**120.
I guess x under sine and integration x are different due to multiprocessing. Can somebody clarify situation? Maybe, there is problem with globals?