【问题标题】:Running a small python program in background inside Jupyter notebook without blocking the main process在 Jupyter notebook 的后台运行一个小的 python 程序,而不阻塞主进程
【发布时间】: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


【解决方案1】:

创建一个守护线程解决了这个问题(其中一个问题是它会打印您当前正在打印/工作的cell 中的值

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

对此有何更正/建议?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多