Currently, I am producing a WebSocket client in python using asyncio that connects to a server every second until I interrupt it with my keyboard and outputs the response from the server to a .csv file. When I run the script, It successfully runs, but I get this in my terminal:
'coroutine' object is not callable
When I press Ctrl + c to abort the code, I get the following:
sys:1: RuntimeWarning: coroutine 'test' was never awaited
What is the issue here and how do I resolve it? Mypython code is given below:
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()