簡體   English   中英

Python:登錄模塊腳本以在另一個腳本中調用

[英]Python : Logging in module script to be called in another script

我大約有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,missionbase.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.basicConfig(...)因為這行代碼會修改日志記錄模塊的所謂根記錄程序。 該根記錄器是在您首次導入記錄模塊時創建的,它位於全局范圍內。 因此,根記錄器始終可用-只需在需要的位置和時間使用它,例如logging.debug('message')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM