python运维常用相关模块
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.模块的分类
模块,用一砣代码实现了某个功能的代码集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操作相关的模块
模块分为三种:
1>.自定义模块:自定义的模块,顾名思义,就是你自己写的python程序,我们知道python的代码都存在一个以".py"结尾的文件中的,我们这样命名一个python脚本,吧后缀去掉就是模块名称,这个就是自定义模块,我举个例子:我写了一个yinzhengjie.py的文件。里面的内容我们可以忽略,如果我们要导入这个模块的话直接导入yinzhengjie这个模块名称就好了;
2>.内置模块:那么问题来了,我们学的cha(),id()等等所有的内置函数是模块吗?答案是否定的!不是!对内置函数不是内置模块,他们只是python解释器自带的一些功能,那么什么是内置模块呢?一会我会再我的博客中提到一些常用的内置模块;
3>.开源模块:这个就很好解释了,python语言的官网提供了一个供应开发人员上传你的代码到服务器上(https://pypi.python.org/pypi),然后客户端只要在命令行中输入安装命令就可以随意的在shell或者cmd的python解释器中调用这个第三方模块,比如:pip install paramiko.
二.内置模块解析:
1.OS模块详解
1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #@author :yinzhengjie
4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
5 #EMAIL:y1053419035@qq.com
6 import os
7 #1.获取当前工作目录,即当前python脚本工作的目录路径
8 print(os.getcwd())
9 #2.改变当前脚本工作目录;相当于shell下cd,记住,这个是没有返回值的哟!
10 print(os.chdir(r"D:\python\daima\DAY1"))
11 #3.返回当前目录: ('.')
12 print(os.curdir)
13 #4.获取当前目录的父目录字符串名:('..')
14 print(os.pardir)
15 #5.可生成多层递归目录(创建目录),生产完毕后返回一个None值
16 print(os.makedirs("D:\python\daima\DAY10"))
17 #6.若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推(和上面的相反,就是删除目录。)
18 print(os.removedirs("D:\python\daima\DAY10"))
19 #7.生成单级目录;相当于shell中mkdir dirname,如果当前目录已经存在改目录就会报错!
20 print(os.mkdir("DAY10"))
21 #8.删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname,如果当前目录没有改目录就会报错!
22 print(os.rmdir("DAY10"))
23 #9.列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
24 print(os.listdir("D:\python\daima"))
25 #10.删除一个文件
26 # os.remove("locked.txt")
27 #11.重命名文件/目录
28 # os.rename("oldname","newname")
29 #12.os.stat('path/filename') 获取文件/目录信息
30 print(os.stat("D:\python\daima\DAY4"))
31 #13.输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
32 print(os.sep)
33 #14.输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
34 print(os.linesep)
35 #15.输出用于分割文件路径的字符串
36 print(os.pathsep)
37 #16.输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
38 print(os.name)
39 #17.运行shell或者windows命令,直接显示命令的输出结果,可以将这个数据存放在一个变量中哟
40 # print(os.system("dir"))
41 #18.返回path规范化的绝对路径
42 print(os.path.abspath("user_info.txt"))
43 #19.将path分割成目录和文件名二元组返回
44 print(os.path.split(r"D:\python\daima\DAY1\user_info.txt"))
45 #20.返回path的目录。其实就是os.path.split(path)的第一个元素
46 print(os.path.dirname(r"D:\python\daima\DAY1\user_info.txt"))
47 #21.os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
48 print(os.path.basename(r"D:\python\daima\DAY1\user_info.txt"))
49 #22.os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
50 print(os.path.exists(r"D:\python\daima\DAY1\user_info.txt"))
51 #23.os.path.isabs(path) 如果path是绝对路径,返回True
52 print(os.path.isabs(r"D:\python\daima\DAY1\user_info.txt"))
53 #24.os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
54 print(os.path.isfile(r"D:\python\daima\DAY1\user_info.txt"))
55 #25.os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
56 print(os.path.isdir(r"D:\python\daima\DAY1\user_info.txt"))
57 #26.os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
58 print(os.path.join(r"user_info.txt",r"D:\python\daima\DAY1\user_info.txt"))
59 #27.os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
60 print(os.path.getatime(r"D:\python\daima\DAY1\user_info.txt"))
61 #28.os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
62 print(os.path.getmtime(r"D:\python\daima\DAY1\user_info.txt"))
63 '''
64 更多关于os模块的使用方法请参考:https://docs.python.org/2/library/os.html?highlight=os#module-os
65 '''
66
67
68 #以上代码执行结果如下:
69 D:\python\daima\DAY4
70 None
71 .
72 ..
73 None
74 None
75 None
76 None
77 ['.idea', 'DAY1', 'DAY2', 'DAY3', 'DAY4', 'DAY5', '__pycache__']
78 os.stat_result(st_mode=16895, st_ino=22799473113577966, st_dev=839182139, st_nlink=1, st_uid=0, st_gid=0, st_size=4096, st_atime=1487743397, st_mtime=1487743397, st_ctime=1486692902)
79 \
80
81
82 ;
83 nt
84 D:\python\daima\DAY1\user_info.txt
85 ('D:\\python\\daima\\DAY1', 'user_info.txt')
86 D:\python\daima\DAY1
87 user_info.txt
88 True
89 True
90 True
91 False
92 D:\python\daima\DAY1\user_info.txt
93 1483869109.7747889
94 1483869109.7758367
2.sys模块常用方法
1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #@author :yinzhengjie
4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
5 #EMAIL:y1053419035@qq.com
6 import sys
7 #1.获取Python解释程序的版本信息
8 print(sys.version)
9 #2.返回操作系统平台名称
10 print(sys.platform)
11 #3.返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
12 print(sys.path)
13 #4.退出程序,正常退出时exit(0),如果不写数字的话,默认就是0
14 # print(sys.exit(100))
15 #5.命令行参数List,第一个元素是程序本身路径
16 # path_info = sys.argv[1]
17 #6.显示当前系统最大的Int值
18 print(sys.maxsize)
19
20 '''
21 更多使用方法请参考:https://docs.python.org/2/library/sys.html?highlight=sys#module-sys
22 '''
23
24
25 #以上代码执行结果如下:
26
27 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)]
28 win32
29 ['D:\\python\\daima\\DAY4', 'D:\\python\\daima', 'C:\\Users\\yzj\\AppData\\Local\\Programs\\Python\\Python35-32\\python35.zip', 'C:\\Users\\yzj\\AppData\\Local\\Programs\\Python\\Python35-32\\DLLs', 'C:\\Users\\yzj\\AppData\\Local\\Programs\\Python\\Python35-32\\lib', 'C:\\Users\\yzj\\AppData\\Local\\Programs\\Python\\Python35-32', 'C:\\Users\\yzj\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages']
30 2147483647
3.json和pickle模块详解
1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #@author :yinzhengjie
4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
5 #EMAIL:y1053419035@qq.com
6 import pickle
7 '''
8 pickle:
9 1.>用于python特有的类型 和 python的数据类型间进行转换
10 2.>pickle模块提供了四个功能:dumps、dump、loads、load.
11 补充说明:将数据通过特殊的形式转换成只有python解释器识别的字符串,这个过程我们叫做序列化,而把哪些python能够识别的字符串转换成我们能看懂的叫做反序列化。
12 '''
13 data_info = {"name":"尹正杰","password":"123"}
14 #1.将数据通过特殊的形式转换为只有python语言知识的字符串并写入文件
15 # pickle_str = pickle.dumps(data_info)
16 # print(pickle_str)
17 # f = open("test.txt","wb")
18 # f.write(pickle_str)
19 #2.上面的写入文件的方法也可以这么玩,看起来更简单
20 # with open("test_1.txt","wb") as fb:
21 # pickle.dump(data_info,fb)
22 #我们知道将数据存入文件,那么我们怎么把存入文件的东西读出来呢?
23 #方法一:
24 # f = open("test_1.txt","rb")
25 # print(pickle.loads(f.read()))
26 #方法二:
27 f = open("test_1.txt","rb")
28 print(pickle.load(f))
1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #@author :yinzhengjie
4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
5 #EMAIL:y1053419035@qq.com
6 import json
7 '''
8 用于序列化的两个模块
9 1>.json:用于字符串 和 python数据类型间进行转换
10 2>.pickle:用于python特有的类型和python的数据类型间进行转换
11 json模块提供了四个功能:dumps、dump、loads、load
12 pickle模块提供了四个功能:dumps、dump、loads、load
13 '''
14 accounts = {
15 "id":521,
16 "name":"yinzhengjie",
17 "banlance":"9000"
18 }
19 #存数据方式一:
20 # f = open(r"D:\python\daima\DAY4\test_2.txt","w")
21 # json_str = json.dumps(accounts)
22 # f.write(json_str)
23 #存数据方式二:
24 # with open(r"D:\python\daima\DAY4\test_2.txt","w") as fp:
25 # json.dump(accounts,fp)
26 #读取数据的方法一:
27 # f = open("test_2.txt","r")
28 # print(json.loads(f.read()))
29 #方法二:
30 f = open("test_2.txt","r")
31 print(json.load(f))
对比json和pickle的异同:
1>.相同点:都是用于系列化和反序列化的模块。
2>.不同点:json是在所有语言都通用的数据存储格式,而pickle是仅仅只有python语言独有的存储格式。
4.time模块与datetime模块详解
1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #@author :yinzhengjie
4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
5 #EMAIL:y1053419035@qq.com
6 import time
7 #1.测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
8 print(time.process_time())
9 #2.返回与utc时间的时间差,以秒计算
10 print(time.altzone)
11 #3.返回默认时间格式
12 print(time.asctime())
13 #4.返回本地时间的struct_time对象格式
14 print(time.localtime())
15 #5.返回utc时间的struc时间对象格式
16 print(time.gmtime(time.time()-800000))
17 #6.返回本地时间格式,
18 print(time.asctime(time.localtime()))
19 #7.返回时间格式,同上
20 print(time.ctime())
21 #8.将日期字符串转成struct时间对象格式
22 string_2_struct = time.strptime("2016/05/22","%Y/%m/%d")
23 print(string_2_struct)
24 #9.将struct时间对象转成时间戳
25 struct_2_stamp = time.mktime(string_2_struct)
26 print(struct_2_stamp)
27 #10.将utc时间戳转换成struct_time格式
28 print(time.gmtime(time.time()-86640))
29 #11.将utc struct_time格式转成指定的字符串格式
30 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))
1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #@author :yinzhengjie
4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
5 #EMAIL:y1053419035@qq.com
6 import time,datetime
7 #1.打印当前系统时间
8 print(datetime.datetime.now())
9 #2.时间戳直接转成日期格式如:2017-02-22
10 print(datetime.date.fromtimestamp(time.time()))
11 #3.当前时间+3天
12 print(datetime.datetime.now() + datetime.timedelta(3))
13 #4.当前时间-3天
14 print(datetime.datetime.now() + datetime.timedelta(-3))
15 #5.当前时间+3小时
16 print(datetime.datetime.now() + datetime.timedelta(hours=3))
17 #6.当前时间+30分
18 print(datetime.datetime.now() + datetime.timedelta(minutes=30))
19 #7.时间替换
20 c_time = datetime.datetime.now()
21 print(c_time.replace(minute=3,hour=2))
关于时间的一个转换流程图:
测试代码如下:
1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #@author :yinzhengjie
4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
5 #EMAIL:y1053419035@qq.com
6 import time
7 #1.将日期转换成struct_time格式,会以一个tuple的形式打印出来
8 # struct_time = time.strptime("2017/2/22","%Y/%m/%d") #注意分割的符号要保持一致哟,我这里分割的符号是“/”
9 struct_time = time.strptime("2017-2-22 17:29:30","%Y-%m-%d %H:%M:%S") #ye ky 注意分割的符号要保持一致哟,我这里分割的符号是“-”
10 print(struct_time)
11 #2.将struct_time格式转换成时间戳的形式
12 stamp_time = time.mktime(struct_time)
13 print(stamp_time)
14 #3.将时间戳的形式,转换成日期格式
15 date_time = time.gmtime(stamp_time)
16 print(date_time)
17 print(time.strftime("%Y-%m-%d %H:%M:%S",date_time))
关于参数的详细说明如下:
| Directive | Meaning | Notes |
|---|---|---|
%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. |
5.random模块详解
1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_
3 #@author :yinzhengjie
4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
5 #EMAIL:y1053419035@qq.com
6 import random
7 '''
8 random:
9 是用来生成随机数字的。
10 '''
11 #举例子:
12 print(random.random())
13 print(random.randint(1,20))
14 print(random.randrange(1,10))
15 '''
16 random 都有哪些应用呢?
17 '''
18 #生成随机验证码,版本一:
19 checkcode = ''
20 for i in range(6): #修改后面的数字表示随机生成的数字个数,因为要循环6次
21 current = random.randrange(0,4)
22 if current != i:
23 temp = chr(random.randint(65,90))
24 else:
25 temp = random.randint(0,9)
26 checkcode += str(temp)
27 print(checkcode)
28 #生成随机验证码,版本二
29 import string
30 source = string.digits + string.ascii_lowercase
31 print("".join(random.sample(source,6))) #修改后面的数字表示随机生成的数字个数
6.logging模块
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug(), info(), warning(), error() and critical() 5个级别,从左往右依次增加告警级别,下面我们看一下怎么用。
看一下这几个日志级别分别代表什么意思
| 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. |
日志格式
|
%(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 |
用户输出的消息 |
A.简单的logging模块案例演示:
1>.初探logging模块:
1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 #EMAIL:y1053419035@qq.com 6 import logging 7 logging.warning("user [尹正杰] attempted wrong password more than 3 times") 8 logging.critical("server is down") 9 10 11 以上代码执行结果如下: 12 WARNING:root:user [尹正杰] attempted wrong password more than 3 times 13 CRITICAL:root:server is down
2>.如果想把日志写到文件里,也很简单:
1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 #EMAIL:y1053419035@qq.com 6 import logging 7 logging.basicConfig(filename='yinzhengjie.log', level=logging.INFO) 8 logging.debug('This message should go to the log file') 9 logging.info('So should this') 10 logging.warning('And this, too') 11 12 ''' 13 补充说明: 14 logging.basicConfig中的参数level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子,第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。 15 ''' 16 17 18 #查看'yinzhengjie.log'文件内容如下: 19 INFO:root:So should this 20 WARNING:root:And this, too
B.如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识了:
1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 #EMAIL:y1053419035@qq.com 6 ''' 7 Python使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适: 8 1>.logger提供了应用程序可以直接使用的接口; 9 2>.handler将(logger创建的)日志记录发送到合适的目的输出; 10 3>.filter提供了细度设备来决定输出哪条日志记录; 11 4>.formatter决定日志记录的最终输出格式。 12 '''
1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 #EMAIL:y1053419035@qq.com 6 ''' 7 Python使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适: 8 1>.logger提供了应用程序可以直接使用的接口; 9 2>.handler将(logger创建的)日志记录发送到合适的目的输出; 10 3>.filter提供了细度设备来决定输出哪条日志记录; 11 4>.formatter决定日志记录的最终输出格式。 12 ''' 13 14 15 #logger 16 ''' 17 每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名. 18 #1>.比如聊天工具的图形界面模块可以这样获得它的Logger: 19 LOG=logging.getLogger(”chat.gui”) 20 #2>.而核心模块可以这样: 21 LOG=logging.getLogger(”chat.kernel”) 22 #3>.指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高 23 Logger.setLevel(lel) 24 #4>.添加或删除指定的filter 25 Logger.addFilter(filt)、Logger.removeFilter(filt) 26 #5>.增加或删除指定的handler 27 Logger.addHandler(hdlr)、Logger.removeHandler(hdlr) 28 #6>.可以设置的日志级别 29 Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical() 30 ''' 31 32 33 #handler 34 ''' 35 handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler 36 #1>.指定被处理的信息级别,低于lel级别的信息将被忽略 37 Handler.setLevel(lel) 38 #2>.给这个handler选择一个格式 39 Handler.setFormatter() 40 #3>.新增或删除一个filter对象 41 Handler.addFilter(filt)、Handler.removeFilter(filt) 42 每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler: 43 #1>.logging.StreamHandler 44 使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:StreamHandler([strm]),其中strm参数是一个文件对象。默认是sys.stderr 45 2) logging.FileHandler 46 和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:FileHandler(filename[,mode]),filename是文件名,必须指定一个文件名。mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。 47 3) logging.handlers.RotatingFileHandler 48 这个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并不会被更名,而是被删除。 49 4) logging.handlers.TimedRotatingFileHandler 50 这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]]),其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义,interval是时间间隔。when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:(S[秒],M[分],H[小时],D[天],W[每星期(interval==0时代表星期一)],midnight[每天凌晨] 51 '''