Let suppose I have this simple function:
def fun():
for i in range(5):
print(i)
sleep(2)
and I want to run it in background without interrupting the main code flow, is this achievable?
I tried saving the code in test.py
and did:
from IPython.lib.backgroundjobs import BackgroundJobFunc
with open('test.py') as code:
job = BackgroundJobFunc(exec, code.read())
result = job.run()
It printed 0 and exited. I also tried:
from subprocess import Popen, PIPE
process = Popen(['python', 'test.py.py'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print(stdout)
and
from threading import Thread
thread = Thread(target = fun)
thread.start()
thread.join()
print("thread finished...exiting")
Both blocked the main process. Could not do anything before it finished it's execution. Is there a different way?