如何调用一个类中包含的异步函数?

如何调用一个类中包含的异步函数?,第1张

如何调用一个类中包含的异步函数

最后,我可以找到正确的方法(特别感谢 @dirn

#!/usr/bin/env python3import sys, jsonimport asynciofrom websockets import connectclass EchoWebsocket:    async def __aenter__(self):        self._conn = connect('wss://ws.binaryws.com/websockets/v3')        self.websocket = await self._conn.__aenter__()     return self    async def __aexit__(self, *args, **kwargs):        await self._conn.__aexit__(*args, **kwargs)    async def send(self, message):        await self.websocket.send(message)    async def receive(self):        return await self.websocket.recv()class mtest:    def __init__(self):        self.wws = EchoWebsocket()        self.loop = asyncio.get_event_loop()    def get_ticks(self):        return self.loop.run_until_complete(self.__async__get_ticks())    async def __async__get_ticks(self):        async with self.wws as echo: await echo.send(json.dumps({'ticks_history': 'R_50', 'end': 'latest', 'count': 1})) return await echo.receive()

这在main.py中:

from testws import *a = mtest()foo = a.get_ticks()print (foo)print ("async works like a charm!")foo = a.get_ticks()print (foo)

这是输出

root@ubupc1:/home/dinocob# python3 test.py{"count": 1, "end": "latest", "ticks_history": "R_50"}async works like a charm!{"count": 1, "end": "latest", "ticks_history": "R_50"}

任何改进的技巧都值得欢迎!;)



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5653558.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存