2 years ago
#68540

prime_mover
Hitting Task exception was never retrieved while executing a signal handler using asyncio in Python3.6
I have a Python3.6 application that uses bleak lib for BLE communication. I need to handle Ctrl-C signal by disconnecting BLE and do some clean up in case user decides to terminate the script while the BLE connection is ON. However, when signal is received the script terminates without disconnecting and throws following error: Task exception was never retrieved
Following are the snippets from my code:
The disconnect function to be called during clean up:
async def disconnect(self):
ret = 1
try:
await self.client.stop_notify(self.rx_char)
status = await self.client.disconnect()
ret = 0 if status else -1
self.is_connected = False
except:
ret = -1
return ret
The signal handler to be executed:
async def sig_handler():
global data_file
logging.info("Ctrl-C/Ctrl-Z was pressed.")
if data_file != None:
data_file.close()
logging.info('Exiting...')
ret = await g_app.disconnect()
logging.info(f'Disconnected! ret {ret}')
asyncio.get_event_loop().stop()
exit(1)
The setting up of signal handler:
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.add_signal_handler(getattr(signal, 'SIGINT'), lambda: asyncio.ensure_future(sig_handler()))
loop.run_until_complete(main(sys.argv[1:]))
When I hit Ctrl-C, the script terminates with following traceback:
2022-01-19 12:25:34,041 - Ctrl-C/Ctrl-Z was pressed.
2022-01-19 12:25:34,042 - Exiting...
2022-01-19 12:25:34,043 - Disconnected! ret -1
2022-01-19 12:25:34,078 - Task exception was never retrieved
future: <Task finished coro=<sig_handler() done, defined at sensor_data.py:344> exception=SystemExit(1,)>
Traceback (most recent call last):
File "/usr/lib/python3.6/asyncio/base_events.py", line 475, in run_until_complete
self.run_forever()
File "/usr/lib/python3.6/asyncio/base_events.py", line 442, in run_forever
self._run_once()
File "/usr/lib/python3.6/asyncio/base_events.py", line 1462, in _run_once
handle._run()
File "/usr/lib/python3.6/asyncio/events.py", line 145, in _run
self._callback(*self._args)
File "sensor_data.py", line 353, in sig_handler
exit(1)
File "/usr/lib/python3.6/_sitebuiltins.py", line 26, in __call__
raise SystemExit(code)
SystemExit: 1
I am not sure what seems to be going wrong here. Looks like the disconnect func is being called by return error inside the signal handler, whereas this does not happen when disconnect is called from a coroutine.
signals
python-3.6
python-asyncio
0 Answers
Your Answer