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

harrison4:

基于此答案,我想在一个将从另一个文件导入的类中构建一个异步websoket客户端:

#!/usr/bin/env python3

import sys, json
import asyncio
from websockets import connect

class EchoWebsocket:
    def __await__(self):
        # see: https://stackoverflow.com/a/33420721/1113207
        return self._async_init().__await__()

    async def _async_init(self):
        self._conn = connect('wss://ws.binaryws.com/websockets/v3')
        self.websocket = await self._conn.__aenter__()
        return self

    async def close(self):
        await self._conn.__aexit__(*sys.exc_info())

    async def send(self, message):
        await self.websocket.send(message)

    async def receive(self):
        return await self.websocket.recv()

class mtest:
    async def start(self):
        try:
            self.wws = await EchoWebsocket()
        finally:
            await self.wws.close()

    async def get_ticks(self):
        await self.wws.send(json.dumps({'ticks_history': 'R_50', 'end': 'latest', 'count': 1}))
        return await self.wws.receive()

if __name__ == '__main__':
    a = mtest()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(a.start())

然后将其导入中main.py,其中包含以下内容:

from testws import *

a = mtest()
print (a.get_ticks())
print ("this will be printed after the ticks")

但是它检索到以下错误:

root@ubupc1:/home/dinocob# python3 test.py
<coroutine object hello.get_ticks at 0x7f13190a9200>
test.py:42: RuntimeWarning: coroutine 'mtest.get_ticks' was never awaited
  print (a.get_ticks())
this will be printed after the ticks

这是怎么回事?如果mtest.get_ticks开头是async单词,为什么我无法访问它def

harrison4:

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

#!/usr/bin/env python3

import sys, json
import asyncio
from websockets import connect

class 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"}

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Springt Boot中创建一个调用包含构造函数注入服务的测试?

如何以组方式调用一个异步函数?

在redux-thunk中在另一个内部调用一个异步函数

使用RxJS如何缓冲函数调用,直到解决了另一个异步函数调用

在同一个类中调用函数指针

如何在Angular 6中的另一个类中的一个类中调用函数?

无法在同一个类中调用函数

从Kivy中的另一个类调用函数

如何在python中的一个类中计算__repr__函数调用次数?

是否可以在另一个类中调用一个类的构造函数?

PHP如何从另一个类调用函数?

我如何从一个类中创建一个NSString函数然后调用它?

如何从jQuery中的另一个函数调用父类的函数

在Swift中从另一个类调用函数

如何在类中调用函数以在php中调用另一个类?

从另一个函数中调用类函数

如何从C#中其他同级类中的一个类调用同级类的函数

如何从另一个类调用函数?

如何在一个类中从另一个调用一个函数(方法)?

如何从一个类调用另一个类的函数?

从另一个类中的一个类调用函数

如何在 Selenium 中创建一个将从另一个类调用的 driver.get 函数?

如何从另一个类调用函数

我如何从包含我的对象的另一个类调用函数?

如何一个接一个地调用异步函数?

在另一个类中调用一个类的构造函数

在 JS 类的构造函数中调用一个获取初始数据的异步函数是否可以?

如何在另一个异步函数中调用异步函数

如何使用 3 个函数调用一个类?