IPython:在后台异步运行命令

17 投票
3 回答
9049 浏览
提问于 2025-04-17 22:48

假设我有一个Python命令或脚本,我想在IPython会话中异步运行,也就是在后台运行。

我希望能够从我的IPython会话中调用这个命令,并在它完成时或者出错时收到通知。我不想让这个命令阻塞我的IPython提示符。

有没有什么IPython魔法命令可以支持这个?如果没有,推荐在IPython中如何运行本地的异步任务/脚本/命令呢?

比如,我有一个函数:

def do_something():
   # This will take a long time
   # ....
   return "Done"

它在当前的命名空间中。我该如何将它放到后台运行,并在完成时收到通知呢?

3 个回答

4

最通用的方法是使用 多进程模块。这个模块可以让你在后台调用当前脚本中的函数,也就是在一个全新的进程中运行。

编辑 这可能不是最优雅的方法,但应该能完成任务。

import time
from multiprocessing import Process, Pipe
ALONGTIME = 3

def do_something(mpPipe):
    # This will take a long time
    print "Do_Something_Started"
    time.sleep(ALONGTIME)
    print "Do_Something_Complete"
    mpPipe.send("Done")

if __name__ == "__main__":
    parent_conn, child_conn = Pipe()
    p = Process(target=do_something, args=(child_conn,))
    p.start()
    p.join() # block until the process is complete - this should be pushed to the end of your script / managed differently to keep it async :)
    print parent_conn.recv() # will tell you when its done.
6

以前在iPython中有一个很神奇的功能,可以让你做到这一点:

https://github.com/ipython/ipython/wiki/Cookbook:-Running-a-file-in-the-background

不过,这个功能似乎被删掉了,现在还在等着在新版本中回来:

https://github.com/ipython/ipython/issues/844

不过,它仍然提供了一个库,可以帮助你实现这个功能:

http://ipython.org/ipython-doc/rel-0.10.2/html/api/generated/IPython.background_jobs.html

10

好的,试试在一个单元格里输入:

%%script bash --bg --out script_out

sleep 10
echo hi!

脚本魔法的相关内容和其他IPython的魔法一起有详细说明。这里需要的参数是 -bg,这样可以让下面的脚本在后台运行,也就是异步运行,而不是在前台同步运行。

GitHub问题 #844 现在已经解决了。

撰写回答