在Jupyter上启动python脚本作为后台作业

编程入门 行业动态 更新时间:2024-10-15 08:21:08
本文介绍了在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后台作业旨在将任一纯代码运行到 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脚本作为后台作业

本文发布于:2023-11-28 18:17:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643452.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:作业   脚本   后台   Jupyter   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!