8th,常用模块、正则表达式

时间:2022-09-03 12:19:51

re模块

什么是正则?

正则就是用一些具有特殊含义的符号组合到一起(正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。内嵌在Python中,通过re模块实现。正则表达式模式被编译成一系列的字节码,然后由用c编写的匹配引擎执行。

常用正则表达式符号

'.'     默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^'     匹配字符开头,若指定flags 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']
'?'     匹配前一个字符1次或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'    匹配字符结尾,同$
'\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'

'}

8th,常用模块、正则表达式

最常用的匹配语法

 re.match 从头开始匹配
 re.search 匹配包含,会扫描整个字符串,不会从头开始,找到第一个匹配的结果就会返回
 re.findall 把所有匹配到的字符放到以列表中的元素返回
 re.splitall 以匹配到的字符当做列表分隔符
 re.sub      匹配字符并替换

反斜杠

Python原生字符创可以解决反斜杠问题,匹配一个数字可以协亨r"\d","\"可以使用r"\\"来表示

了解知道的几个匹配模式

re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
M(MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图)
S(DOTALL): 点任意匹配模式,改变'.'的行为

 time与datatime模块

在Python中,表示时间的方式:

  • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。
  • 格式化的时间字符串(Format String)
  • 结构化的时间(struct_time):struct_time元组共有9个元素(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
 import time

 #时间戳
 print(time.time())

 #格式化的时间字符串
 print(time.strftime("%Y-%m-%d %X"))

 #本地时区的struct_time
 print(time.localtime())

 #UTC时区的struc_time
 print(time.gmtime())

其中计算机认识的时间只能是“时间戳”格式,三者之间的转换:

8th,常用模块、正则表达式

 #--------------------------按图1转换时间
 # localtime([secs])
 # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
 time.localtime()
 time.localtime(1473525444.037215)

 # gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。

 # mktime(t) : 将一个struct_time转化为时间戳。
 print(time.mktime(time.localtime()))#1473525749.0

 # strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
 # time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
 # 元素越界,ValueError的错误将会被抛出。
 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56

 # time.strptime(string[, format])
 # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
 #  tm_wday=3, tm_yday=125, tm_isdst=-1)
 #在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。

#线程推迟指定的时间运行,单位为秒sleep(secs)
#时间加减
import datetime

# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
#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)) #时间替换

datetime模块

random模块

import random

print(random.random())#(0,1)----float    大于0且小于1之间的小数

print(random.randint(1,3))  #[1,3]    大于等于1且小于等于3之间的整数

print(random.randrange(1,3)) #[1,3)    大于等于1且小于3之间的整数

',[4,5]]))#1或者23或者[4,5]

',[4,5]],2))#列表元素任意2个组合

print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716 

item=[1,3,5,7,9]
random.shuffle(item) #打乱item的顺序,相当于"洗牌"
print(item)
import random
def make_code(n):
    res=''
    for i in range(n):
        s1=chr(random.randint(65,90))
        s2=str(random.randint(0,9))
        res+=random.choice([s1,s2])
    return res

print(make_code(9))

生成随机验证码

os模块

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    输出用于分割文件路径的字符串 win下为;,Linux下为:
 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所指向的文件或者目录的最后修改时间
 os.path.getsize(path) 返回path的大小

 sys模块

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

shutil模块

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

json&pickle模块

eval的重点通常是用来执行一个字符串表达式,并表达式的值。遇到特殊类型时,需要用json。

import json
x = "[null, true, false, 1]"
print(eval(x))
print(json.loads(x))

什么是序列化?

我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被成为serialization,marshalling, flattening等等,都是一个意思

为什么要序列化?

1、持久保存状态

在断电或重启程序之前将程序当前内存中所有的数据都保存下来(保存到文件中),以便于下次程序执行能够从文件中载入之前的数据,然后继续执行,这就是序列化。

举个栗子:游戏保存并继续;虚拟机状态挂起等

2、跨平台数据交互

序列化之后,不仅可以把序列化后的内容写入磁盘,还可以通过网络传输到别的机器上,如果收发双方约定好使用同一种序列化格式,那么便打破了平台/语言差异化带来的限制,实现了跨平台数据交互。

反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。

如何序列化:

json

如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。

JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:

8th,常用模块、正则表达式

8th,常用模块、正则表达式

 import json

 dic = {"name":"alvin", "age":23, "sex":"male"}
 print(type(dic))

 j = json.dumps(dic)
 print(type(j))

 f = open("序列化对象", "w")
 f.write(j)#——————————等价于json.dump(dic, f)
 f.close()
 #———————————————反序列化<br>
 import json
 f = open("序列化对象")
 data = json.loads(f.read())

无论数据是怎样创建的,只要满足json格式,就可以json。loads出来,不一定非要dumps的数据才能loads.

pickle

8th,常用模块、正则表达式

 import pickle

 dic={'name':'alvin','age':23,'sex':'male'}

 print(type(dic))#<class 'dict'>

 j=pickle.dumps(dic)
 print(type(j))#<class 'bytes'>

 f=open('序列化对象_pickle','wb')#注意是w是写入str,wb是写入bytes,j是'bytes'
 f.write(j)  #-------------------等价于pickle.dump(dic,f)

 f.close()
 #-------------------------反序列化
 import pickle
 f=open('序列化对象_pickle','rb')

 data=pickle.loads(f.read())#  等价于data=pickle.load(f)

 print(data['age'])

pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于python,并且可能不同版本的Python彼此都不兼容,因此,只能用pickle保存那些不重要的数据,不能成功地反序列化也没关系。

shelve模块

shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以使python所支持的数据类型

 import shelve

 f=shelve.open(r'sheve.txt')
 # f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
 # f['stu2_info']={'name':'gangdan','age':53}
 # f['school_info']={'website':'http://www.pypy.org','city':'beijing'}

 print(f['stu1_info']['hobby'])
 f.close()

xml模块xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多。

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数据

xml协议在各个语言里都支持,在Python中可以用以下模块操作xml:

 #print(root.iter("year")) #全文搜索
 #print(root.find("country"))#在root的子节点找,只找一个
 #print(root.findall("country"))#在root的子节点找,找所有
 import xml.etree.ElementTree as ET

 tree = ET.parse("xmltest.xml")
 root = tree.getroot()
 print(root.tag)

 #遍历xml文档
 for child in root:
     print('========>',child.tag,child.attrib,child.attrib['name'])
     for i in child:
         print(i.tag,i.attrib,i.text)

 #只遍历year 节点
 for node in root.iter('year'):
     print(node.tag,node.text)
 #---------------------------------------

 import xml.etree.ElementTree as ET

 tree = ET.parse("xmltest.xml")
 root = tree.getroot()

 #修改
 for node in root.iter('year'):
     new_year=int(node.text)+1
     node.text=str(new_year)
     node.set('updated','yes')
     node.set('version','1.0')
 tree.write('test.xml')

 #删除node
 for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
      root.remove(country)

 tree.write('output.xml')
 #在country内添加(append)节点year2
 import xml.etree.ElementTree as ET
 tree = ET.parse("a.xml")
 root=tree.getroot()
 for country in root.findall('country'):
     for year in country.findall('year'):
         if int(year.text) > 2000:
             year2=ET.Element('year2')
             year2.text='新年'
             year2.attrib={'update':'yes'}
             country.append(year2) #往country节点下添加子节点

 tree.write('a.xml.swap')

自己创建xml文档:

 import xml.etree.ElementTree as ET

 new_xml = ET.Element("namelist")
 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
 age = ET.SubElement(name,"age",attrib={"checked":"no"})
 sex = ET.SubElement(name,"sex")
 sex.text = '
 name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
 age = ET.SubElement(name2,"age")
 age.text = '

 et = ET.ElementTree(new_xml) #生成文档对象
 et.write("test.xml", encoding="utf-8",xml_declaration=True)

 ET.dump(new_xml) #打印生成的格式

configparser模块

用于生成和修改常见配置文档

配置文件如下:

# 注释1
; 注释2

[section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31

[section2]
k1 = v1

读取

 import configparser

 config=configparser.ConfigParser()
 config.read('a.cfg')

 #查看所有的标题
 res=config.sections() #['section1', 'section2']
 print(res)

 #查看标题section1下所有key=value的key
 options=config.options('section1')
 print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary']

 #查看标题section1下所有key=value的(key,value)格式
 item_list=config.items('section1')
 print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]

 #查看标题section1下user的值=>字符串格式
 val=config.get('section1','user')
 print(val) #egon

 #查看标题section1下age的值=>整数格式
 val1=config.getint('section1','age')

 #查看标题section1下is_admin的值=>布尔值格式
 val2=config.getboolean('section1','is_admin')
 print(val2) #True

 #查看标题section1下salary的值=>浮点型格式
 val3=config.getfloat('section1','salary')
 print(val3) #31.0

改写

 import configparser

 config=configparser.ConfigParser()
 config.read('a.cfg',encoding='utf-8')

 #删除整个标题section2
 config.remove_section('section2')

 #删除标题section1下的某个k1和k2
 config.remove_option('section1','k1')
 config.remove_option('section1','k2')

 #判断是否存在某个标题
 print(config.has_section('section1'))

 #判断标题section1下是否有user
 print(config.has_option('section1',''))

 #添加一个标题
 config.add_section('egon')

 #在标题egon下添加name=egon,age=18的配置
 config.set('egon','name','egon')
 config.set('egon','age',18) #报错,必须是字符串

 #最后将修改的内容写入文件,完成最终的修改
 config.write(open('a.cfg','w'))

基于上述方法添加一个ini文档

 import configparser

 config = configparser.ConfigParser()
 config[',
                       'Compression': 'yes',
                      '}

 config['bitbucket.org'] = {}
 config['bitbucket.org']['User'] = 'hg'
 config['topsecret.server.com'] = {}
 topsecret = config['topsecret.server.com']
 topsecret['     # mutates the parser
 topsecret['ForwardX11'] = 'no'  # same here
 config['DEFAULT']['ForwardX11'] = 'yes'
 with open('example.ini', 'w') as configfile:
    config.write(configfile)

 #基于上述方法添加一个ini文档

hashlib模块

什么是hash?

hash是一种算法(3.x里代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法),该算法接受传入的内容,经过运算得到一串hash值

hash值的特点

(1)只要传入的内容一样,得到的hash值必然一样===》要用明文传输密码文件完整性校验

(2)不能由hash值反解成内容===》把密码做成hash值,不应该在网络传输明文密码

(3)只要使用的hash算法不便,无论校验的内容有多大,得到的hash值长度是固定的

hash算法就像一座工厂,工厂接收你送来的原材料(可以用m.update()为工厂运行原材料),经过加工返回的产品就是hash值

8th,常用模块、正则表达式

 import hashlib

 m=hashlib.md5()# m=hashlib.sha256()

 m.update('hello'.encode('utf8'))
 print(m.hexdigest())  #5d41402abc4b2a76b9719d911017c592

 m.update('alvin'.encode('utf8'))

 print(m.hexdigest())  #92a7e713c30abbb0319fa07da2a5c4af

 m2=hashlib.md5()
 m2.update('helloalvin'.encode('utf8'))
 print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af

 '''
 注意:把一段很长的数据update多次,与一次update这段长数据,得到的结果一样
 但是update多次为校验大文件提供了可能。
 '''

以上加密算法虽然非常厉害,但有时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密

 import hashlib

 #####256#####

 hash = hashlib.sha256("898oaFs09f".encode("utf8"))
 hahs.update("alvin".encode("utf8"))
 print(hash.hexdigest())

python还有一个hmac模块,它内部对我们创建key和内容进行进一步的处理然后再加密:

 import hmac
 h = hmac.new("alvin".encode("utf8"))
 h.update("hello".encode("utf8"))
 print(h.hexdigest())
 #要想保证hmac最终结果一致,必须保证:
 #1:hmac.new括号内指定的初始key一样
 #2:无论update多少次,校验的内容累加到一起是一样的内容

 import hmac

 h1=hmac.new(b'egon')
 h1.update(b'hello')
 h1.update(b'world')
 print(h1.hexdigest())

 h2=hmac.new(b'egon')
 h2.update(b'helloworld')
 print(h2.hexdigest())

 h3=hmac.new(b'egonhelloworld')
 print(h3.hexdigest())

 '''
 f1bf38d054691688f89dcd34ac3c27f2
 f1bf38d054691688f89dcd34ac3c27f2
 bcca84edd9eeb86f30539922b28f3981
 '''

 #注意!注意!注意

subprocess模块

subprocess模块允许用户建立新程序,连接至其输入、输出、错误句柄并得到他们的返回代码

subprocess.run()  #可以用于所有可以处理的情况;
'''
subprocess.run(args*stdin=Noneinput=Nonestdout=Nonestderr=Noneshell=Falsetimeout=Nonecheck=False)
'''
subprocess.Popen()  #可以用于更高级的用途

常用subprocess方法

 #执行命令,返回命令执行状态 , 0 or 非0
 >>> retcode = subprocess.call(["ls", "-l"])

 #执行命令,如果命令结果为0,就正常返回,否则抛异常
 >>> subprocess.check_call(["ls", "-l"])
 0

 #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
 >>> subprocess.getstatusoutput('ls /bin/ls')
 (0, '/bin/ls')

 #接收字符串格式命令,并返回结果
 >>> subprocess.getoutput('ls /bin/ls')
 '/bin/ls'

 #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
 >>> res=subprocess.check_output(['ls','-l'])
 >>> res
 b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\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.

 #例子
 >>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
 >>> p.stdout.read()
 b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /\n'

终端输入的命令分为两种:

(1)输入即可得到输出,如:ifconfig

(2)输入进行某环境,依赖再输入,如:python

需要交互的命令示例

 import subprocess

 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 obj.stdin.write('print 1 \n ')
 obj.stdin.write('print 2 \n ')
 obj.stdin.write('print 3 \n ')
 obj.stdin.write('print 4 \n ')

 out_error_list = obj.communicate(timeout=10)
 print out_error_list
 import  subprocess

 '''
 sh-3.2# ls /Users/egon/Desktop |grep txt$
 mysql.txt
 tt.txt
 事物.txt
 '''

 res1=subprocess.Popen('ls /Users/jieli/Desktop',shell=True,stdout=subprocess.PIPE)
 res=subprocess.Popen('grep txt$',shell=True,stdin=res1.stdout,
                  stdout=subprocess.PIPE)

 print(res.stdout.read().decode('utf-8'))

 #等同于上面,但是上面的优势在于,一个数据流可以和另外一个数据流交互,可以通过爬虫得到结果然后交给grep
 res1=subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True,stdout=subprocess.PIPE)
 print(res1.stdout.read().decode('utf-8'))

 #windows下:
 # dir | findstr 'test*'
 # dir | findstr 'txt$'
 import subprocess
 res1=subprocess.Popen(r'dir C:\Users\Administrator\PycharmProjects\test\函数备课',shell=True,stdout=subprocess.PIPE)
 res=subprocess.Popen('findstr test*',shell=True,stdin=res1.stdout,
                  stdout=subprocess.PIPE)

 print(res.stdout.read().decode('gbk')) #subprocess使用当前系统默认编码,得到结果为bytes类型,在windows下需要用gbk解码

logging模块

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还有可能有错误、警告等信息输出,python的loggin模块提供了标准的日志接口,可以通过它存储各种格式的日志,logging的日志可以分为debug(), info(), warning(), error() 和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

各个级别的含义:

level 信息
debug 详细信息,通常只在诊断问题的时候使用
info 程序正如期望的工作的确认信息
warning 某些不期望发生的事情的指示,或者未来一些问题的指示。软件仍然在期望的状态下运行
error 由于更严重的问题,软件已经不能表现一些功能
critical 严重的错误,表明程序已经不能继续运行

把日志写到文件里

 import logging

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

其中level=loggin.INFO意思是,把日志记录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被记录到文件里,上面代码中,第一条日志是不会被记录的,如果希望记录debug日志,需要把日志级别改为DEBUG。

在日志中加上时间

 import logging
 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
 logging.warning('is when this event was logged.')

 #输出
 12/12/2010 11:46:36 AM is when this event was logged.

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

用户输出的消息

8th,常用模块、正则表达式的更多相关文章

  1. Python模块之常用模块,反射以及正则表达式

    常用模块  1. OS模块 用于提供系统级别的操作,系统目录,文件,路径,环境变量等 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("di ...

  2. pytho day6 &lt&semi;正则表达式、常用模块、反射&gt&semi;

    本节介绍: 一:正则表达式: 正则表达并不是python 独有的.在各个语言里都有该语法的介绍.正则表达是处理字符串的强大的处理工具.拥有自己的独特的 处理方法.和处理引擎.虽然性能没有python ...

  3. python常用模块(1):collections模块和re模块(正则表达式详解)

    从今天开始我们就要开始学习python的模块,今天先介绍两个常用模块collections和re模块.还有非常重要的正则表达式,今天学习的正则表达式需要记忆的东西非常多,希望大家可以认真记忆.按常理来 ...

  4. os常用模块,json,pickle,shelve模块,正则表达式(实现运算符分离),logging模块,配置模块,路径叠加,哈希算法

    一.os常用模块 显示当前工作目录 print(os.getcwd()) 返回上一层目录 os.chdir("..") 创建文件包 os.makedirs('python2/bin ...

  5. 正则表达式、re、常用模块

    阅读目录 正则表达式 字符 量词 . ^ $ * + ? { } 字符集[][^] 分组 ()与 或 |[^] 转义符 \ 贪婪匹配 re 总结 正则 re 常用模块 namedtuple deque ...

  6. 进击的Python【第五章】:Python的高级应用(二)常用模块

    Python的高级应用(二)常用模块学习 本章学习要点: Python模块的定义 time &datetime模块 random模块 os模块 sys模块 shutil模块 ConfigPar ...

  7. python学习笔记之常用模块(第五天)

    参考老师的博客: 金角:http://www.cnblogs.com/alex3714/articles/5161349.html 银角:http://www.cnblogs.com/wupeiqi/ ...

  8. day--6&lowbar;python常用模块

    常用模块: time和datetime shutil模块 radom string shelve模块 xml处理 configparser处理 hashlib subprocess logging模块 ...

  9. Tengine 常用模块使用介绍

    Tengine 和 Nginx Tengine简介 从2011年12月开始:Tengine是由淘宝网发起的Web服务器项目.它在Nginx的基础上,针对大访问量网站的需求,添加了很多高级功能 和特性. ...

  10. Python基础之--常用模块

    Python 模块 为了实现对程序特定功能的调用和存储,人们将代码封装起来,可以供其他程序调用,可以称之为模块. 如:os 是系统相关的模块:file是文件操作相关的模块:sys是访问python解释 ...

随机推荐

  1. 现在遇到一个问题,无法判断url是属于哪一个CDN

    解决的办法是到申请域名的网站上面去调用api获取域名的cname来确定

  2. Xenu Link Sleuth-简单使用

    1.工具说明 xenu link sleuth,主要用于测试网站死链接.包括图片.链接. 下载地址:http://home.snafu.de/tilman/xenulink.html#Download ...

  3. 又折腾到这么晚 &comma; 图片Viewpager PagerIndicator&comma;listview 和侧边栏滑动的事件处理

    代码 思路 根据坐标判断 事件是否拦截 调用 getParent().requestDisallowInterceptTouchEvent(true);方法告诉上层ViewGroup 是否拦截 返回t ...

  4. angular1&period;x &plus; ES6开发风格记录

    angular1.x和ES6开发风格 一.Module ES6有自己的模块机制,所以我们要通过使用ES6的模块机制来淡化ng的框架,使得各业务逻辑层的看不出框架的痕迹,具体的做法是: 把各功能模块的具 ...

  5. SpringBoot之旅第三篇-日志

    一.前言 日志对于一个系统的重要性不言而喻,日志能帮我们快速定位线上问题,市场上存在非常多的日志框架,比较常见的有 JUL,JCL,Log4j,Log4j2,Logback.SLF4j.jboss-l ...

  6. python 网络编程之TCP传输&amp&semi;粘包传输

    只有TCP有粘包现象,UDP永远不会粘包. 所谓粘包问题主要还是C/S两端数据传输时 因为接收方不知道消息之间的界限,不知道一次性提取多少字节的数据所造成的 根本原因:粘包是由TCP协议本身造成的,T ...

  7. python学习:修改字符串大小写

    修改字符串大小写 函数:title()字符串首字母大写,upper()字符串全部大写,lower()字符串全部小写. 代码举例: name = "ada lovelace"prin ...

  8. 微信小程序 组件 Demo

    文字跑马灯效果:       http://www.wxapp-union.com/portal.php?mod=view&aid=1038 触摸水波涟漪效果:   http://www.wx ...

  9. &lbrack;翻译&rsqb; Visual Studio 2019 RC版发布

    [翻译] Visual Studio 2019 RC版发布 原文: Visual Studio 2019 Release Candidate (RC) now available 今天,我们将分享 V ...

  10. Vue 结合 Axios 接口超时统一处理

    引语:当网路慢的时候.又或者公司服务器不在内地的时候,接口数据请求不回来超时报错的情况相信大家肯定遇到过的,这里我把我公司项目请求超时的处理方法分享下,希望看过后有帮助. axios基本用法就不多说了 ...