Python經常使用模塊

1、模塊介紹

 模塊就是一組功能的集合體,咱們的程序能夠導入模塊來複用模塊裏的功能,一個模塊就是一個包含了一組功能的python文件。

在python中,模塊的使用方式都是同樣的,但其實細分的話,模塊能夠分爲四個通用類別
python

①使用python編寫的.py文件
②已被編譯爲共享庫或DLL的C或C++擴展
③把一系列模塊組織到一塊兒的文件夾(注:文件夾下有一個__init__.py文件,該文件夾稱之爲包)
④使用C編寫並連接到python解釋器的內置模塊django

2、爲什麼要使用模塊?

一、從文件級別組織程序,更方便管理
隨着程序的發展,功能愈來愈多,爲了方便管理,咱們一般將程序分紅一個個的文件,這樣作程序的結構更清晰,方便管理。這時咱們不只僅能夠把這些文件當作腳本去執行,還能夠把他們當作模塊來導入到其餘的模塊中,實現了功能的重複利用
#二、拿來主義,提高開發效率
一樣的原理,咱們也能夠下載別人寫好的模塊而後導入到本身的項目中使用,這種拿來主義,能夠極大地提高咱們的開發效率
#ps
若是你退出python解釋器而後從新進入,那麼你以前定義的函數或者變量都將丟失,所以咱們一般將程序寫到文件中以便永久保存下來,須要時就經過python test.py方式去執行,此時test.py被稱爲腳本script。ide

3、經常使用模塊

一、logging模塊:

       日誌就是記錄一些信息,方便查詢或者輔助開發函數

①日誌級別

CRITICAL = 50 #FATAL = CRITICAL
ERROR = 40
WARNING = 30  #WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0    #不設置

logging模塊指定全局配置,針對全部logger有效,控制打印到文件中ui

可在logging.basicConfig()函數中經過具體參數來更改logging模塊默認行爲,可用參數有
filename:用指定的文件名建立FiledHandler(後邊會具體講解handler的概念),這樣日誌會被存儲在指定的文件中。
filemode:文件打開方式,在指定了filename時使用這個參數,默認值爲「a」還可指定爲「w」。
format:指定handler使用的日誌顯示格式。 
datefmt:指定日期時間格式。 
level:設置rootlogger(後邊會講解具體概念)的日誌級別 
stream:用指定的stream建立StreamHandler。能夠指定輸出到sys.stderr,sys.stdout或者文件,默認爲sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。



#格式
%(name)s:Logger的名字,並不是用戶名,詳細查看

%(levelno)s:數字形式的日誌級別

%(levelname)s:文本形式的日誌級別

%(pathname)s:調用日誌輸出函數的模塊的完整路徑名,可能沒有

%(filename)s:調用日誌輸出函數的模塊的文件名

%(module)s:調用日誌輸出函數的模塊名

%(funcName)s:調用日誌輸出函數的函數名

%(lineno)d:調用日誌輸出函數的語句所在的代碼行

%(created)f:當前時間,用UNIX標準的表示時間的浮 點數表示

%(relativeCreated)d:輸出日誌信息時的,自Logger建立以 來的毫秒數

%(asctime)s:字符串形式的當前時間。默認格式是 「2003-07-08 16:49:45,896」。逗號後面的是毫秒

%(thread)d:線程ID。可能沒有

%(threadName)s:線程名。可能沒有

%(process)d:進程ID。可能沒有

%(message)s:用戶輸出的消息
View Code

format參數中可能用到的格式化串
編碼

%(name)s Logger的名字
%(levelno)s 數字形式的日誌級別
%(levelname)s 文本形式的日誌級別
%(pathname)s 調用日誌輸出函數的模塊的完整路徑名,可能沒有
%(filename)s 調用日誌輸出函數的模塊的文件名
%(module)s 調用日誌輸出函數的模塊名
%(funcName)s 調用日誌輸出函數的函數名
%(lineno)d 調用日誌輸出函數的語句所在的代碼行
%(created)f 當前時間,用UNIX標準的表示時間的浮 點數表示
%(relativeCreated)d 輸出日誌信息時的,自Logger建立以 來的毫秒數
%(asctime)s 字符串形式的當前時間。默認格式是 「2003-07-08 16:49:45,896」。逗號後面的是毫秒
%(thread)d 線程ID。可能沒有
%(threadName)s 線程名。可能沒有
%(process)d 進程ID。可能沒有
%(message)s用戶輸出的消息




#========使用
import logging
logging.basicConfig(filename='access.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)

logging.debug('調試debug')
logging.info('消息info')
logging.warning('警告warn')
logging.error('錯誤error')
logging.critical('嚴重critical')





#========結果
access.log內容:
2017-07-28 20:32:17 PM - root - DEBUG -test:  調試debug
2017-07-28 20:32:17 PM - root - INFO -test:  消息info
2017-07-28 20:32:17 PM - root - WARNING -test:  警告warn
2017-07-28 20:32:17 PM - root - ERROR -test:  錯誤error
2017-07-28 20:32:17 PM - root - CRITICAL -test:  嚴重critical

part2: 能夠爲logging模塊指定模塊級的配置,即全部logger的配置
View Code

②低配版默認爲warning:只能寫入文件或者屏幕輸出

import logging

logging.basicConfig(
        # level=logging.DEBUG,
        level=10,  #顯示的級別
        format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s', # 顯示格式
        datefmt='%Y %m %d',  #日期
        # filename='a.log',  #默認是a模式, 就是使用的gbk編碼。
        # filemode='w'  通常不用改。
)

logging.debug('調試模式')  # 10
logging.info('正常運行')  # 20
logging.warning('警告')  # 30
logging.error('錯誤')  # 40
logging.critical('系統崩了')  # 50
View Code

③標配版

import logging

# 建立logging對象
logger = logging.getLogger()

# 建立文件對象
fh1 = logging.FileHandler('a1.log', encoding='utf-8')
fh2 = logging.FileHandler('a2.log', encoding='utf-8')

# 建立屏幕對象
sh = logging.StreamHandler()

formater1 = logging.Formatter(
        fmt='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s',  # 顯示格式
        datefmt='%Y-%m-%d %H:%M:%S',)

formater2 = logging.Formatter(
        fmt='%(asctime)s %(levelname)s %(message)s',  # 顯示格式
        datefmt='%Y-%m-%d %H:%M:%S',)

formater3 = logging.Formatter(
        fmt='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s',  # 顯示格式
        datefmt='%Y-%m-%d %H:%M:%S',)

# 給對象綁定格式
fh1.setFormatter(formater1)
fh2.setFormatter(formater2)
sh.setFormatter(formater3)

# 給logger對象添加其餘對象
logger.addHandler(fh1)
logger.addHandler(fh2)
logger.addHandler(sh)

# 設置logger級別
logger.setLevel(40)
sh.setLevel(50)  # 按照logger對象設置的級別顯示
fh1.setLevel(30)
fh2.setLevel(30)

logging.debug('調試模式')  # 10
logging.info('正常運行')  # 20
logging.warning('警告')  # 30
logging.error('錯誤')  # 40
logging.critical('系統崩了')  # 50
View Code

④高配版:經過導入文件(導入字典的方式)寫日誌相似Django。

import os
import logging.config

# 定義三種日誌輸出格式 開始

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]' #其中name爲getlogger指定的名字

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# 定義日誌輸出格式 結束

# print(__file__)
logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log文件的目錄

logfile_name = '高配版.log'  # log文件名

# # 若是不存在定義的日誌目錄就建立一個
# if not os.path.isdir(logfile_dir):
#     os.mkdir(logfile_dir)

# log文件的全路徑
logfile_path = os.path.join(logfile_dir, logfile_name)


# log配置字典
# 第一層鍵值對的鍵固定的關鍵字不能改變。
LOGGING_DIC = {
    'version': 1, # 版本
    'disable_existing_loggers': False,  #
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
        'id_simple_format':{
                'format': id_simple_format
        }
    },
    'filters': {},
    'handlers': {
        #打印到終端的日誌
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日誌,收集info及以上的日誌
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日誌文件
            'maxBytes': 300,  # 日誌大小 300bytes
            'backupCount': 5, # 最多隻有5個文件
            'encoding': 'utf-8',  # 日誌文件的編碼,不再用擔憂中文log亂碼了
        },
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default', 'console'],  # 這裏把上面定義的兩個handler都加上,即log數據既寫入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)傳遞
        },
    },
}



logging.config.dictConfig(LOGGING_DIC)  # 導入上面定義的logging配置
# # logging.config  # 將你寫好的logging 字典 在導入logging.config後,傳到logging模塊中
logger = logging.getLogger()  # 生成一個log實例  經過字典本身設置的個性化的log對象

logger.info('正常運行狀態')  # 記錄該文件的運行狀態
View Code

 ⑤django的配置

#logging_config.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
                      '[%(levelname)s][%(message)s]'
        },
        'simple': {
            'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
        },
        'collect': {
            'format': '%(message)s'
        }
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        #打印到終端的日誌
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        #打印到文件的日誌,收集info及以上的日誌
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自動切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"),  # 日誌文件
            'maxBytes': 1024 * 1024 * 5,  # 日誌大小 5M
            'backupCount': 3,
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        #打印到文件的日誌:收集錯誤及以上的日誌
        'error': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自動切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"),  # 日誌文件
            'maxBytes': 1024 * 1024 * 5,  # 日誌大小 5M
            'backupCount': 5,
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        #打印到文件的日誌
        'collect': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自動切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
            'maxBytes': 1024 * 1024 * 5,  # 日誌大小 5M
            'backupCount': 5,
            'formatter': 'collect',
            'encoding': "utf-8"
        }
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default', 'console', 'error'],
            'level': 'DEBUG',
            'propagate': True,
        },
        #logging.getLogger('collect')拿到的logger配置
        'collect': {
            'handlers': ['console', 'collect'],
            'level': 'INFO',
        }
    },
}


# -----------
# 用法:拿到倆個logger

logger = logging.getLogger(__name__) #線上正常的日誌
collect_logger = logging.getLogger("collect") #領導說,須要爲領導們單獨定製領導們看的日誌
View Code
相關文章
相關標籤/搜索