2017-02-22 87 views
0

我想了解如何在Python中使用Logging模塊。如何在後續的模塊調用中使用已導入的模塊Python

我有以下主要代碼:

import logging 
import First 
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s %(message)s',filename=r'C:\Users\bhatsubh\Desktop\Everything\Codes\Python\Logs\automation.log',filemode='a') 
logging.debug('A debug message') 
logging.info('Some information') 
logging.warning('A shot across the bows') 
logging.error('Committed a blunder') 
obj = First.Demo("Subhayan",75000) 
print (obj.getSal()) 

的First.py模塊包含下面的代碼:

class Demo: 
    def __init__(self,Name,salary): 
     logging.info("Inside Demo init") 
     self.name = Name 
     self.salary = salary 
    def getSal(self): 
     logging.info("Inside Demo getSal") 
     sal = self.salary * 100 
     return sal 

現在是有什麼方法中,我可以在頂部導入模塊記錄我的模塊文件的級別,然後在剩餘的調用中使用它,而不必在每個其他文件中再次導入它。

非常感謝您提供任何解釋。

+0

它可以完成,但最好只導入兩個文件。 –

+0

謝謝史蒂文,但你能否詳細說明一下?我的意思是我猜想在這兩個文件中導入將是最佳實踐,但僅僅爲了知識,其他工作是什麼。 –

回答

0

真的,我會建議只導入這兩個文件。 Python如何處理進口是如何解釋的here

否則,如果你真的想,那麼你可以這樣做。

First.py

math = None # declare a name for your module 

def func(): 
    print(math.pi) 

main.py

import First 
import math # using math module as example 

test2.math = math 
test2.func() 

現在有了這個問題是,首先現在依賴於有它math屬性設置。如果這是一個問題,那麼你可以改變它。

def func(): 
    print(math.pi) 

if __name__ == '__main__': 
    import math 
else: 
    math = None