day--6_python經常使用模塊

經常使用模塊:

  1. time和datetimenode

  2. shutil模塊python

  3. radommysql

  4. stringnginx

  5. shelve模塊git

  6. xml處理正則表達式

  7. configparser處理算法

  8. hashlibsql

  9. subprocess編程

  10. logging模塊json

  11. re正則表達式

time模塊

time模塊,即時間模

import time    # 導入時間模塊

print(time.process_time())  # 返回處理時間,不包含sleep時間,mac上測試不出來

print(time.asctime())  # 返回時間格式Mon Nov 14 10:07:07 2016

print(time.localtime())  # 返回被點時間對象struct time:time.struct_time(tm_year=2016, tm_mon=11, tm_mday=14, tm_hour=10, tm_min=8, tm_sec=41, tm_wday=0, tm_yday=319, tm_isdst=0)

print(time.altzone)   # 返回UTC時間差,以秒計算
print(time.time())    # 返回時間戳

'''
# 返回UTC時間的struc時間對象格式:
time.struct_time(tm_year=2016, tm_mon=11, tm_mday=3,
tm_hour=16, tm_min=14, tm_sec=11,
tm_wday=3, tm_yday=308, tm_isdst=0)
'''
print(time.gmtime(time.time()-900000))

print(time.asctime(time.localtime()))   # 返回時間格式:Mon Nov 14 10:14:11 2016

print(time.ctime())  # 返回格式:Mon Nov 14 10:15:12 2016

# 日期字符串轉換爲時間戳
time2 = time.strptime("2016/11/13 22:22:22", '%Y/%m/%d %H:%M:%S') # 將日期字符串轉換爲時間對象
print(time2)

time2_stamp = time.mktime(time2)     # 將時間對象轉換爲時間戳
print(time2_stamp)

time2_time = time.asctime(time2)    # 將時間戳轉換爲時間格式
print(time2_time)

# 將時間戳轉換爲字符串格式
time3 = time.gmtime(time2_stamp) # 返回時間對象
print(time3)
print(time.strftime('%Y/%m/%d %H:%M:%S', time3))   # 返回格式:2016/11/13 14:22:22

datetime模塊

時間模塊

import datetime
import time
# 返回當前時間
print(datetime.datetime.now())  # 返回格式:2016-11-14 10:32:10.415558

#時間戳直接轉換爲日期格式
print(datetime.datetime.fromtimestamp(time.time())) # 返回格式:2016-11-14 10:32:10.415558

# 當前時間加3天
print(datetime.datetime.now() + datetime.timedelta(3))  # 返回結果:2016-11-17 10:43:07.668299

# 當前時間減3天
print(datetime.datetime.now() - datetime.timedelta(3))  # 返回結果2016-11-11 10:43:07.668299

# 當前時間加3小時
print(datetime.datetime.now() - datetime.timedelta(hours=3))  # 返回結果2016-11-14 07:43:07.668299

# 當前時間減30分鐘

print(datetime.datetime.now() - datetime.timedelta(minutes=30))  # 返回結果:2016-11-14 10:13:07.668299

# 時間替換
c_time = datetime.datetime.now()    # 返回2016-11-14 10:54:44.986484
print(c_time.replace(minute=3,hour=2))  # 返回:2016-11-14 02:03:44.986484

經常使用時間字符

directive 英文含義 中文含義
%a Locale’s abbreviated weekday name. sun(sunday簡寫)
%A Locale’s full weekday name. sunday(完整顯示)
%b Locale’s abbreviated month name. 英文1到12月簡寫
%B Locale’s full month name. 英文1到12月完整的月名字
%c Locale’s appropriate date and time representation.  
%d Day of the month as a decimal number [01,31]. 一個月【01,31】
%H Hour (24-hour clock) as a decimal number [00,23]. 24小時制【00-23】
%I

Hour (12-hour clock) as a decimal number [01,12].

12小時制【01-12】
%j Day of the year as a decimal number [001,366]. 天的顯示【001-366】
%m Month as a decimal number [01,12]. 月【01-12】
%M Minute as a decimal number [00,59] 分鐘【00-59】
%p Locale’s equivalent of either AM or PM. AM上午
PM 下午
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. 一年的第多少周
%w Weekday as a decimal number [0(Sunday),6]. 一週7天顯示【0-6】6表示星期天
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.  
%x Locale’s appropriate date representation.  
%X

Locale’s appropriate time representation.

 
%y Year without century as a decimal number [00,99]. 2016年顯示16年
%Y Year with century as a decimal number. 2016年顯示2016年
%z

Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].

顯示時區
%Z

Time zone name (no characters if no time zone exists).

 
%%

A literal '%' character.

 

radom隨機數

隨機數模塊

import random  # 導入隨機數模塊
import string  # 導入字符串模塊

print(random.random())  # 生成隨機數

print(random.randint(1, 5))  # 生成1-5的隨機數包含5自己,每次顯示一個

print(random.randrange(1, 5))  # 生成1-5的隨機數,不包含5自己,每次顯示一個

print(random.sample(range(10), 5))  # 生成5個隨機數,格式爲列表格式[7, 0, 1, 9, 5]

# 生成隨機驗證碼

print(''.join(random.sample(string.ascii_lowercase, 5)))  # 生成5個隨機字母 返回:kbzdn

print(''.join(random.sample(string.ascii_letters, 5)))  # 生成5個隨機驗證碼 返回:sNpGj


# 生成隨機驗證碼的另外一種方法
checkcode = ''
for i in range(4):
    current = random.randrange(0, 4)
    if current != i:
        '''
        chr(random.randint(65, 90))將數字轉換爲ascii碼的對應表
        chr(65) = A,chr(66) = B
        '''
        temp = chr(random.randint(65, 90))
    else:
        temp = random.randint(0, 9)
    checkcode += str(temp)
print(checkcode)

string字符模塊

import string  # 導入字符串模塊

print(string.ascii_letters)  # 返回:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

print(string.ascii_lowercase)  # 返回:abcdefghijklmnopqrstuvwxyz

print(string.ascii_uppercase)  # 返回:ABCDEFGHIJKLMNOPQRSTUVWXYZ

print(string.digits)  # 返回:0123456789

print(string.hexdigits)  # 返回16進制:0123456789abcdefABCDEF

print(string.octdigits)  # 返回8進制整數:01234567

shutil

# 高級的 文件、文件夾、壓縮包處理模塊
例子1:shutil.copyfileobj()
將文件內容拷貝到另外一個文件中嗎,能夠拷貝部份內容:
import shutil
f = open('test.xml','r',encoding='utf-8')
 f1 = open('test_new.xml','w',encoding='utf-8')
shutil.copyfileobj(f,f1) 
# shutil.copyfileobj()方法須要打開文件才能拷貝
例子2:shutil.copyfile()
拷貝文件
import shutil
shutil.copyfile('test.xml','test_new_1.xml')

例子3:

shutil.copymode(stc,dst)
import shutil
# shutil.copymode(stc,dst)  # 僅拷貝權限,內容、組用戶均不變
# src源文件,dst目標
shutil.copymode('test.xml', 'test_new_1.xml')

例子4:shutil.copy(stc,dst)

# 拷貝文件和權限
import shutil

# 拷貝文件和權限
# shutil.copy(stc,dst)
shutil.copy('test.xml', 'test_new_1.xml')

例子5:shutil.copy2() 拷貝文件和狀態信息

import shutil
# shutil.copy2() 拷貝文件和狀態信息
shutil.copystat('test.xml', 'test_new_1.xml')

例子6:shutil.copystat() 拷貝文件和狀態信息

import shutil
# shutil.copystat() 拷貝文件和狀態信息
shutil.copystat('test.xml', 'test_new_1.xml')

例子7:shutil.copy2(src, dst)

import shutil
# shutil.copy2(src, dst)
# 拷貝文件和狀態信息
shutil.copy2('test.xml', 'test_new_1.xml')

例子8:shutil.make_archive(base_name, format,...)

建立壓縮包並返回文件路徑,例如:zip、tar

  • base_name: 壓縮包的文件名,也能夠是壓縮包的路徑。只是文件名時,則保存至當前目錄,不然保存至指定路徑,
    如:www                        =>保存至當前路徑
    如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
  • format: 壓縮包種類,「zip」, 「tar」, 「bztar」,「gztar」
  • root_dir: 要壓縮的文件夾路徑(默認當前目錄)
  • owner: 用戶,默認當前用戶
  • group: 組,默認當前組
  • logger: 用於記錄日誌,一般是logging.Logger對象
# 將D:\python_progream\python_s15\day6 下的文件打包放置當前程序目錄
import shutil
ret = shutil.make_archive("start", format='zip', root_dir='D:\python_progream\python_s15\day6')

結果:

image

zipfile模塊

zip壓縮,shutil對壓縮包的處理是調用zipfile和taifile模塊來進行的

zipfile代碼

import zipfile

# 壓縮
z = zipfile.ZipFile('testabc.zip', 'w')
z.write('xml_mode.py')
z.write('timelog.log')
z.close()

# 解壓
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
z.close()
#
# zipfile 壓縮解壓

 

tarfile代碼

import tarfile

# 壓縮
tar = tarfile.open('your.tar','w')
tar.add('/Users/xiaofeng/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
tar.add('/Users/xiaofeng/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
tar.close()

# 解壓
tar = tarfile.open('xxx.tar','r')
tar.extractall()  # 可設置解壓地址
tar.close()

tarfile 壓縮解壓

shelve模塊

shelve模塊是一個簡單的k,v將內存數據經過文件持久化模塊,能夠持久化pickle可支持的python數據格式

要使用shelve模塊,必需要導入模塊:import shelve

import shelve

f = shelve.open('shelve_test') #打開一個文件

def stu(name, age):
    print('stu',name, age)
t2 = (1, 2, 3, 4)
name = ["aaa", "rain", "test"]
f["test"] = name  # 持久化列表
f["t2"] = t2    # 持久化元組
f["func"] = stu  # 持久化函數

f.close()

shleve讀取

import shelve

def stu(name, age):
    print('stu', name, age)
    return 0
f = shelve.open('shelve_test')
print(f["test"])   # 返回['aaa', 'rain', 'test']
print(f["test"][1])  # 返回:rain
print(f['t2'])     # 返回:(1, 2, 3, 4)
print(f['t2'][2])  # 返回:3
print(f["func"]('xao', 22))   # 返回:stu xao 22

xml處理模塊

xml是實現不一樣語言或程序之間進行數據交換協議,跟json差很少,可是json使用起來簡單,不過,古時候,在json尚未誕生的年代,你們只能用xml,只進不少傳統公司還在用xml

xml格式以下,就是經過<>節點來區別數據結構的:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

xml協議在各個語言裏都是支持的,在python中能夠用如下模塊操做xml

若是要操做xml格式的文件

首先須要引入xml相關模塊

import xml.etree.ElementTree as ET
tree = ET.parse("test.xml")
root = tree.getroot()
print(root.tag)   # tag首行
# for child in root:
#     print(child.tag, child.attrib)
#     for i in child:
#         print(i.tag, i.text)    # text打印值

# 返回值:
'''
data
country {'name': 'Liechtenstein'}
rank 2
year 2008
gdppc 141100
neighbor None
neighbor None
country {'name': 'Singapore'}
rank 5
year 2011
gdppc 59900
neighbor None
country {'name': 'Panama'}
rank 69
year 2011
gdppc 13600
neighbor None
neighbor None
'''

# 只遍歷year節點
# for node in root.iter('year'):
#     print(node.tag, node.text)
# 返回值:
'''
year 2008
year 2011
year 2011
'''

#  修改
# 遍歷全部年並修改年的值+1
for node in root.iter('year'):
    new_year = int(node.text) + 1  # 全部的年的值加1
    node.text = str(new_year)   # 將new_year中的數字轉換爲字符串
    node.set("updated", "yes")  # 全部的年添加屬性
tree.write("test1.xml")

# 刪除
# 刪除node
for country in root.findall('country'):  # findall查找全部
    rank = int(country.find('rank').text)  # 將rank的值付給rank,並轉換爲整數
    if rank > 50:
        root.remove(country)    # 移除一個country標籤
tree.write('test2.xml')

# 建立一個xml文件
new_xml = ET.Element("dev")  # 建立根標籤,dev爲根標籤的名字
name = ET.SubElement(new_xml, "name", attrib={"enrolled":"yes"}) # 建立子標籤,子標籤的名字爲name
# attrib指定屬性
# 返回值
age = ET.SubElement(name, "age", attrib={"enrolled":"yes"}) # 設置name的子標籤age,並設置屬性
sex = ET.SubElement(name, "sex")  # 設置子標籤中的子標籤
sex.text = '33'   # 設置sex的值
et = ET.ElementTree(new_xml)
et.write("test3.xml", encoding="utf-8",xml_declaration=True)
# 返回值:<?xml version='1.0' encoding='utf-8'?>
# ET.dump(test3.xml) #打印生成的格式

生成的文件

<?xml version='1.0' encoding='utf-8'?>
<dev> 
    <name enrolled="yes">
<age enrolled="yes" /> 
        <sex>33</sex>
</name>
</dev>

configparser模塊

用於生成常見的配置文檔,當前名稱在python3版本中變動爲configparser,在2版本中首字母是大寫。

configparser生成的常見配置文件以下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

若是想用python生成一個這樣的文檔怎麼作:

import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}
config['xuanchuan.org'] = {}
config['xuanchuan.org']['user'] = 'hg'
config['top.server.com'] = {}
top = config['top.server.com']
top['Host Port'] = '56666'
top['ForwardX11'] = 'no'
config["DEFAULT"]['ForwardX11'] = 'yes'
with open('config.ini','w') as f:
    config.write(f)

粘貼結果:

[DEFAULT]
compressionlevel = 9
serveraliveinterval = 45
compression = yes
forwardx11 = yes

[xuanchuan.org]
user = hg

[top.server.com]
host port = 56666
forwardx11 = no

config.ini文件操做:

# 讀取config.ini文件
import configparser
config = configparser.ConfigParser()
config.sections()

print(config.read('config.ini'))  # 返回值['config.ini']
print(config.sections())   # 返回:['xuanchuan.org', 'top.server.com'],默認[DEFAULT]不讀取
print(config["DEFAULT"]['forwardx11'])  # 返回值:yes
print(config['top.server.com']['Host Port'])  # 返回值:56666,此處key是不區分大小寫的

# 遍歷config.ini文件
for key in config['top.server.conf']:
    print(key)

# 改'
config['top.server.com']['Host Port'] = '222'
print(config['top.server.com']['Host Port'])
with open('config1.ini', 'w') as f:
    config.write(f)

hashlib模塊

用於加密的模塊,3.x裏代替了md5模塊和sha模塊,主要提供sha1,sha224,sha256,sha384,sha512,MD5算法

import hashlib
m = hashlib.md5()
m.update(b'hello')
# print(m.digest())  # 二進制格式的hash
print(m.hexdigest())  # 16禁止格式的hash
# 返回值:5d41402abc4b2a76b9719d911017c592
###md5算法
m.update(b'admin')
print(m.hexdigest())
# 返回值:dbba06b11d94596b7169d83fed72e61b

# # sha1算法
sha_1 = hashlib.sha1()
sha_1.update(b"admin")
print(sha_1.hexdigest())
# 返回值:d033e22ae348aeb5660fc2140aec35850c4da997

# ##sha224算法
sha_224 = hashlib.sha224()
sha_224.update(b"admin")
print(sha_224.hexdigest())
# 返回值:58acb7acccce58ffa8b953b12b5a7702bd42dae441c1ad85057fa70b

# ## sha256算法
sha_256 = hashlib.sha256()
sha_256.update(b"admin")
print(sha_256.hexdigest())
# 返回值:8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

# ## sha384算法
sha_384 = hashlib.sha384()
sha_384.update(b"admin")
print(sha_384.hexdigest())
# 返回值:9ca694a90285c034432c9550421b7b9dbd5c0f4b6673f05f6dbce58052ba20e4248041956ee8c9a2ec9f10290cdc0782

# ## sha512算法
sha_512 = hashlib.sha512()
sha_512.update(b"admin")
print(sha_512.hexdigest())
# 返回值:c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9077ec

hmac模塊

加嚴算法

import hmac   # 引入模塊,用於消息傳輸,相似於QQ消息
h = hmac.new(b'alber')
h.update(b"hello")
print(h.hexdigest())
# 返回值:1b6752f035a051eb026c3824de78a714
# 或者
h = hmac.new(b'alber',b'hello')
print(h.hexdigest())
# 返回值:1b6752f035a051eb026c3824de78a714

logging模塊

不少程序都有記錄日誌的需求,而且日誌中包含的信息既有正常的程序訪問日誌,還可能有錯誤、警告等信息輸出,python的logging模塊提供了標準的日誌接口,你能夠經過它存儲各類格式的日誌,loging的日誌能夠分爲debug(),info(),warning(),error()andcritical()5個級別,下面看一下怎麼使用

最簡單的用法:

此處須要粘貼代碼

下面看下這幾個日誌級別分別表明什麼含義:

level when it's used
DEBUG 調試錯誤
INFO 相信信息
WARNING 警告信息
ERROR 錯誤信息
CRIITICAL  

若是想把日誌寫到文件也很簡答:

import logging
logging.basicConfig(filename='log.log',level=logging.DEBUG) #默認是追加模式a
logging.debug("this is debug")
logging.info("this is info")
logging.warning("user[alber] attempet warning")
logging.critical("mysql server is down")

日誌文件:

DEBUG:root:this is debug
INFO:root:this is info
WARNING:root:user[alber] attempet warning
CRITICAL:root:mysql server is down

日誌格式format=

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

%(name)s logger的名字
%(levelno)s 數字形式的日誌級別
%(levelname)s 文本格式的日誌級別
%(pathname)s 調用日誌輸出函數的模塊的完成路徑名,可能沒有
%(filename)s 調用日誌輸出函數的模塊的文件名
%(module)s 調用日誌輸出函數的模塊名
%(funcName)s 調用日誌輸出函數的函數名
%(lineno)d 調用日誌輸出函數的語句所在的代碼行
%(created)f 當前時間,用unix標準的表示時間的浮點數表示
%(relactiveCreated)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='log.log',level=logging.DEBUG) #默認是追加模式a
logging.debug("this is debug")
logging.info("this is info")
logging.warning("user[alber] attempet warning")
logging.critical("mysql server is down")

# 返回值:log.log文件

logging.basicConfig(filename='log.log', level=logging.DEBUG,
                    format='%(asctime)s  %(levelname)s:%(message)s',
                    datefmt='%Y-%m-%d %I:%M:%S %p')  # 默認是追加模式a
logging.debug("this is debug")
logging.info("this is info")
logging.warning("user[alber] attempet warning")
logging.critical("mysql server is down")

logger = logging.getLogger("nginx")  # 指定程序名
logger.setLevel(logging.DEBUG)   #設定程序的日誌級別

日誌文件:

2016-11-14 05:34:02 PM  WARNING: user[alber] attempet warning
2016-11-14 05:34:02 PM  CRITICAL: mysql server is down
2016-11-14 05:34:17 PM  DEBUG:this is debug
2016-11-14 05:34:17 PM  INFO:this is info
2016-11-14 05:34:17 PM  WARNING:user[alber] attempet warning
2016-11-14 05:34:17 PM  CRITICAL:mysql server is down

若是想同時把log打印在屏幕和日誌文件裏,就要了解複雜的知識了

python使用logging模塊記涉及四個主要類,使用官方文檔的概述最爲合適:

logger提供了應用程序能夠直接使用接口

handler將(logger建立)日誌記錄發送到合適的目的輸出

filter提供了細度設備來決定輸出哪條日誌記錄

formatter決定記錄日誌的最終輸出格式

logger

每一個程序在輸出信息以前偶要得到一個logger。logger一般對應了程序的模塊名,好比聊天工具的圖形界面模塊能夠這樣得到它的logger:

log=logging.getlogger("char.gui")

而核心模塊能夠這樣

log=logging.getlogger("kerenel")

logger.setLevel(level):指定日誌最低級別,低於level的級別將被忽略,debug是最低的內置級別,critical爲最高

logger.addFilter(filt),Logger.removeFilter(filt):添加或刪除指定的filter

Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增長或刪除指定的handler

Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():能夠設置的日誌級別

handler

handler對象負責發送相關的信息到指定目的地。Python的日誌系統有多種Handler可使用。有些Handler能夠把信息輸出到控制檯,有些Logger能夠把信息輸出到文件,還有些 Handler能夠把信息發送到網絡上。若是以爲不夠用,還能夠編寫本身的Handler。能夠經過addHandler()方法添加多個多handler

Handler.setLevel(level):指定被處理的信息級別,低於lel級別的信息將被忽略
Handler.setFormatter():給這個handler選擇一個格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或刪除一個filter對象

每一個Logger能夠附加多個Handler。接下來咱們就來介紹一些經常使用的Handler:
1) logging.StreamHandler
使用這個Handler能夠向相似與sys.stdout或者sys.stderr的任何文件對象(file object)輸出信息。它的構造函數是:
StreamHandler([strm])
其中strm參數是一個文件對象。默認是sys.stderr

2) logging.FileHandler
和StreamHandler相似,用於向一個文件輸出日誌信息。不過FileHandler會幫你打開這個文件。它的構造函數是:
FileHandler(filename[,mode])
filename是文件名,必須指定一個文件名。
mode是文件的打開方式。參見Python內置函數open()的用法。默認是’a',即添加到文件末尾。

3) logging.handlers.RotatingFileHandler
這個Handler相似於上面的FileHandler,可是它能夠管理文件大小。當文件達到必定大小以後,它會自動將當前日誌文件更名,而後建立 一個新的同名日誌文件繼續輸出。好比日誌文件是chat.log。當chat.log達到指定的大小以後,RotatingFileHandler自動把 文件更名爲chat.log.1。不過,若是chat.log.1已經存在,會先把chat.log.1重命名爲chat.log.2。。。最後從新建立 chat.log,繼續輸出日誌信息。它的構造函數是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode兩個參數和FileHandler同樣。
maxBytes用於指定日誌文件的最大文件大小。若是maxBytes爲0,意味着日誌文件能夠無限大,這時上面描述的重命名過程就不會發生。
backupCount用於指定保留的備份文件的個數。好比,若是指定爲2,當上面描述的重命名過程發生時,原有的chat.log.2並不會被改名,而是被刪除。

4) logging.handlers.TimedRotatingFileHandler
這個Handler和RotatingFileHandler相似,不過,它沒有經過判斷文件大小來決定什麼時候從新建立日誌文件,而是間隔必定時間就 自動建立新的日誌文件。重命名的過程與RotatingFileHandler相似,不過新的文件不是附加數字,而是當前時間。它的構造函數是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename參數和backupCount參數和RotatingFileHandler具備相同的意義。
interval是時間間隔。
when參數是一個字符串。表示時間間隔的單位,不區分大小寫。它有如下取值:
S 秒
M 分
H 小時
D 天
W 每星期(interval==0時表明星期一)
midnight 天天凌晨

例子:

import logging
logger = logging.getLogger("nginx")  # 指定程序名
logger.setLevel(logging.DEBUG)   #設定程序的日誌級別

# 指定log的顯示方式
ch = logging.StreamHandler()  # 顯示器屏幕方式輸入
ch.setLevel(logging.DEBUG)    # 顯示器屏幕輸入的日誌級別

fh = logging.FileHandler('access.log')  # 顯示器文件輸出,access.log是日誌文件名字
fh.setLevel(logging.WARNING)  # 顯示器文件輸出的日誌級別

# 指定日誌格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

ch.setFormatter(formatter)
fh.setFormatter(formatter)

logger.addHandler(ch)
logger.addHandler(fh)

logger.debug("this is debug")
logger.info("this is info")
logger.warning("user[alber] attempet warning")
logger.critical("mysql server is down")

日誌文件:

2016-11-14 18:22:45,612 - nginx - WARNING - user[alber] attempet warning
2016-11-14 18:22:45,613 - nginx - CRITICAL - mysql server is down

日誌切割例子:

import logging
from logging import handlers

logger = logging.getLogger("nginx")

log_file = "timelog.log"

# 以大小切割
#fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)
# maxBytes,多少字節切割,backupCount,保留的分數

# 以時間切割
fh = handlers.TimedRotatingFileHandler(filename=log_file,
                                       when="S", interval=5, backupCount=3)
# when= 'S' 指定單位爲秒 interval= 5 表示5面切割,backupCount=3,備份三份

formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.warning("test1")
logger.warning("test12")
logger.warning("test13")
logger.warning("test14")

re模塊

經常使用的正則表達式模塊

符號

含義

.

默認匹配除\n以外的任意一個字符,若指定gflag DOTALL,則匹配任意字符,包括換行

^

匹配字符開頭,若指定flag MULTILINE這中也能夠匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)

$

匹配以字符結尾,e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也能夠

*

匹配*號前的字符0次或屢次,re.findall("ab*","cabb3abcbbac")  結果爲['abb', 'ab', 'a']

+

匹配前一個字符1次或屢次,re.findall("ab+","ab+cd+abb+bba") 結果['ab', 'abb']

'?'

匹配前面的字符一次或0次

'{m}'

匹配前一個字符m次

'{n,m}'

匹配前一個字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果'abb', 'ab', 'abb']

'|'

匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 結果'ABC'

'(...)'

分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結果 abcabca456c

'\A'

只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的

'\Z'

只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的

'\d'

匹配數字0-9

'\D'

匹配非數字

\w'

匹配[A-Za-z0-9]

'\W'

匹配非[A-Za-z0-9]

's'

匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 結果 '\t'

'(?P<name>...)'

分組匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 結果{'province': '3714', 'city': '81', 'birthday': '1993'}

最經常使用的匹配語法

re.match從頭開始匹配

re.search 配額包含

re.findall 把全部匹配到的字符放在以列表中的元素返回

re.splitall 以匹配到的字符看成列表分割符

re.sub 匹配字符串並替換

反斜槓的困擾
與大多數編程語言相同,正則表達式裏使用"\"做爲轉義字符,這就可能形成反斜槓困擾。假如你須要匹配文本中的字符"\",那麼使用編程語言表示的正則表達式裏將須要4個反斜槓"\\\\":前兩個和後兩個分別用於在編程語言裏轉義成反斜槓,轉換成兩個反斜槓後再在正則表達式裏轉義成一個反斜槓。Python裏的原生字符串很好地解決了這個問題,這個例子中的正則表達式可使用r"\\"表示。一樣,匹配一個數字的"\\d"能夠寫成r"\d"。有了原生字符串,你不再用擔憂是否是漏寫了反斜槓,寫出來的表達式也更直觀。

僅需輕輕知道的幾個匹配模式

re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)

M(MULTILINE): 多行模式,改變'^'和'$'的行爲(參見上圖)

S(DOTALL): 點任意匹配模式,改變'.'的行爲

例子:

相關文章
相關標籤/搜索