我有一个由多个模块组成的 Python 程序。 “main”模块创建一个文件变量 log_file
用于记录输出;所有其他模块也需要写入该文件。
但是,我不想将“主”模块导入到其他模块中,因为这将是一个非常奇怪的依赖项(更不用说由于循环依赖项它甚至可能无法工作)。
那么,我应该在哪里存储 log_file
变量?
编辑:
按照@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"
主要.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.")
虽然 logging module可能会解决您眼前的问题和许多其他问题,设置模块模式对于除日志文件名之外的许多其他事情也很有用。 Django 使用它来配置几乎所有内容。
关于python - 在python中在哪里存储日志文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4090652/