在 ipython/jupyter notebook 中运行单元的新线程 [英] a new thread for running a cell in ipython/jupyter notebook

查看:52
本文介绍了在 ipython/jupyter notebook 中运行单元的新线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时运行单个单元格需要很长时间,而在运行时,我想在同一个笔记本中编写和运行其他单元格,访问同一上下文中的变量.

Sometimes it takes a long time to run a single cell, while it is running, I would like to write and run other cells in the same notebook, accessing the variables in the same context.

是否有任何 ipython 魔法可以使用,当它被添加到一个单元时,运行该单元将自动创建一个新线程并使用笔记本中的共享全局数据运行?

Is there any ipython magic that can be used such that when it is added to a cell, running the cell will automatically create a new thread and run with shared global data in the notebook?

推荐答案

这可能不是答案,而是方向.我没有看到类似的东西,我仍然对这个感兴趣.

It may not be an answer, but rather the direction to it. I did not saw anything like that, still I'm interested in this too.

我目前的发现表明需要定义它的自定义单元格魔法.好的参考资料是文档中的custom cell magic section 和我会考虑的两个示例:

My current findings suggesting that one need to define it's own custom cell magic. Good references would be the custom cell magic section in the documentation and two examples that I would consider:

这两个链接都将代码包装在一个线程中.这可能是一个起点.

Both those links wrapping the code in a thread. That could be a starting point.

更新: github 上的 ngcm-tutorial 有后台作业类的描述

UPDATE: ngcm-tutorial at github has description of background jobs class

##github.com/jupyter/ngcm-tutorial/blob/master/Day-1/IPython%20Kernel/Background%20Jobs.ipynb
from IPython.lib import backgroundjobs as bg
jobs = bg.BackgroundJobManager()

def printfunc(interval=1, reps=5):
    for n in range(reps):
        time.sleep(interval)
        print('In the background... %i' % n)
        sys.stdout.flush()
    print('All done!')
    sys.stdout.flush()

jobs.new('printfunc(1,3)')
jobs.status()

更新 2:另一种选择:

from IPython.display import display
from ipywidgets import IntProgress

import threading

class App(object):
    def __init__(self, nloops=2000):
        self.nloops = nloops
        self.pb = IntProgress(description='Thread loops', min=0, max=self.nloops)

    def start(self):
        display(self.pb)
        while self.pb.value < self.nloops:
            self.pb.value += 1 
        self.pb.color = 'red'

app = App(nloops=20000)

t = threading.Thread(target=app.start)

t.start()
#t.join()

这篇关于在 ipython/jupyter notebook 中运行单元的新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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