在Jupyter上启动python脚本作为后台作业 [英] Launching a python script as a background job on Jupyter

查看:304
本文介绍了在Jupyter上启动python脚本作为后台作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在木星笔记本中将*.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后台作业旨在将任一纯代码运行到

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 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脚本作为后台作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆