0

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?

Deshwal
  • 3,436
  • 4
  • 35
  • 94
  • To a degree you can use asyncio like in [this answer](https://stackoverflow.com/questions/63384326/how-to-update-interactive-figure-in-loop-with-jupyterlab/63517891#63517891). You may also be interested in [akernel](https://github.com/davidbrochart/akernel) (asynchronous Python kernel for Jupyter). – krassowski Jan 22 '22 at 01:32

1 Answers1

0

Creating a daemon thread solved the problem ( with one problem that it prints the value in cell you're currently printing / working)

 t1 = threading.Thread(target=fun)
 t1.setDaemon(True)
 t1.start()

Any corrections / suggestions to this?

Deshwal
  • 3,436
  • 4
  • 35
  • 94