【发布时间】:2022-01-19 00:36:14
【问题描述】:
假设我有这个简单的功能:
def fun():
for i in range(5):
print(i)
sleep(2)
我想在不中断主代码流的情况下在后台运行它,这可以实现吗?
我尝试将代码保存在 test.py 中并做到了:
from IPython.lib.backgroundjobs import BackgroundJobFunc
with open('test.py') as code:
job = BackgroundJobFunc(exec, code.read())
result = job.run()
它打印 0 并退出。 我也试过了:
from subprocess import Popen, PIPE
process = Popen(['python', 'test.py.py'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print(stdout)
和
from threading import Thread
thread = Thread(target = fun)
thread.start()
thread.join()
print("thread finished...exiting")
两者都阻塞了主进程。在它完成执行之前无法做任何事情。 有什么不同的方法吗?
【问题讨论】:
-
在一定程度上你可以像this answer那样使用asyncio。您可能还对akernel(Jupyter 的异步 Python 内核)感兴趣。
标签: python jupyter-notebook ipython jupyter jupyter-lab