开发者

Why isn't IDLE creating a new log file with logging module when being run again?

I was testing out some simple logging examples for Python's logging module in IDLE:

import logging

logging.basicConfig(level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s', filename='TESTLOG.log')

logging.deb开发者_如何学Cug('A debug message')

And it works as expected: A file called TESTLOG.log is created with the debug message.

But if I delete the log file while the IDLE script window is open, when I try to run the module again / f5, a new log file is not created. If I close the script window and then re-open and run it, the log file is created.

Conversely, if I run the script from the command line, the log file is always generated after I delete the log file and rerun the script.

What's the difference between the two situations?


The first time basicConfig is called it adds a Handler to the root logger in the logging module. Subsequent calls to basicConfig check to see if there is already a Handler in the root logger, and if there is then the call to basicConfig has no effect (i.e. it will not re-create the log file).

If you open an IDLE window and run your script, the logging module is loaded and the script configures the root logger with its call to basicConfig. Because you don't subsequently close the IDLE window, the logging module remains loaded and subsequent calls to basicConfig have no effect.

Closing and re-opening the IDLE window effectively fires up a new instance of python and the logging module must be reloaded and therefore the call to basicConfig has an effect. Similarly, running the script from the command line requires a new instance of python each time the script is run.


You don't say what operating system you're on, but I guess it isn't Windows, since you can't delete open files in Windows. On Linux, open files can be deleted, but the file hangs around until all open handles to it have been closed, then disappears. This seems consistent with what you're seeing: in the IDLE case, the file remains open as long as IDLE is running, so the file is really still there even though you've deleted it, until the IDLE process is terminated. In the case of scripts, they terminate each time, so the file is closed and when you delete it, it's really deleted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜