Python 自定义模块路径

问题:

假设我们自己写了一个名为 log_config.py 的日志记录程序模块。此模块会被其他程序所引用,如下例子。

import log_config
logger = log_config.log_config("./test_log.txt", "tester")
logger.info("log start.")
logger.info("something happens")
logger.info("log end.")

解决方法:

  • 先看一下目前系统中的Python 路径情况:
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
  • 结果显示,在这几个目录都是 Python 的系统目录。我们的模块可以放在如下二个目录即可。
'/usr/local/lib/python2.7/dist-packages', 
'/usr/lib/python2.7/dist-packages'

更进一步:

  • 如果自定义的模块不想与Python 系统的模块放在同一目录下,可以在上面二个目录中增加一个路径文件 user_defined_modules.pth 。此文件内容就是我们自定义模块的存放路径。例子如下:
/home/tom/python_modules/

在 /home/tom/python_module/ 目录中把我们的模块文件 log_config.py 存放好即可。

附录 log_config.py 源码:

此代码可以设置日志文件的生成规则,目录设置的是 1 小时 1 个文件。如果一小时内单个文件大小超过 10 MB会自动分割成多个文件。

#!/usr/bin/python
# encoding=utf-8

#example
#import log_config
#logger = log_config.log_config("./test_log.txt", "tester")
#logger.info("log start")
#logger.info("log end")

#!/usr/bin/env python
# -*- coding:utf-8 -*

""" Setup a Logger which creates a new log file when it
reach up to it limits, such as one hour and file size 10 MB.
"""

__author__ = "Zhiwei Yan"
__copyright__ = "Copyright 2016, The Common tools Project"
__credits__ = ["Zhiwei Yan"]
__license__ = "Apache License"
__version__ = "2.0"
__maintainer__ = "Zhiwei YAN"
__email__ = "jerod.yan@gmail.com"
__status__ = "Production"

import logging
import logging.handlers as handlers
import time, datetime
class SizedTimedRotatingFileHandler(handlers.TimedRotatingFileHandler):
    """
    Handler for logging to a set of files, which switches from one file
    to the next when the current file reaches a certain size, or at certain
    timed intervals
    """
    def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None,
                 delay=0, when='h', interval=1, utc=False):
        # If rotation/rollover is wanted, it doesn't make sense to use another
        # mode. If for example 'w' were specified, then if there were multiple
        # runs of the calling application, the logs from previous runs would be
        # lost if the 'w' is respected, because the log file would be truncated
        # on each run.
        if maxBytes > 0:
            mode = 'a'
        handlers.TimedRotatingFileHandler.__init__(
            self, filename, when, interval, backupCount, encoding, delay, utc)
        self.maxBytes = maxBytes

    def shouldRollover(self, record):
        """
        Determine if rollover should occur.

        Basically, see if the supplied record would cause the file to exceed
        the size limit we have.
        """
        if self.stream is None:                 # delay was set...
            self.stream = self._open()
        if self.maxBytes > 0:                   # are we rolling over?
            msg = "%s\n" % self.format(record)
            self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
            if self.stream.tell() + len(msg) >= self.maxBytes:
                return 1
        t = int(time.time())
        if t >= self.rolloverAt:
            return 1
        return 0



def log_config(log_filename, logger_str):
    
    logging.basicConfig(format = "%(asctime)s" "[%(module)s:%(funcName)s:%(lineno)d]\n" "%(message)s \n")

    logger=logging.getLogger(logger_str)
    logger.propagate = False
    logger.setLevel(logging.DEBUG)

    handler=SizedTimedRotatingFileHandler(
            log_filename, 
            maxBytes=10*1024*1024, backupCount=24*30,
            when='h',interval=1,
            # encoding='bz2',  # uncomment for bz2 compression
            )

    logformatter = logging.Formatter("%(asctime)s" "[%(module)s:%(funcName)s:%(lineno)d]\n" "%(message)s \n")
    handler.setFormatter(logformatter)
    logger.addHandler(handler)

    return logger

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 0.1本系列教程说明 本系列教程,采用的大纲母本为《Understanding Network Hacks Att...
    小黑y99阅读 65,225评论 0 3
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,599评论 6 427
  • 按照官方的解释,加-m选项是以模块的方式执行,那么到底是什么意思呢? 首先我们来看下这段简单的测试代码: #!/u...
    crazyhank阅读 4,431评论 0 0
  • 你觉得“幸运”的时候,是因为你的欲望得到满足;你觉得“不幸”的时候,是因为你的欲望落空。好运气发生在你身上,你当然...
    Satada阅读 137评论 0 0
  • 一朵微尘附着的云,本是纯澈 白天里,你就在山川大海上漂泊 你是自由的 偶然倾心,宿命在作怪 我知道,你必然不会爱我...
    大圣归去来兮阅读 249评论 0 3