Python_oldboy_常用模块(九)

 本节大纲:

  1. 模块介绍
  2. time &datetime模块
  3. random
  4. os
  5. sys
  6. shutil
  7. json & pickle
  8. shelve
  9. xml处理
  10. yaml处理
  11. configparser
  12. hashlib
  13. subprocess
  14. logging模块
  15. re正则表达式

 

1.模块介绍

模块,用一砣代码实现了某个功能的代码集合。 

类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。

如:os 是系统相关的模块;file是文件操作相关的模块

模块分为三种:

  • 自定义模块
  • 内置标准模块(又称标准库)
  • 开源模块

自定义模块 和开源模块的使用参考 http://www.cnblogs.com/wupeiqi/articles/4963027.html

 

2.time & datetime模块

import time

# print(time.time()/60/60/24/365)   #时间戳:秒  从1970年1月份开始
# print(time.altzone/60/60)      #返回与utc时间的时间差,以秒计算\
# print(time.asctime())          #返回时间格式"Fri Aug 19 11:14:16 2016",
#
# print(time.localtime())        #返回本地时间 的struct time对象格式 tm_wday=6  周日是第6提天,周1是第0天
# t = time.localtime()
# print(t.tm_year,t.tm_mon)      #可以自定义要显示的内容
# t1 = time.localtime(time.time()-(60*60*24))     #减去一天的时间
# print(t1)
#
# print(time.ctime())            #返回Fri Aug 19 12:38:29 2016 格式, 同上

#自定义展示时间格式
# print(time.strftime('%Y-%m-%d %H:%M:%S'))
# struct_time=time.localtime(time.time()-86400)
# print(time.strftime('%Y-%m-%d %H:%M:%S',struct_time))       #获取前一台的时间

# # 日期字符串 转成  时间戳
# print(time.strptime('2017-02-23','%Y-%m-%d'))       #把字符串转成时间对象
# t = time.strptime('2017-02-23','%Y-%m-%d')
# print(time.mktime(t))                               #把字符串转换成时间戳


#将时间戳转为字符串格式
# print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
# print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式



# #时间加减
# import datetime
# print(datetime.datetime.now())          #打印当前日期
# print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
#
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
#
# c_time  = datetime.datetime.now()
# print(c_time.replace(minute=3,hour=2)) #时间替换
View Code

 

DirectiveMeaningNotes
%a Locale’s abbreviated weekday name.  
%A Locale’s full weekday name.  
%b Locale’s abbreviated month name.  
%B Locale’s full month name.  
%c Locale’s appropriate date and time representation.  
%d Day of the month as a decimal number [01,31].  
%H Hour (24-hour clock) as a decimal number [00,23].  
%I Hour (12-hour clock) as a decimal number [01,12].  
%j Day of the year as a decimal number [001,366].  
%m Month as a decimal number [01,12].  
%M Minute as a decimal number [00,59].  
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%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. (3)
%w Weekday as a decimal number [0(Sunday),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. (3)
%x Locale’s appropriate date representation.  
%X Locale’s appropriate time representation.  
%y Year without century as a decimal number [00,99].  
%Y Year with century as a decimal number.  
%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.

http://images2015.cnblogs.com/blog/720333/201608/720333-20160819123407390-767693951.png

 

 

 

 

3.random

# -*- coding: UTF-8 -*-
#blog:http://www.cnblogs.com/linux-chenyang/
#random ,string模块
import random
print(random.random())                  #生成随机数
print(random.randint(1,10))             #1~10以内随机生成一个数
print(random.randrange(1,20,2))         #步长为2,永远显示奇数
print(random.sample([1,2,3,4,5,6,63,23,543],2)) #随机取两个值
print(random.sample(range(100),5))

#生成随机验证码
import random,string

print(string.digits)                        #显示所有的数字
print(string.ascii_letters)                 #显示所有的英文字母
print(string.ascii_lowercase)               #显示小写英文字母
print(string.ascii_uppercase)               #显示大小英文字符

souce = string.digits+string.ascii_letters

print(souce)
print(''.join(random.sample(souce,6)))

#生成随机验证码2
import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print(checkcode)
View Code

4.os模块

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
os.curdir  返回当前目录: ('.')
os.pardir  获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    可生成多层递归目录
os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
os.stat('path/filename')  获取文件/目录信息
os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep    输出用于分割文件路径的字符串
os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  运行shell命令,直接显示
os.environ  获取系统环境变量
os.path.abspath(path)  返回path规范化的绝对路径
os.path.split(path)  将path分割成目录和文件名二元组返回
os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)  返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  如果path是绝对路径,返回True
os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
View Code

6.shutil

高级的 文件、文件夹、压缩包 处理模块

# -*- coding: UTF-8 -*-
#blog:http://www.cnblogs.com/linux-chenyang/
import shutil

#shutil.copyfileobj(fsrc, fdst[, length])   fsrc和fdst表示对象,不是文件名
#f = open("testfile.log")
#f1 = open("testnew.log","w")
#shutil.copyfileobj(f,f1)

#shutil.copyfile(src, dst)   直接输入文件名copy
#shutil.copyfile(r"D:\pycharm\s16\day5\access.log","testnew2.log")

#shutil.copymode(src, dst)   仅拷贝权限。内容、组、用户均不变

#shutil.copy(src, dst)  拷贝文件和权限

#shutil.copy2(src, dst) 拷贝文件和状态信息

#shutil.ignore_patterns(*patterns)
#shutil.copytree(src, dst, symlinks=False, ignore=None)
#递归的去拷贝文件
#例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
#可以过滤目录和指定的文件
#shutil.copytree("D:\\pycharm\s16\day5",'D:\\pycharm\s16\day6\Test',ignore=shutil.ignore_patterns('目录','access.log'))

#shutil.rmtree(path[, ignore_errors[, onerror]])  递归的去删除文件,目录,不能指定过滤条件
#shutil.rmtree('D:\\pycharm\s16\day6\Test')

#shutil.move(src, dst)   递归的去移动文件
View Code

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对象
#压缩一个zip文件
shutil.make_archive('day5', 'zip','D:\\pycharm\s16\day5')

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

#压缩
z = zipfile.ZipFile('lijun.zip','w')

z.write("D:\\pycharm\s16\day5\ccess.log",arcname="ccess.log")   #不要目录
z.write("D:\\pycharm\s16\day6")
z.write('类.py')

z.close()

#解压
z = zipfile.ZipFile('lijun.zip', 'r')
z.extractall()                          #()里面可以添加文件名,只解压一个
z.extract(path="C:\\zip3")              #指定解压路径和名字
z.close()
View Code
import tarfile

# 压缩
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
tar.close()

# 解压
tar = tarfile.open('your.tar','r')
tar.extractall()  # 可设置解压地址
tar.close()
View Code

 7.json & pickle

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

 

pickle运用场景:游戏的存档,虚拟机的快照

# -*- coding: UTF-8 -*-
#blog:http://www.cnblogs.com/linux-chenyang/
#数据是个字典
#1.往文件里写东西,只能传人字符串和bytes格式,像数字,字典,列表都是内存的数据类型,只能在内存里用,不能在硬盘上写。
#解决方法:字典存的时候先用str()函数转成字符串的形式,读的时候在用eval()函数转成字典
#
#把内存数据类型转成字符串这就叫数据的序列化
#从字符串转成内存里的数据类型叫反序列化
#
#pickle就是专门用于以上场景:必须是字节的形式
#案例:在一个脚本里写,来另外一个脚本里读,文件的名字叫accoun.db

import pickle

account = {
    'id':622202020011458,
    'credit':50000,
    'balance':8000,
    'expire_date':"2020-5-21",
    'passwd':'123455'
}

f = open("account.db","wb")

f.write(pickle.dumps(account))              #序列化
#pickle.dump(account.f)

f.close()



####################
# -*- coding: UTF-8 -*-
#blog:http://www.cnblogs.com/linux-chenyang/
import  pickle
f = open('account.db',"rb")

account = pickle.loads(f.read())            #反序列化
#pickle.load(f)

print(account)


#输出:
{'credit': 50000, 'balance': 8000, 'passwd': '123455', 'expire_date': '2020-5-21', 'id': 622202020011458}
View Code

json的用法和pickie用法一样,只不过要将wb和rb的方式改成w和r

#案例:在一个脚本里写,来另外一个脚本里读,文件的名字叫accoun.db

import json as pickle

account = {
    'id':622202020011458,
    'credit':50000,
    'balance':8000,
    'expire_date':"2020-5-21",
    'passwd':'123455'
}

f = open("account.db","w")

f.write(pickle.dumps(account))              #序列化
#pickle.dump(account.f)

f.close()


########
import  json as pickle
f = open('account.db',"r")

account = pickle.loads(f.read())            #反序列化
#pickle.load(f)

print(account)


#输出:这时候account.db里的内容也直接可以显示,pickle里的account.db内容是显示不了的

{'expire_date': '2020-5-21', 'balance': 8000, 'credit': 50000, 'passwd': '123455', 'id': 622202020011458}
View Code

pickle和json的区别:

  • pickle可以支持序列化python中的任何的数据类型,json只支持str,float,set,dict,list,tuple。
  • pickle只支持python,而json是一个通用的序列化的一个格式(举列:你可以把python的程序序列化后传给java)。

 8.shelve模块

 

11.configparser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 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['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
   config.write(configfile)

写完了还可以再读出来哈。

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
View Code

configparser增删改查语法

[section1]
k1 = v1
k2:v2
  
[section2]
k1 = v1
 
import ConfigParser
  
config = ConfigParser.ConfigParser()
config.read('i.cfg')
  
# ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options
  
#item_list = config.items('group2')
#print item_list
  
#val = config.get('group1','key')
#val = config.getint('group1','key')
  
# ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w"))
  
#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w"))
  
  
#config.set('group2','k1',11111)
#config.write(open('i.cfg', "w"))
  
#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))
View Code

 

13.subprocess模块

subprocess – 创建附加进程
subprocess模块提供了一种一致的方法来创建和处理附加进程,与标准库中的其它模块相比,提供了一个更高级的接口。用于替换如下模块:
os.system() , os.spawnv() , os和popen2模块中的popen()函数,以及 commands().

常用subprocess方法示例:(linux python3环境下演示)

1.subprocess.run的用法

#每执行一个subprocess命令,就想当于启动了一个进程,启动了一个终端执行命令

>>> subprocess.run("df")
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda2        4128448  779452   3139284  20% /
tmpfs            6092252       0   6092252   0% /dev/shm
/dev/sda7      379731360  342792 360099276   1% /data0
/dev/sda5        8256952  154020   7683504   2% /tmp
/dev/sda3       12385456 3583720   8172592  31% /usr
/dev/sda6        8256952  985492   6852032  13% /var
CompletedProcess(args='df', returncode=0)

>>> subprocess.run(['df','-h'])                #实际是个列表的形式,假如直接写入df -h是会报错    
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda2       4.0G  762M  3.0G  20% /
tmpfs           5.9G     0  5.9G   0% /dev/shm
/dev/sda7       363G  335M  344G   1% /data0
/dev/sda5       7.9G  151M  7.4G   2% /tmp
/dev/sda3        12G  3.5G  7.8G  31% /usr
/dev/sda6       7.9G  963M  6.6G  13% /var
CompletedProcess(args=['df', '-h'], returncode=0)            

>>> subprocess.run(['df','-h','|','grep','/dev/sda7'])   #遇到有管道符的这种,这样的方式可以执行出结果,但是会报错
df: `|': No such file or directory
df: `grep': No such file or directory
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda7       363G  335M  344G   1% /data0
CompletedProcess(args=['df', '-h', '|', 'grep', '/dev/sda7'], returncode=1)

>>> subprocess.run("df -h | grep /dev/sda7",shell=True)    #利用这种方法可以解决管道符报错的问题
/dev/sda7       363G  335M  344G   1% /data0
CompletedProcess(args='df -h | grep /dev/sda7', returncode=0)

>>> a = subprocess.run("df -h | grep /dev/sda7",shell=True)  #只会保存命令的执行状态,不会保存具体输出的内容
/dev/sda7       363G  335M  344G   1% /data0
>>> print(a)
CompletedProcess(args='df -h | grep /dev/sda7', returncode=0)
>>> a.returncode
0
   
View Code

2.subprocess.call,执行命令,执行命令,返回命令执行状态 , 0 or 非0

>>> subprocess.call("df -h | grep /dev/sda7",shell=True)
/dev/sda7       363G  335M  344G   1% /data0
0

3.subprocess.check_all,执行命令,如果命令结果为0,就正常返回,否则抛异常

>>> a = subprocess.check_all("df -ssss | grep /dev/sda7",shell=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'subprocess' has no attribute 'check_all'

4.subprocess.getstatusoutput,接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果

>>> subprocess.getstatusoutput("df -h | grep /dev/sda7")  #不用加shell参数的命令也可以正常执行
(0, '/dev/sda7       363G  335M  344G   1% /data0')

5.subprocess.getoutput,接收字符串格式命令,并返回结果

>>> subprocess.getoutput("df -h | grep /dev/sda7")  #结果
'/dev/sda7       363G  335M  344G   1% /data0'

6.subprocess.check_output,执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res

>>> res=subprocess.check_output("df -h | grep /dev/sda7",shell=True)  #直接输出的就是结果
>>> res
b'/dev/sda7       363G  335M  344G   1% /data0\n'

#上面那些方法,底层都是封装的subprocess.Popen
poll()
Check if child process has terminated. Returns returncode

wait()
Wait for child process to terminate. Returns returncode attribute.


terminate() 杀掉所启动进程
communicate() 等待任务结束

stdin 标准输入
stdout 标准输出
stderr 标准错误

pid
The process ID of the child process.

>>> res=subprocess.Popen("df -hT | grep /dev/sda7",shell=True,stdout=subprocess.PIPE) #两个进程之间是不能直接通信的,python和shell,第一条命令就相当于建立个管道,将命令输出过去,结果在传过来
>>> res.stdout.read()
b'/dev/sda7      ext4   363G  335M  344G   1% /data0\n'

>>> res=subprocess.Popen("df -hT | grep /dev/sda7",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)  #假如有错误的信息也想传过来,就加stderr=subprocess.PIPE
>>> res.stdout.read()
b'/dev/sda7      ext4   363G  335M  344G   1% /data0\n'

例子:

1.poll()和wait()的用法

#执行一个命令,不知道什么时间才会执行完,要是直接read读的时候的话就会卡住。可以先用poll()看下命令是否执行完,然后在去read

>>> res=subprocess.Popen("top -bn 5",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

>>> print(res.poll())
None

>>> print(res.poll())       #已经执行完
0

>>> res.stdout.read()    #这时就不会卡了,直接可以看到输出的结果

>>> print(res.wall())      #只是显示命令的执行状态
View Code

2.terminate()和communicate()的用法

>>> res=subprocess.Popen("df -h | grep /dev/sda7;sleep 10",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)  #执行一个时间长的命令
>>> res.poll()                          #查看命令好没有执行完
>>> res.terminate()                 #杀掉进程
>>> res.poll()
-15
>>> res.stdout.read()               #然后立马就可以看到结果
b'/dev/sda7       363G  335M  344G   1% /data0\n'  


#communicate()的应用场景,假如我备份一个东西,我觉得半个小时的时间就可以搞定,假如超过这个时间我就认为是异常了,不用在哪傻等了,开始排错
>>> res=subprocess.Popen("df -h | grep /dev/sda7;sleep 100",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

>>> res.communicate(timeout=2)    #执行这个命令会卡这,2秒后才会输出结果
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/subprocess.py", line 1068, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "/usr/local/lib/python3.5/subprocess.py", line 1699, in _communicate
    self._check_timeout(endtime, orig_timeout)
  File "/usr/local/lib/python3.5/subprocess.py", line 1094, in _check_timeout
    raise TimeoutExpired(self.args, orig_timeout)
subprocess.TimeoutExpired: Command 'df -h | grep /dev/sda7;sleep 100' timed out after 2 seconds




        
View Code

 

可用参数:

 

      • args:shell命令,可以是字符串或者序列类型(如:list,元组)
      • bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
      • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
      • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
      • close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
        所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
      • shell:同上
      • cwd:用于设置子进程的当前目录
      • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
      • universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
      • startupinfo与createionflags只在windows下有效
        将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

14.logging模块

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()info()warning()error() and critical() 5个级别,下面我们看一下怎么用。

最简单的用法:

import logging
 
logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")
 
#输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down
View Code

看一下这几个日志级别分别代表什么意思

 

Level When it’s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.

如果想把日志写到文件里,也很简单

import logging

logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')



#example.log文件内容,level定义日志级别,只要比debug高的就打印出来
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
View Code

感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!

import logging

logging.basicConfig(filename='example.log',
                    format='%(asctime)s %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p',
                    level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')


#example.log文件里的内容
02/24/2017 04:19:13 PM This message should go to the log file
02/24/2017 04:19:13 PM So should this
02/24/2017 04:19:13 PM And this, too
View Code

在日志中显示调用的文件名和函数,一般还要加上%(lineno)d

import logging

logging.basicConfig(filename='example.log',
                    format='%(asctime)s %(filename)s %(funcName)s %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p',
                    level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')


def sayhi():
    logging.info('call logging in sayhi')

sayhi()


#example.log文件里的内容
02/24/2017 04:46:24 PM logging模块.py <module> This message should go to the log file
02/24/2017 04:46:24 PM logging模块.py <module> So should this
02/24/2017 04:46:24 PM logging模块.py <module> And this, too
02/24/2017 04:46:24 PM logging模块.py sayhi call logging in sayhi
View Code

日志格式

%(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

用户输出的消息

 

如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了


Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适:

logger提供了应用程序可以直接使用的接口;

handler将(logger创建的)日志记录发送到合适的目的输出;

filter提供了细度设备来决定输出哪条日志记录;

formatter决定日志记录的最终输出格式。

 

 

logger
每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:
LOG=logging.getLogger(”chat.gui”)
而核心模块可以这样:
LOG=logging.getLogger(”chat.kernel”)

Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。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(lel):指定被处理的信息级别,低于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 每天凌晨

# -*- coding: UTF-8 -*-
#blog:http://www.cnblogs.com/linux-chenyang/
import logging

# create logger
logger = logging.getLogger('TEST-LOG')
logger.setLevel(logging.ERROR)              #全局的日志级别,比如message

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)                  #屏幕的日志级别

# create file handler and set level to warning
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)                #文件的日志级别
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')     #日志格式


# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)


# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)


# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')



#屏幕输出:
2017-02-24 19:19:24,027 - TEST-LOG - INFO - info message
2017-02-24 19:19:24,028 - TEST-LOG - WARNING - warn message
2017-02-24 19:19:24,029 - TEST-LOG - ERROR - error message
2017-02-24 19:19:24,030 - TEST-LOG - CRITICAL - critical message


#文件输出:
2017-02-24 19:19:24,028 - TEST-LOG - WARNING - warn message
2017-02-24 19:19:24,029 - TEST-LOG - ERROR - error message
2017-02-24 19:19:24,030 - TEST-LOG - CRITICAL - critical message


#全局日志级别>屏幕输出&文件输出
View Code

文件自动截断例子

# -*- coding: UTF-8 -*-
#blog:http://www.cnblogs.com/linux-chenyang/
import logging
from logging import handlers

# create logger
logger = logging.getLogger('TEST-LOG')
logger.setLevel(logging.DEBUG)              #全局的日志级别,比如message

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)                  #屏幕的日志级别

# create file handler and set level to warning
#fh =  handlers.TimedRotatingFileHandler("access.log",when="S",interval=5,backupCount=3)
fh = handlers.RotatingFileHandler("access.log",maxBytes=4,backupCount=3)
fh.setLevel(logging.WARNING)                #文件的日志级别
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')     #日志格式


# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)


# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)


# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
View Code

 

posted @ 2017-02-23 16:34  一只奔跑的乌龟  阅读(335)  评论(0编辑  收藏  举报