首页 > 解决方案 > Python:登录模块脚本以在另一个脚本中调用

问题描述

我有大约 15 个用于应用程序开发的不同 python 脚本,其中 10 个包括用于调试目的的日志记录。现在有一个主脚本说“hutextract.py”,它以文件名作为参数运行。以前,日志文件名固定为“test.log”。现在我想创建与输入文件名同名的日志文件(扩展名除外)。我的“hutextract.py”代码,其中“randpage”和“mandate”是其他python脚本:

from randpage import genrand
from mandatebase import formext
...# importing other scripts, functions
import logging

file_name=sys.argv[1]
def return_log_name():
    return ".".join(file_name.split("/")[-1].split(".")[:-1]) + ".log"

log_file_name = return_log_name()

logging.basicConfig(filename=log_file_name, level=logging.DEBUG, format="%(asctime)s:%(levelname)s:%(message)s")

在 randpage.py、taskbase.py 和其他脚本中,还包括日志记录:

import logging
from hutextract import return_log_name
log_file_name = return_log_name()
logging.basicConfig(filename=log_file_name, level=logging.DEBUG, format="%(asctime)s:%(levelname)s:%(message)s")

这会产生一个错误,当我们尝试使用调用其他脚本(及其函数)的参数运行 hutextract.py 时,该错误很明显,这些脚本再次从 hutextract.py 调用 return_log_name 函数以进行日志记录:

Traceback (most recent call last):
 File "hutextract.py", line 3, in <module>
    from randpage import genrand
 File "/home/src/randpage.py", line 3, in <module>
    from mandate_final import sigext
 File "/home/src/mandate_final.py", line 5, in <module>
    from hutextract import return_log_name
 File "/home/src/hutextract.py", line 3, in <module>
    from randpage import genrand
ImportError: cannot import name 'genrand'

如何在所有模块脚本中进行日志记录以保存与作为参数给出的输入文件名相同名称的日志文件?

标签: pythonpython-3.xloggingmodule

解决方案


您提供的错误是由于循环导入。你可能会在回溯中看到这个圆圈hutextract.py- randpage.py- mandate_final.py-hutextract.py

现在到日志记录。您应该logging.basicConfig(...)在多个脚本中(在启动脚本中)只使用一次,因为这行代码修改了所谓的日志记录模块的根记录器。此根记录器是在您首次导入日志记录模块时创建的,它位于全局范围内。因此,根记录器始终可用 - 只需logging.debug('message')在需要的时间和地点使用它。


推荐阅读