【问题标题】:asyncio and gevent loops - how to communicate between each other?asyncio 和 gevent 循环 - 如何相互通信?
【发布时间】:2017-11-12 18:23:46
【问题描述】:

我正在尝试基于现有库在两个协议之间建立桥梁,基本上是基于事件(例如传输消息或宣布它)做一些事情。问题是一个库使用 Gevent 循环,另一个使用 Asyncio 循环,所以我无法使用内置循环功能在另一个循环上执行信号/事件操作,并且基本上无法访问另一个环形。

如何在它们之间建立基于事件的通信?我似乎无法从现有循环中访问另一个循环。我觉得想多了。 有没有办法通过多线程在循环之间共享对象来做到这一点?

示例代码:

import libraryBot1
import libraryBot2

bot1 = libraryBot1.Client()
bot2 = libraryBot2.Client()

@bot1.on('chat_message')
def handle_message(user, message_text):
    bot2.send(message_text)

@bot2.on('send')
def handle_message(message_text):
    print(message_text)

if __name__ == "__main__"
    # If I login here, then its run_forever on behind the scenes
    # So I cant reach second connection
    bot1.login(username="username", password="password")

    # Never reached
    bot2.login(username="username", password="password")

如果我在另一边尝试使用多线程,那么它们都已启动,但它们无法相互访问(通信)。

【问题讨论】:

  • 可以添加相关的代码吗?
  • 添加了一些示例代码,希望对理解我的问题有所帮助。

标签: python python-3.x python-asyncio gevent coroutine


【解决方案1】:

这是一个仅使用 gevent 的示例。可以用与 asyncio 兼容的方式包装 greenlets:

import gevent
from gevent.pool import Pool
from gevent.event import AsyncResult

a = AsyncResult()
pool = Pool(2)

def shared(stuff):
    print(stuff)

pool.map(bot1.login, username="username", password="password", event=a, shared=shared)
pool.map(bot2.login, username="username", password="password", event=a, shared=shared)

# and then in both you could something like this

if event.get() == 'ready':
    shared('some other result to share')

相关:

【讨论】:

  • 值得注意的是,aiogevent 已从 PyPI 中删除,仅其 repo 的分支仍然存在。
  • @killthrush 感谢您的提醒。看起来像是关于将克隆的 repos 滚动到 gevent 的一些讨论:github.com/gevent/gevent/issues/982
猜你喜欢
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 2018-04-17
  • 2012-12-05
  • 1970-01-01
  • 2013-08-04
  • 2012-03-22
  • 2011-06-21
相关资源
最近更新 更多