2017-02-22 88 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