哪里在python中存储日志文件名? [英] where to store a log file name in python?

查看:196
本文介绍了哪里在python中存储日志文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个模块的Python程序. "main"模块创建一个文件变量log_file来记录输出.其他所有模块也需要写入该文件.

I have a Python program that consists of several modules. The "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.

但是,我不想将"main"模块导入其他模块,因为这将是一个非常奇怪的依赖关系(更不用说由于循环依赖关系,它甚至可能无法工作).

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).

那么,我应该在哪里存储log_file变量?

Where, then, should I store the log_file variable?

在@pyfunc后面回答-这样可以吗:

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)

推荐答案

一种方法是将所有代码带入另一个模块,以便可以将其导入主文件和其他模块中.

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.

希望您已检查: http://docs.python.org/library/logging. html

这篇关于哪里在python中存储日志文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆