Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: can't delete file after logging to

Tags:

python

I'm writing to log file using the following code:

import logging
from gmplot import gmplot
logging.basicConfig(filename="sample.log", level=logging.INFO)
logging.debug("This is a debug message")
logging.info("Informational message")
logging.error("An error has happened!")

But then it's impossible to delete this file. how can I 'release' this file?

like image 850
erez Avatar asked Jul 24 '26 12:07

erez


2 Answers

You need to close() your logging:

As explained there: python does not release filehandles to logfile

When your Run class completes, call:

handlers = self.log.handlers[:]
for handler in handlers:
    handler.close()
    self.log.removeHandler(handler)
like image 79
Luc Avatar answered Jul 27 '26 00:07

Luc


simply use logging.shutdown(), when you are done with logging.

like image 40
Kamlesh Avatar answered Jul 27 '26 00:07

Kamlesh