python - 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'
如何在所有模块脚本中进行日志记录以保存与作为参数给出的输入文件名相同名称的日志文件?
解决方案
您提供的错误是由于循环导入。你可能会在回溯中看到这个圆圈hutextract.py
- randpage.py
- mandate_final.py
-hutextract.py
现在到日志记录。您应该logging.basicConfig(...)
在多个脚本中(在启动脚本中)只使用一次,因为这行代码修改了所谓的日志记录模块的根记录器。此根记录器是在您首次导入日志记录模块时创建的,它位于全局范围内。因此,根记录器始终可用 - 只需logging.debug('message')
在需要的时间和地点使用它。
推荐阅读
- python - 调用 tabulate TypeError: 'tuple' object is not callable 后出现此错误
- angular - 在属性中存储来自 Angular 订阅的数据
- c# - 为什么可以将 Windows 特定的 Nugets 添加到 ASP.NET Core
- javascript - 将我的 if 条件转换为使用正则表达式选项切换大小写:javascript
- html - 当我使用
,内容消失(菜单和路由器出口) - postgresql - PostgreSQL 在部分索引中使用时间戳差异进行 upsert
- javascript - JSDoc 不显示参数表和返回值/名称/描述
- python - 使用其他行中的非唯一值从 Dataframe 行中提取值
- sql-server - XML 同名但属性不同的多个节点 SQL
- powershell - 具有多个潜在凭据的 PowerShell Connect-VIServer