我有一个由多个模块组成的 Python 程序。 “main”模块创建一个文件变量log_file
用于记录输出;所有其他模块也需要写入该文件。
但是,我不想将“主”模块导入到其他模块中,因为这将是一个非常奇怪的依赖项(更不用说由于循环依赖它甚至可能无法工作)。
那么,我应该在哪里存储log_file
多变的?
EDIT:
以下 @pyfunc 回答 - 这样可以吗:
--- 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)
将“全局”变量放入“设置”模块中。
设置.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")
其他模块.py
import logging
logging.debug("This is a message from another place.")
虽然记录模块 http://docs.python.org/library/logging.html可能会解决您眼前的问题和许多其他问题,除了日志文件名之外,设置模块模式对于许多其他事情也很有用。 Django 使用它来配置几乎所有内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)