python日志内容存储到文件里,哪里在python中存储日志文件名?

本文讨论了一个Python程序中多个模块如何共享一个日志文件的问题。为了避免导入主模块造成依赖混乱,作者提出了一种通过配置模块来间接引用日志文件的方法,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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)

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值