栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

最后,我可以找到正确的方法(特别感谢 @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"}

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号