re(正则)模块

常用方法

  • findall()

    以列表返回所有满足条件的结果

     import  re
     print(re.findall('\d','a1b2c2abc123'))#['1', '2', '2', '1', '2', '3']
  • search()

    查找到第一个匹配信息就返回一个包含匹配信息的对象(未找到时返回None),该对象通过group()函数查看结果

     import re
    
     str = 'a1b2c2abc123'
     
  • match()

    从字符串开始位置匹配,其它同search()

     import re
    
     str = 'a1b2c2abc123'
     print(re.match('\d', str).group() if re.match('\d', str) else '未找到')  # 未找到
     print(re.match('a.+', str).group() if re.match('a', str) else '未找到')  # a1b2c2abc123
  • split()

    以正则匹配到的字符切割字符串,返回切割后的字符串列表

     import re
    
     str = 'a1b2c2abc123'
     print(re.split('[123]', str))  # ['a', 'b', 'c', 'abc', '', '', '']
  • sub()

    将匹配到的内容替换为指定内容,返回替换后的字符串()

     import re
    
     str = 'a1b2c2abc123'
     print(re.sub('[123]', 'A', str))  # aAbAcAabcAAA
  • subn()

    将匹配到的内容替换为指定内容,返回元祖.第一个值是替换后的字符串,第二个值是替换的次数

     import re
    
     str = 'a1b2c2abc123'
     print(re.subn('[123]', 'A', str))  # ('aAbAcAabcAAA', 6)
  • compile()

    将正则表达式编译为字节码对象,可多次调用

     import re
    
     str = 'a1b2c2abc123'
     re_obj = re.compile('[123]')
     print(re_obj.sub('A', str))  # aAbAcAabcAAA
     print(re_obj.subn('A', str))  # ('aAbAcAabcAAA', 6)
     print(re_obj.findall(str))  # ['1', '2', '2', '1', '2', '3']
     print(re_obj.split(str))  # ['a', 'b', 'c', 'abc', '', '', '']
     print(re_obj.match(str))  # None
     
  • finditer()

    返回一个存放匹配结果的迭代器

     import re
    
     str = 'a1b2c2abc123'
     result = re.finditer('\d', str)
     print(result)  # <callable_iterator object at 0x00000000026F80F0>
    
     print([g.group() for g in result])  # ['2', '1', '2', '3']

优先级问题

  • findall()

    findall会优先把组匹配结果内容返回

    ?: 可取消优先返回组匹配结果

     import re
    
     print(re.findall('zz([a-y])', 'zze'))  # ['e']
     print(re.findall('zz(?:[a-y])', 'zze'))  # ['zze']
  • split()

    当正则包含组时,切割结果会保留分割内容

     import re
    
     str = 'a1b2c2abc123'
     print(re.split('\d', str))  # ['a', 'b', 'c', 'abc', '', '', '']
     print(re.split('(\d)', str))  # ['a', '1', 'b', '2', 'c', '2', 'abc', '1', '', '2', '', '3', '']

扩展

  • 组命名

    可通过'?P'给组命名

     import re
    
     str = '<title>python learning</title>'
     result = re.search('<(?P<tag_name>[a-z]+)>(?P<title>.+)</([a-z]+)>', str)
     print(result.group('title'))  # python learning
     print(result.group('tag_name'))  # title
     print(result.group())  # <title>python learning</title>

collections模块

新增的数据类型

  • namedtuple:带名称的元组

     from collections import namedtuple
    
     Point = namedtuple('point', ['x', 'y'])
     point1 = Point(1, 2)
     point2 = Point(2, 3)
     print(point1)  # point(x=1, y=2)
     print(point1.x, point1.y)  # 1 2
     print(point2)  # point(x=2, y=3)
     print(point2.x, point2.y)  # 2 3
  • deque:双向队列

     from collections import deque
    
     dq = deque([1, 2])
     dq.append('a')  # 尾部插入  [1,2,'a']
     dq.appendleft('b')  # 头部插入 ['b',1,2,'a']
     dq.insert(2, 3)  # ['b',1,3,2,'a']
     print(dq.pop())  # a 从后面取数据
    
     print(dq.popleft())  # b 从前面取数据
     print(dq)  # deque([1, 3])
  • OrderedDict:有序字典

     # 有序字典
     from collections import OrderedDict
    
     od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
     for k in od:
         print(k)
    
     # result:
     # a
     # b
     # c
  • defaultdict:默认字典

     from collections import defaultdict
    
     d = defaultdict(lambda: 5)  # 传入callable参数
     d['key1'] = 1
    
     print(d['key'])  # 5 不存在时使用默认值
  • Counter:计数器

     from collections import Counter
    
     c = Counter('abcdeabcdabcaba')
     print(c)  # Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

time(时间)模块

表示时间的三种方式

  • 时间戳(timestamp)

    通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量运行“type(time.time())”,返回的是float类型

  • 格式化的时间字符串(Format String)

    如:'1999-12-06'

    python中时间日期格式化符号:
    %y 两位数的年份表示(00-99)
    %Y 四位数的年份表示(000-9999)
    %m 月份(01-12)
    %d 月内中的一天(0-31)
    %H 24小时制小时数(0-23)
    %I 12小时制小时数(01-12)
    %M 分钟数(00=59)
    %S 秒(00-59)
    %a 本地简化星期名称
    %A 本地完整星期名称
    %b 本地简化的月份名称
    %B 本地完整的月份名称
    %c 本地相应的日期表示和时间表示
    %j 年内的一天(001-366)
    %p 本地A.M.或P.M.的等价符
    %U 一年中的星期数(00-53)星期天为星期的开始
    %w 星期(0-6),星期天为星期的开始
    %W 一年中的星期数(00-53)星期一为星期的开始
    %x 本地相应的日期表示
    %X 本地相应的时间表示
    %Z 当前时区的名称
    %% %号本身
  • 元组(struct_time)

    struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)

    索引(Index) 属性(Attribute) 值(Values)
    0 tm_year(年) 比如2011
    1 tm_mon(月) 1 - 12
    2 tm_mday(日) 1 - 31
    3 tm_hour(时) 0 - 23
    4 tm_min(分) 0 - 59
    5 tm_sec(秒) 0 - 60
    6 tm_wday(weekday) 0 - 6(0表示周一)
    7 tm_yday(一年中的第几天) 1 - 366
    8 tm_isdst(是否是夏令时) 默认为0

使用

  • 时间戳(timestamp)

     import time
     print(time.time())  # 1535813663.732
  • 格式化的时间字符串(Format String)

     import time
    
     print(time.strftime("%Y-%m-%d %X"))  # 2018-09-01 22:55:30
     print(time.strftime("%Y-%m-%d %H-%M-%S"))  # 2018-09-01 22-55-30
  • 元组(struct_time)

     import time
    
     print(
         time.localtime())  # time.struct_time(tm_year=2018, tm_mon=9, tm_mday=1, tm_hour=22, tm_min=56, tm_sec=31, tm_wday=5, tm_yday=244, tm_isdst=0)

转换

  • 时间戳(timestamp)和结构化时间(struct_time)

     import time
    
     # 时间戳-->结构化时间 localtime()
     print(time.localtime(
         1600000000))  # time.struct_time(tm_year=2020, tm_mon=9, tm_mday=13, tm_hour=20, tm_min=26, tm_sec=40, tm_wday=6, tm_yday=257, tm_isdst=0)
    
     # 结构化时间-->时间戳 mktime()
     print(time.mktime(time.localtime(1600000000)))  # 1600000000.0
  • 格式化的时间字符串(timestamp)和结构化时间(struct_time)

     import time
    
     # 结构化时间-->字符串时间
     # time.strftime("格式定义","结构化时间")  结构化时间参数若不传,则显示当前时间
     print(time.strftime("%Y-%m-%d %X"))  # 2018-09-01 23:06:43
     print(time.strftime("%Y-%m-%d", time.localtime(1600000000)))  # 2020-09-13
    
     # 字符串时间-->结构化时间
     # time.strptime(时间字符串,字符串对应格式)
     print(time.strptime("2018-09-01 23:06:43",
                         "%Y-%m-%d %X"))  # time.struct_time(tm_year=2018, tm_mon=9, tm_mday=1, tm_hour=23, tm_min=6, tm_sec=43, tm_wday=5, tm_yday=244, tm_isdst=-1)
     print(time.strptime("07/24/2017",
                         "%m/%d/%Y"))  # time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, tm_isdst=-1)

例子

  • 计算时间差

     import time
     last_time=time.mktime(time.strptime('1997-05-12 08:30:00','%Y-%m-%d %H:%M:%S'))
     time_now=time.mktime(time.strptime('2018-09-01 11:00:00','%Y-%m-%d %H:%M:%S'))
     dif_time=time_now-last_time
     struct_time = time.localtime(dif_time)
     print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(struct_time.tm_year-1970,struct_time.tm_mon-1,
                                            struct_time.tm_mday-1,struct_time.tm_hour,
                                            struct_time.tm_min,struct_time.tm_sec))

random(随机数)模块

使用

  • 随机小数

     import random
    
     print(random.random())  # 0.33630703804107664 大于0且小于1之间的小数
     print(random.uniform(1, 3))  # 2.0639651365332607 大于1小于3的小数
  • 随机整数

     import random
    
     print(random.randint(1,5))  # 2 大于等于1且小于等于5之间的整数
     print(random.randrange(1,10,2)) # 1 大于等于1且小于10之间的奇数
  • 随机选择返回

     import random
    
     # 随机选择一个返回
    
     # 随机选择多个返回,返回的个数为函数的第二个参数
     ', [4, 5]], 2))  # ['23', [4, 5]]
  • 打乱次序

     import random
    
     item = [1, 2, 3, 4, 5]
     random.shuffle(item)  # 打乱次序
     print(item)  # [4, 2, 5, 3, 1]

例子

  • 生成随机验证码字符串

     import random
    
     def v_code():
         code = ''
         for i in range(5):
             num = random.randint(0, 9)
             alf = chr(random.randint(65, 90))
             add = random.choice([num, alf])
             code = "".join([code, str(add)])
    
         return code
    
     print(v_code())

os模块

os模块是与操作系统交互的一个接口

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.system("bash command")  运行shell命令,直接显示
os.popen("bash command).read()  运行shell命令,获取执行结果
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd

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所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小

sys模块

sys模块是与python解释器交互的一个接口

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0),错误退出sys.exit(1)
sys.version        获取Python解释程序的版本信息
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称

序列化模块

序列化:将对象转成字符串

反序列化:将字符串转成对象

json

用于字符串和python数据类型间进行转换

  • dumps()和loads()

    dumps():序列化,将对象转成字符串

    loads():反序列化,将字符串转成对象

     import json
    
     dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
     str_dic = json.dumps(dic)  # 序列化:将一个字典转换成一个字符串
     print(type(str_dic), str_dic)  # <class 'str'> {"k3": "v3", "k1": "v1", "k2": "v2"}
     # 注意,json转换完的字符串类型的字典中的字符串是由""表示的
    
     dic2 = json.loads(str_dic)  # 反序列化:将一个字符串格式的字典转换成一个字典
     # 注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
     print(type(dic2), dic2)  # <class 'dict'> {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
    
     list_dic = [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]
     str_dic = json.dumps(list_dic)  # 也可以处理嵌套的数据类型
     print(type(str_dic), str_dic)  # <class 'str'> [1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]
     list_dic2 = json.loads(str_dic)
     print(type(list_dic2), list_dic2)  # <class 'list'> [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]
     import json
     f = open('file','w')
     json.dump({'国籍':'中国'},f)
     ret = json.dumps({'国籍':'中国'})
     f.write(ret+'\n')
     json.dump({'国籍':'美国'},f,ensure_ascii=False)
     ret = json.dumps({'国籍':'美国'},ensure_ascii=False)
     f.write(ret+'\n')
     f.close()
    
     # file:
     # {"\u56fd\u7c4d": "\u4e2d\u56fd"}{"\u56fd\u7c4d": "\u4e2d\u56fd"}
     # {"国籍": "美国"}{"国籍": "美国"}

    ensure_ascii

    参数说明:Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key
    ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为\uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。) 
    indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json
    separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。
    default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
    sort_keys:将数据根据keys的值进行排序。 
     import json
     data = {'username':['李华','二愣子'],'sex':'male','age':16}
     json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)
     print(json_dic2)
     #result:
     # {
     #   "age":16,
     #   "sex":"male",
     #   "username":[
     #     "李华",
     #     "二愣子"
     #   ]
     # }

    格式化输出

  • dump()和load()

    dumps():序列化,将对象转成字符串并通过文件句柄输出到文件

    loads():反序列化,通过文件句柄读取文件字符串内容并转成对象

     import json
     f = open('json_file','w')
     dic = {'k1':'v1','k2':'v2','k3':'v3'}
     json.dump(dic,f)  #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
     f.close()
    
     f = open('json_file')
     dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
     f.close()
     print(type(dic2),dic2)

pickle

用于python特有的类型和python的数据类型间进行转换

  • dumps()和loads()

    序列化,将对象转换为bytes

    反序列化,将bytes转换成对象

     str_dic = pickle.dumps(dic)
     print(
         str_dic)  # b'\x80\x03}q\x00(X\x02\x00\x00\x00k1q\x01X\x02\x00\x00\x00v1q\x02X\x02\x00\x00\x00k2q\x03X\x02\x00\x00\x00v2q\x04X\x02\x00\x00\x00k3q\x05X\x02\x00\x00\x00v3q\x06u.'
    
     dic2 = pickle.loads(str_dic)
     print(dic2)  # {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
    
     import time
  • dump()和load()

    序列化,将对象转换为bytes,并通过文件句柄保存到文件

    反序列化,通过文件句柄读取bytes并转换成对象

     import pickle
     import time
    
     struct_time = time.localtime(1000000000)
     print(
         struct_time)  # time.struct_time(tm_year=2001, tm_mon=9, tm_mday=9, tm_hour=9, tm_min=46, tm_sec=40, tm_wday=6, tm_yday=252, tm_isdst=0)
     f = open('pickle_file', 'wb')
     pickle.dump(struct_time, f)
     f.close()
    
     f = open('pickle_file', 'rb')
     struct_time2 = pickle.load(f)
     

shelve

通过文件句柄序列化同步到文件

 import shelve

 f1 = shelve.open('shelve_file')
 f1['key'] = {1: 'a'}
 f1.close()
 # writeback为True时,所做变更会同步到文件
 f2 = shelve.open('shelve_file', writeback=True)
 print(f2['key'])  # {1: 'a'}
 f2['key']['new_value'] = 'this was not here before'
 print(f2['key'])  # {1: 'a', 'new_value': 'this was not here before'}
 f2.close()

hashlib模块

md5和sha加密

 import hashlib

 str = '
 md5_helper = hashlib.md5()
 md5_helper.update(bytes(str, 'utf-8'))
 print(md5_helper.hexdigest())  # 202cb962ac59075b964b07152d234b70

 sha_helper = hashlib.sha1()
 sha_helper.update(bytes(str, 'utf-8'))
 print(sha_helper.hexdigest())  # 40bd001563085fc35165329ea1ff5c5ecbdbbeef

加盐

 import hashlib

 str = '
 md5_helper = hashlib.md5()
 md5_helper.update(bytes(str, 'utf-8'))
 print(md5_helper.hexdigest())  # 202cb962ac59075b964b07152d234b70
 # 加盐
 md5_salt_helper = hashlib.md5("salt".encode("utf8"))
 md5_salt_helper.update(bytes(str, 'utf-8'))
 print(md5_salt_helper.hexdigest())  # 8c4fb7bf681156b52fea93442c7dffc9

configparser模块

创建配置文件

 import configparser

 config = configparser.ConfigParser()

 config[',
                      'Compression': 'yes',
                      ',
                      'ForwardX11': 'yes'
                      }

 config['bitbucket.org'] = {'User': 'hg'}

 config[', 'ForwardX11': 'no'}

 with open('example.ini', 'w') as configfile:
     config.write(configfile)

 # example.ini:
 # [DEFAULT]
 # serveraliveinterval = 45
 # compression = yes
 # compressionlevel = 9
 # forwardx11 = yes
 #
 # [bitbucket.org]
 # user = hg
 #
 # [topsecret.server.com]
 # host
 # port = 50022
 # forwardx11 = no

查找

 import configparser

 config = configparser.ConfigParser()

 # ---------------------------查找文件内容,基于字典的形式

 print(config.sections())  # []

 config.read('example.ini')

 print(config.sections())  # ['bitbucket.org', 'topsecret.server.com']

 print('bytebong.com' in config)  # False
 print('bitbucket.org' in config)  # True

 print(config['bitbucket.org']["user"])  # hg

 print(config['DEFAULT']['Compression'])  # yes

 print(config['topsecret.server.com']['ForwardX11'])  # no

 print(config['bitbucket.org'])  # <Section: bitbucket.org>

 # 注意,有default会默认default的键
 for key in config['bitbucket.org']:
     print(key)
 # user
 # serveraliveinterval
 # compression
 # compressionlevel
 # forwardx11

 # 同for循环,找到'bitbucket.org'下所有键
 print(
     config.options('bitbucket.org'))  # ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
 # 找到'bitbucket.org'下所有键值对
 print(config.items(
     'bitbucket.org'))  # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
 # 获取Section下的key对应的value
 print(config.get('bitbucket.org', 'compression'))  # yes

增删改

 import configparser

 config = configparser.ConfigParser()

 config.read('example.ini')

 config.add_section('yuan')

 config.remove_section('bitbucket.org')
 config.remove_option('topsecret.server.com', "forwardx11")

 config.set(')
 config.set(')
 with open('new.ini', "w") as f:
     config.write(f)

 # example.ini:
 # [DEFAULT]
 # serveraliveinterval = 45
 # compression = yes
 # compressionlevel = 9
 # forwardx11 = yes
 #
 # [bitbucket.org]
 # user = hg
 #
 # [topsecret.server.com]
 # host port = 50022
 # forwardx11 = no

 # new.ini:
 # [DEFAULT]
 # serveraliveinterval = 45
 # compression = yes
 # compressionlevel = 9
 # forwardx11 = yes
 #
 # [topsecret.server.com]
 # host port = 50022
 # k1 = 11111
 #
 # [yuan]
 # k2 = 22222

logging模块

默认

 import logging
 logging.debug('debug message')
 logging.info('info message')
 logging.warning('warning message')
 logging.error('error message')
 logging.critical('critical message') 

默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG)

函数式简单配置

中文会出现乱码情况

 import logging

 logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                     datefmt='%a, %d %b %Y %H:%M:%S',
                     filename='test.log',
                     filemode='w')

 logging.debug('debug message')
 logging.info('info message')
 logging.warning('warning message')
 logging.error('error message')
 logging.critical('critical message')

 # test.log:
 # Tue, 04 Sep 2018 22:10:44 loggingģ��.py[line:19] DEBUG debug message
 # Tue, 04 Sep 2018 22:10:44 loggingģ��.py[line:20] INFO info message
 # Tue, 04 Sep 2018 22:10:44 loggingģ��.py[line:21] WARNING warning message
 # Tue, 04 Sep 2018 22:10:44 loggingģ��.py[line:22] ERROR error message
 # Tue, 04 Sep 2018 22:10:44 loggingģ��.py[line:23] CRITICAL critical message

logger对象配置

 import logging

 logger = logging.getLogger()
 # 创建一个handler,用于写入日志文件
 fh = logging.FileHandler('test.log', encoding='utf-8')

 # 再创建一个handler,用于输出到控制台
 ch = logging.StreamHandler()
 formatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(message)s')

 fh.setLevel(logging.DEBUG)

 fh.setFormatter(formatter)
 ch.setFormatter(formatter)
 ##logger对象可以添加多个fh和ch对象
 logger.addHandler(fh)
 logger.addHandler(ch)

 logger.debug('logger debug message')
 logger.info('logger info message')
 logger.warning('logger warning message')
 logger.error('logger error message')
 logger.critical('logger critical message')

 #test.log:
 # 2018-09-04 22:19:08,855 - logging模块.py - WARNING - logger warning message
 # 2018-09-04 22:19:08,855 - logging模块.py - ERROR - logger error message
 # 2018-09-04 22:19:08,855 - logging模块.py - CRITICAL - logger critical message

配置参数说明

logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:

filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

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:线程名。可能没有
%进程ID。可能没有
%(message)s:用户输出的消息

最新文章

  1. (转)Java中使用Jedis操作Redis
  2. Nginx中FastCGI配置优化
  3. Unity加载模块深度解析(Shader)
  4. sublime 插件zen coding
  5. 将自定义的 service provider 绑定到 IOC 容器
  6. WebMethod 属性
  7. Linux查看端口信息命令
  8. u盘烧写后实际容量变小了
  9. spring struts2 ibatis 框架结构图
  10. Json对象与Json字符串的转化、JSON字符串与Java对象的转换
  11. Docker最全教程——从理论到实战(六)
  12. ROM、RAM、CPU、CACHE、FLASH的区别
  13. promise知识点小结
  14. Asp.Net WebApi 跨域设置
  15. LeetCode链表相加-Python&lt;二&gt;
  16. _event_active
  17. redis的repl-ping-slave-period和repl-ping-replica-period
  18. VC++中出现stack overflow错误时修改VC++的默认堆栈大小
  19. 计算机硬盘大小转换(B,KB,MB,GB,TB,PB之间的大小转换)
  20. HTML——图片自动轮换和手动轮换

热门文章

  1. 恶心github 下载慢
  2. Convolution卷积算法python以numpy,Matplotlib实现
  3. aspx页面,取得Excel某列不同类型的数据为空
  4. Win2012R2 AD主域控登录密码忘记
  5. vscode + gradle 创建 java 项目 - java language server无法启动
  6. ASP.NET MVC 右键点击添加没有区域(Area)、控制器、试图等选项
  7. 基于μC/OS—III的CC1120驱动程序设计
  8. Android Studio中解决jar包重复依赖导致的代码编译错误
  9. tensorflow冻结变量方法(tensorflow freeze variable)
  10. python @staticmethod和@classmethod的作用