I have a Python program that consists of several modules. T开发者_开发技巧he "main" module creates a file variable log_file
for logging the output; all the other modules would need to write to that file as well.
However, I don't want to import the "main" module into other modules, since it would be a really weird dependency (not to mention it might not even work due to circular dependency).
Where, then, should I store the log_file
variable?
EDIT:
Following @pyfunc answer - would this be ok:
--- config.py ---
# does not mention log_file
# unless it's required for syntax reasons; in which case log_file = None
# ...
--- main.py ---
from datetime import datetime
import config.py
log_filename = str(datetime.now()) + '.txt'
config.log_file = open(log_filename, 'w')
# ...
--- another_module.py ---
import config.py
# ...
config.log_file.write(some_stuff)
Put the "global" variable in a "settings" module.
settings.py
log_file = "/path/to/file"
main.py
import settings
import logging
logging.basicConfig(filename=settings.log_file,level=logging.DEBUG)
logging.debug("This should go to the log file")
other_module.py
import logging
logging.debug("This is a message from another place.")
While the logging module may solve your immediate problem and many others, the settings module pattern is useful for a lot of other things besides log file names. It is used by Django to configure just about everything.
One way is to take all that code into another module so that you could import it in main file and other modules as well.
Hope you have checked on : http://docs.python.org/library/logging.html
精彩评论