带Autobahn、ApplicationRunner和ApplicationSession的多线程

2024-04-28 23:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

python-running-autobahnpython-asyncio-websocket-server-in-a-separate-subproce

can-an-asyncio-event-loop-run-in-the-background-without-suspending-the-python-in

试图解决我的问题与这两个链接以上,但我没有。在

我有以下错误:运行时错误:线程“thread-1”中没有当前事件循环。

下面是代码示例(Python3):

from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner
from asyncio import coroutine
import time
import threading


class PoloniexWebsocket(ApplicationSession):

    def onConnect(self):
        self.join(self.config.realm)

    @coroutine
    def onJoin(self, details):

        def on_ticker(*args):
            print(args)

        try:
            yield from self.subscribe(on_ticker, 'ticker')

        except Exception as e:
            print("Could not subscribe to topic:", e)


def poloniex_worker():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexWebsocket)


def other_worker():
    while True:
        print('Thank you')
        time.sleep(2)


if __name__ == "__main__":
    polo_worker = threading.Thread(None, poloniex_worker, None, (), {})
    thank_worker = threading.Thread(None, other_worker, None, (), {})

    polo_worker.start()
    thank_worker.start()

    polo_worker.join()
    thank_worker.join()

所以,我的最终目标是在开始时启动2个线程。只有一个需要使用ApplicationSession和ApplicationRunner。谢谢您。在


Tags: infromimportselfnoneasynciodefpoloniex
1条回答
网友
1楼 · 发布于 2024-04-28 23:18:43

一个单独的线程必须有它自己的事件循环。因此,如果poloniex_worker需要监听websocket,它需要自己的事件循环:

def poloniex_worker():
    asyncio.set_event_loop(asyncio.new_event_loop())
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexWebsocket)

但是如果您在Unix机器上,如果您尝试这样做,您将面临另一个错误。autobahnasyncio使用Unix信号,但是那些Unix信号只在主线程中工作。如果不打算使用Unix信号,您可以简单地关闭它们。为此,您必须转到定义ApplicationRunner的文件。那就是王八蛋在python3.5>;site packages>;autobahn>;asyncio on my machine中。您可以注释掉代码的信号处理部分,如下所示:

^{pr2}$

所有这些都是大量的工作。如果您不一定需要在与主线程分开的线程中运行应用程序会话,那么最好只在主线程中运行ApplicationSession。在

相关问题 更多 >