在整个过程中自动使用一个类实例 [英] One class instance used automatically throughout process

查看:84
本文介绍了在整个过程中自动使用一个类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦导入和实例化的python日志模块将在整个过程中,所有模块和线程内。他们是如何实现这一效果的?



例如: .py

  import logging 
import mylib

def main :
logging.basicConfig(filename ='myapp.log',level = logging.INFO)
logging.info('Started')
mylib.do_something()
logging。 info('Finished')

如果__name__ =='__main__':
main()

mylib.py

  import logging 

def do_something():
logging.info('Doing something')

strong> myapp.log

  INFO:root:Started 
INFO:root: $ b INFO:root:Finished


解决方案

第一次导入时,加载的模块对象将被放入 sys.modules 。稍后导入将找到模块对象,而不是重新加载模块。



日志模块有一堆模块属性,保存首次导入后的日志配置的状态。


The python logging module once imported and instantiated will be so across the process, inside all modules and threads. How did they achieve that effect?

Example:

myapp.py

import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()

mylib.py

import logging

def do_something():
    logging.info('Doing something')

myapp.log

INFO:root:Started
INFO:root:Doing something
INFO:root:Finished

解决方案

When a module is imported for the first time, the loaded module object is put into sys.modules. Later imports will then find the module object and not reload the module.

The logging module has a bunch of module attributes which hold the state of logging configuration after the first import.

这篇关于在整个过程中自动使用一个类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆