I/O Operation on closed file
Describe the bug
I am creating a script to asynchronously receive message and push it to a buffer which will be read by another async method. This receive method will continue running until a CTRL C is detected and shutdown the notifier stop the program.
My implementation is as follows
import can
import asyncio
from canine import CANineBus
from logging.handlers import TimedRotatingHandler
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
def get_console_handler():
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(FORMATTER)
return console_handler
def get_file_handler():
file_handler = TimedRotatingFileHandler(LOG_FILE, when='midnight')
file_handler.setFormatter(FORMATTER)
return file_handler
def get_logger(logger_name):
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
logger.addHandler(get_console_handler())
logger.addHandler(get_file_handler())
logger.propagate = False
return logger
async def packetConstructor(bus, reader):
while (True):
try:
# wait for reader to have message
msg = await asyncio.wait_for(reader.get_message(), timeout=1.0)
# Push msg to buffer
except asyncio.TimeoutError:
pass # prevent await blocking
async def main():
with can.Bus(interface='canine', bitrate=1000000) as bus:
reader = can.AsyncBufferedReader()
logger = can.Logger("canMsg.log")
listeners: list[MessageRecipient] = [
reader,
logger
]
notifier = can.Notifier(bus, listeners, loop=asyncio.get_running_loop())
try:
packetConstructor_task = asyncio.create_task(packetConstructor(bus, reader))
await packetConstructor_task
except asyncio.CancelledError:
log.debug("Shutting down notifier")
finally:
notifier.stop()
def handler(signal_received, frame):
log.critical("CTRL-c detected")
for task in asyncio.all_tasks():
task.cancel()
if __name__ == "__main__":
log = get_logger("fw_log")
signal(SIGINT, handler)
asyncio.run(main())
When I am receiving data and abruptly press Ctrl-c, it will show
2023-12-25 23:05:31,162 — fw_log — DEBUG — Received invalid ID
2023-12-25 23:05:31,324 — fw_log — DEBUG — Received invalid ID
2023-12-25 23:05:31,454 — fw_log — DEBUG — Received invalid ID
^C2023-12-25 23:05:31,533 — fw_log — CRITICAL — CTRL-c detected
2023-12-25 23:05:31,667 — fw_log — DEBUG — Shutting down notifier
Exception in callback Notifier._on_message_received(can.Message(t..., 0xff, 0xff]))
handle: <Handle Notifier._on_message_received(can.Message(t..., 0xff, 0xff]))>
Traceback (most recent call last):
File "/Users/marvinpranajaya/opt/anaconda3/envs/can-testing/lib/python3.12/asyncio/events.py", line 84, in _run
self._context.run(self._callback, *self._args)
File "/Users/marvinpranajaya/opt/anaconda3/envs/can-testing/lib/python3.12/site-packages/can/notifier.py", line 146, in _on_message_received
res = callback(msg)
^^^^^^^^^^^^^
File "/Users/marvinpranajaya/opt/anaconda3/envs/can-testing/lib/python3.12/site-packages/can/listener.py", line 43, in __call__
self.on_message_received(msg)
File "/Users/marvinpranajaya/opt/anaconda3/envs/can-testing/lib/python3.12/site-packages/can/io/canutils.py", line 197, in on_message_received
self.file.write(framestr)
ValueError: I/O operation on closed file.
CANineBus was not properly shut down
and the received can message will not be saved in the canMsg.log file
Additional context
OS and version: macos ventura Python version: 3.12.0 python-can version: 4.2.2 python-can interface/s (if applicable):
@pipipipi2002 thanks for reporting! Could you please edit your code example to include all imports / dependencies so that the issue can be easily reproduced?
Hi @Tbruno25 , Thank you for reaching out. Ive updated the imports in the code above.