歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> AttributeError: module object has no attribute handlers--Python子模塊導入問題

AttributeError: module object has no attribute handlers--Python子模塊導入問題

日期:2017/3/1 9:41:46   编辑:Linux編程

想使用Python的logging模塊記錄日志,並使用RotatingFileHandler來處理日志以便於在日志文件超過指定的大小後會重新生成新的日志文件。

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

基本代碼如下:

import logging

logger = logging.getLogger('mylogger')
logger.setLevel(logging.INFO)

fh=logging.handlers.RotatingFileHandler('/tmp/test.log', mode = 'a', maxBytes=10240, backupCount=3, encoding='utf-8')

formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

logger.addHandler(fh)

logger.info('hello logging')
logger.warning('hello logging')
logger.error('hello logging')
logger.critical('hello logging')

運行時報錯:

AttributeError: 'module' object has no attribute 'handlers'

原來導入logging模塊後並沒有自動導入其子模塊handlers

import logging
import logging.handlers
……

重新運行,程序正常輸出。

Python程序中模塊在被訪問前必須導入,import logging僅導入了logging模塊,而logging是一個擁有子模塊的包,這些子模塊沒有被自動載入。所以在訪問簽需要明確的導入logging.handlers子模塊。

但有時候,在導入一些包時並不需要額外的動作就能自動導入其子模塊,這是因為在包的__init__.py文件中進行了這些操作。在另外一些情況下,你導入的另外一些東西也可能會導入logging.handlers模塊。無論如何,只要保證訪問前

對應的子模塊已經導入便可。某些時候一個模塊看起來是個包實際上並不是,比如os和os.path。os並非包,它只是提供了其他的模塊叫path,你可以通過os.path來訪問。

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved