1

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()

3 Answers 3

1

You have error in your Timer initialization. You places coroutine object, but you need callable function instead.

Change initialization from

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

to

timer = Timer(interval=1, first_immediately=True, callback=test)
Sign up to request clarification or add additional context in comments.

Comments

1

It seems like you are calling test rather than passing the coroutine test in places where you expecting a value. The result of test() (calling test) is a coroutine object that is never awaited. Therefore, you should treat test like a value rather than a function which you are calling.

Relevant lines to look at:

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

2 Comments

ensure_future requires Corouitine or Future, not 'function'.
so the line asyncio.ensure_future(test()) should then be changed to asyncio.ensure_future(test) too?
0

You should pass test instead of test() to callback kwarg otherwise, test() returns a coroutine object that is never awaited (thus the RuntimeWarning you are getting at the Timer(interval=1, first_immediately=True, callback=test()) line and the 'coroutine' object is not callable error you are getting due to the await self._callback(self) line)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.