协程作为Jupyter笔记本中的后台作业 [英] Coroutine as background job in Jupyter notebook

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

问题描述

我有一个协程,我想在Jupyter笔记本中作为后台作业"运行.我已经看到使用线程完成此操作的方式,但是我想知道是否也有可能参与笔记本的活动循环.

I have a coroutine which I'd like to run as a "background job" in a Jupyter notebook. I've seen ways to accomplish this using threading, but I'm wondering whether it's also possible to hook into the notebook's event loop.

例如,说我有以下课程:

For example, say I have the following class:

import asyncio
class Counter:
    def __init__(self):
        self.counter = 0

    async def run(self):
        while True:
            self.counter += 1
            await asyncio.sleep(1.0)

t = Counter()

,我想执行run方法(无限循环),同时仍然可以随时检查t.counter变量.有什么想法吗?

and I'd like to execute the run method (which loops indefinitely), while still being able to check the t.counter variable at any point. Any ideas?

推荐答案

以下内容基本上可以满足我的要求,但是它确实使用了单独的线程.但是,我仍然可以使用异步原语.

The following basically does what I want I think, but it does use a separate thread. However, I can still use the async primitives.

def run_loop():
    loop = asyncio.new_event_loop()
    run_loop.loop = loop
    asyncio.set_event_loop(loop)
    task = loop.create_task(t.run())
    loop.run_until_complete(task)

from IPython.lib import backgroundjobs as bg
jobs = bg.BackgroundJobManager()
jobs.new('run_loop()')
loop = run_loop.loop # to access the loop outside

这篇关于协程作为Jupyter笔记本中的后台作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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