首页 > 解决方案 > python asyncio WebSocket客户端中的“'coroutine'对象不可调用”

问题描述

目前,我正在使用 asyncio 在 python 中生成一个 WebSocket 客户端,该客户端每秒连接到服务器,直到我用键盘中断它并将服务器的响应输出到 .csv 文件。当我运行脚本时,它成功运行,但我在终端中得到了这个:

'coroutine' object is not callable

当我按 Ctrl + c 中止代码时,我得到以下信息:

sys:1: RuntimeWarning: coroutine 'test' was never awaited

这里有什么问题,我该如何解决?Mypython代码如下:

import asyncio
import websockets
import logging
import datetime
import time

starttime = time.time() # start value for timed data acquisition

logger = logging.getLogger('websockets')
logger.setLevel(logging.INFO)  #Switch to DEBUG for full error information
logger.addHandler(logging.StreamHandler())

class Timer: #class for asynchronous (non-blocking) counter
    def __init__(self, interval, first_immediately, callback):
        self._interval = interval
        self._first_immediately = first_immediately
        self._callback = callback
        self._is_first_call = True
        self._ok = True
        self._task = asyncio.ensure_future(self._job())
        print("init timer done")
    async def _job(self):
        try:
            while self._ok:
                if not self._is_first_call or not self._first_immediately:
                    await asyncio.sleep(self._interval)
                await self._callback(self)
                self._is_first_call = False
        except Exception as ex:
            print(ex)
    def cancel(self):
        self._ok = False
        self._task.cancel()


async def test():
    async with websockets.connect("ws://198.162.1.177:80/", ping_interval=None) as websocket:

        await websocket.send(str(1.001))  #send a message to the websocket server
        response = await websocket.recv() #wait to get a response from the server
        print(response)
        dataline_pv1 = datetime.datetime.today().isoformat() + "," + str(response) + "," + str(0) + "\n" # format and assemble data line
        file_name_pv1 = '{:%Y%m%d}'.format(datetime.datetime.today()) + "_flow.csv" # generate file name

        with open(file_name_pv1, "a") as etherm_file1: # append dataline to file
            etherm_file1.write(dataline_pv1)
            
        
#asyncio.get_event_loop().run_forever(test()) # run until test() is finished while True:
timer = Timer(interval=1, first_immediately=True, callback=test())

loop = asyncio.get_event_loop()
try:
    asyncio.ensure_future(test())
    loop.run_forever()
except KeyboardInterrupt:
    timer.cancel()
    pass
finally:
    print("Closing Loop")
    loop.close()

标签: pythonasynchronouswebsocketpython-asyncio

解决方案


您的Timer初始化有错误。您放置协程对象,但您需要可调用函数。

更改初始化从

timer = Timer(interval=1, first_immediately=True, callback=test())

timer = Timer(interval=1, first_immediately=True, callback=test)

推荐阅读