我正在尝试在木星笔记本中将*.py文件作为后台服务运行.
I am trying to run a *.py file as a background service in Jupiter notebook.
from IPython.lib import backgroundjobs as bg jobs = bg.BackgroundJobManager() jobs.new(%run -i "script.py") # Not working jobs.new("script.py") # Not working推荐答案
Ipython/Jupyter后台作业旨在将任一纯代码运行到 eval (字符串)或函数.不支持文件和ipython magic命令.
Ipython/Jupyter background jobs is designed to run either plain code to eval (string), or function. Files and ipython magic commands is not supported.
您可以做的一件事就是简单地读取文件内容并将其传递给eval:
One thing you can do is to simply read file content and pass it to eval:
from IPython.lib.backgroundjobs import BackgroundJobFunc with open('script.py') as code: job = BackgroundJobFunc(exec, code.read()) result = job.run()BackgroundJobManager 几乎相同,但是有点更智能".
BackgroundJobManager is pretty much the same, but a little bit "smarter".
侧面说明:该接口背后的所有后台机械都在同一进程的线程中运行,并共享解释器状态和输出.因此,请紧记:
Side note: all background machinery behind this interfaces runs in threads of the same process and share interpreter state and output. So, just keep in mind:
- 这不适用于需要大量计算的脚本
- 永远不要以这种方式运行不受信任的代码-总体上适用于eval,但是在这种情况下,您可能会遇到永远无法使GIL返回前端"线程的情况.
- 避免使用stdout的脚本,很可能这些脚本会紧紧抓住您的主线程
- this is not suited for computational-heavy scripts
- never run untrusted code this way — this applies to eval overall, but in this case you can into situation when you'll never get GIL back to your "frontend" thread
- avoid scripts that use stdout, most probably those will clutch with your main thread
更多推荐
在Jupyter上启动python脚本作为后台作业
发布评论