Python:Day8:python模块
什么是模块
模块,用一砣代码实现了某个功能的代码集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操作相关的模块
模块分为三种:
- 自定义模块
- 第三方模块 pip install scikit-image -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com(网络问题安装第三方模块四出错用此命令安装)
- 内置模块
自定义模块
1、定义模块
情景一:

情景二:

情景三:

2、导入模块
Python之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。improt导入模块时首先会将被导入的文件执行一遍。导入模块有一下几种方法:
|
1
2
3
4
|
import modulefrom module.xx.xx import xxfrom module.xx.xx import xx as rename from module.xx.xx import * |
导入模块其实就是告诉Python解释器去解释那个py文件
- 导入一个py文件,解释器解释该py文件
- 导入一个包,解释器解释该包下的 __init__.py 文件 【py2.7】
那么问题来了,导入模块时是根据那个路径作为基准来进行的呢?即:sys.path
|
1
2
3
4
5
|
import sysprint sys.path 结果:['/Users/wupeiqi/PycharmProjects/calculator/p1/pp1', '/usr/local/lib/python2.7/site-packages/setuptools-15.2-py2.7.egg', '/usr/local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg', '/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/xlutils-1.7.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/xlwt-1.0.0-py2.7.egg', '/usr/local/lib/python2.7/site-packages/xlrd-0.9.3-py2.7.egg', '/usr/local/lib/python2.7/site-packages/tornado-4.1-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/backports.ssl_match_hostname-3.4.0.2-py2.7.egg', '/usr/local/lib/python2.7/site-packages/certifi-2015.4.28-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pyOpenSSL-0.15.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/six-1.9.0-py2.7.egg', '/usr/local/lib/python2.7/site-packages/cryptography-0.9.1-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/cffi-1.1.1-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/ipaddress-1.0.7-py2.7.egg', '/usr/local/lib/python2.7/site-packages/enum34-1.0.4-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pyasn1-0.1.7-py2.7.egg', '/usr/local/lib/python2.7/site-packages/idna-2.0-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pycparser-2.13-py2.7.egg', '/usr/local/lib/python2.7/site-packages/Django-1.7.8-py2.7.egg', '/usr/local/lib/python2.7/site-packages/paramiko-1.10.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/gevent-1.0.2-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/greenlet-0.4.7-py2.7-macosx-10.10-x86_64.egg', '/Users/wupeiqi/PycharmProjects/calculator', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages', '/Library/Python/2.7/site-packages'] |
如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append('路径') 添加。
|
1
2
3
4
|
import sysimport osproject_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(project_path) |
模块
内置模块是Python自带的功能,在使用内置模块相应的功能时,需要【先导入】再【使用】
补充:如果如下图所示bin文件要想导入模块main.py。

1 # 规范导入模块路径(倒着找): 2 # print(__file__) 3 # print(os.path.dirname(os.path.dirname(__file__))) 4 # print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 5 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 6 sys.path.append(BASE_DIR)
7 from "文件夹" imprt "模块"
......
一、sys
用于提供对Python解释器相关的操作:
|
1
2
3
4
5
6
7
8
9
|
sys.argv 命令行参数List,第一个元素是程序本身路径,第二个元素是传入的参数(运维要用)sys.exit(n) 退出程序,正常退出时给一个提示exit(0)sys.version 获取Python解释程序的版本信息sys.maxint 最大的Int值sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值,打印出来是一个列表(如此说来那么就可以为其添加添加一个目录)sys.platform 返回操作系统平台名称sys.stdin 输入相关sys.stdout 输出相关sys.stderror 错误相关 |
1 import sys 2 import time 3 4 5 def view_bar(num, total): 6 rate = float(num) / float(total) 7 rate_num = int(rate * 100) 8 r = '\r%d%%' % (rate_num, ) 9 sys.stdout.write(r) 10 sys.stdout.flush() 11 12 13 if __name__ == '__main__': 14 for i in range(0, 100): 15 time.sleep(0.1) 16 view_bar(i, 100)
二、os
os模块是与操作系统交互的一个接口,用于提供系统级别的操作:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径(尽量不要用可能会使斜杠变反,用abspath就可以了),print(os.getcwd())打印当前工作目录os.chdir(r"E:\dirname") 切换当前脚本工作目录到os.curdir 返回当前目录: ('.')os.pardir 获取当前目录的父目录字符串名:('..')os.makedirs(r'dir1\dir2\dir3') 生成多层递归目录或者os.removedirs() 删除空目录并递归到上一级目录如若也为空,则删除,依此类推,如果目录下有文件则删不掉。os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirnameos.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirnameos.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,print()以列表方式打印出来os.remove() 删除一个文件os.rename("oldname","new") 重命名文件/目录,前面是老的文件名后面是要改的文件名os.stat('path/filename') 获取文件/目录信息(上传文件时要用先获取下文件大小)可以用.调用下面的方法如print(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(__file__) 返回file的绝对路径,print(__file__)打印文件名os.path.split(path) 将path以元组的形式分割成一个路径名和一个文件名。("路径", "文件名")os.path.dirname(path) 返回path的上一级目录。其实就是os.path.split(path)的第一个元素os.path.basename(path) 返回path最后的文件名。判断文件结尾如果以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素os.path.exists(path) 如果path存在,返回True;如果path不存在,返回Falseos.path.isabs(path) 如果path是绝对路径,返回Trueos.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回Falseos.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回Falseos.path.join(path1[, path2[, ...]]) 拼接路径。将多个路径组合后返回,第一个绝对路径之前的参数将被忽略os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间 |
在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为反斜杠。
>>> os.path.normcase('c:/windows\\system32\\') 'c:\\windows\\system32\\' 规范化路径,如..和/ >>> os.path.normpath('c://windows\\System32\\../Temp/') 'c:\\windows\\Temp' >>> a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..' >>> print(os.path.normpath(a)) /Users/jieli/test1
os路径处理 #方式一:推荐使用 import os #具体应用 import os,sys possible_topdir = os.path.normpath(os.path.join( os.path.abspath(__file__), os.pardir, #返回上一级 os.pardir, os.pardir )) sys.path.insert(0,possible_topdir)#定义搜索路径的优先顺序,序号从0开始,表示最大优先级,sys.path.insert()加入的也是临时搜索路径,程序退出后失效。 #方式二:不推荐使用 os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
三、hashlib
# 1、什么叫hash:hash是一种算法(3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法),该算法接受传入的内容,经过运算得到一串hash值 # 2、hash值的特点是: #2.1 只要传入的内容一样,得到的hash值必然一样=====>要用明文传输密码文件完整性校验 #2.2 不能由hash值返解成内容=======》把密码做成hash值,不应该在网络传输明文密码 #2.3 只要使用的hash算法不变,无论校验的内容有多大,得到的hash值长度是固定的
hash算法就像一座工厂,工厂接收你送来的原材料(可以用m.update()为工厂运送原材料),经过加工返回的产品就是hash值

|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
import hashlib# ######## md5 ########hash = hashlib.md5()# help(hash.update)hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())print(hash.digest())######## sha1 ########hash = hashlib.sha1()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())# ######## sha256 ########hash = hashlib.sha256()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())# ######## sha384 ########hash = hashlib.sha384()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())# ######## sha512 ########hash = hashlib.sha512()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())注意:把一段很长的数据update多次,与一次update这段长数据,得到的结果一样 但是update多次为校验大文件提供了可能。 |
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
|
1
2
3
4
5
6
7
|
import hashlib# ######## md5 ########hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))hash.update(bytes('admin',encoding="utf-8"))print(hash.hexdigest()) |
python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密
|
1
2
3
4
5
|
import hmach = hmac.new(bytes('898oaFs09f',encoding="utf-8"))h.update(bytes('admin',encoding="utf-8"))print(h.hexdigest()) |
1 #要想保证hmac最终结果一致,必须保证: 2 #1:hmac.new括号内指定的初始key一样 3 #2:无论update多少次,校验的内容累加到一起是一样的内容 4 5 import hmac 6 7 h1=hmac.new(b'egon') 8 h1.update(b'hello') 9 h1.update(b'world') 10 print(h1.hexdigest()) 11 12 h2=hmac.new(b'egon') 13 h2.update(b'helloworld') 14 print(h2.hexdigest()) 15 16 h3=hmac.new(b'egonhelloworld') 17 print(h3.hexdigest()) 18 19 ''' 20 f1bf38d054691688f89dcd34ac3c27f2 21 f1bf38d054691688f89dcd34ac3c27f2 22 bcca84edd9eeb86f30539922b28f3981 23 '''
四、random
|
1
2
3
4
5
6
7
8
|
import randomprint(random.random())#取0~1的浮点数print(random.randint(0, 2))#取0~2的整数包含2print(random.randrange(1, 10))#取1~10的整数不包含10print(random.choice[11,22,33,44,])#随机取列表里的值print(random.sample[11,22,33,44,],2)#随机在列表里取出两个值print(random.uniform(1,3))#取1~3范围内的浮点数item = [1,2,3,4,5]
print(random.suffle(item))#打乱次序
|
1 import random 2 checkcode = '' 3 for i in range(4): 4 current = random.randrange(0,4) 5 if current != i: 6 temp = chr(random.randint(65,90)) 7 else: 8 temp = random.randint(0,9) 9 checkcode += str(temp) 10 print checkcode
1 improt random 2 def v_code(): 3 ret = '' 4 for i in range(5): 5 num = random.randint(0,9) 6 letter = chr(random.randint(65,122)) 7 s = str(random.choice([num, letter])) 8 ret = ret+s #ret+=s 9 return ret 10 print(v_code())
五、re
python中re模块提供了正则表达式相关操作(常用匹配模式元字符)

在字符集 [ ] 里面有意义的符号 -(减号) ^ \
通配符.能匹配除了换行符以外的所有字符

# =================================匹配模式================================= #一对一的匹配 # 'hello'.replace(old,new) # 'hello'.find('pattern') #正则匹配 import re #\w与\W print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3'] print(re.findall('\W','hello egon 123')) #[' ', ' '] #\s与\S print(re.findall('\s','hello egon 123')) #[' ', ' ', ' ', ' '] print(re.findall('\S','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3'] #\n \t都是空,都可以被\s匹配 print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' '] #\n与\t print(re.findall(r'\n','hello egon \n123')) #['\n'] print(re.findall(r'\t','hello egon\t123')) #['\n'] #\d与\D print(re.findall('\d','hello egon 123')) #['1', '2', '3'] print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' '] #\A与\Z print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^ print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$ #^与$ print(re.findall('^h','hello egon 123')) #['h'] print(re.findall('3$','hello egon 123')) #['3'] # 重复匹配:| . | * | ? | .* | .*? | + | {n,m} | #. print(re.findall('a.b','a1b')) #['a1b'] print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab'] print(re.findall('a.b','a\nb')) #[] print(re.findall('a.b','a\nb',re.S)) #['a\nb'] print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一条意思一样 #* print(re.findall('ab*','bbbbbbb')) #[] print(re.findall('ab*','a')) #['a'] print(re.findall('ab*','abbbb')) #['abbbb'] #? print(re.findall('ab?','a')) #['a'] print(re.findall('ab?','abbb')) #['ab'] #匹配所有包含小数在内的数字 print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3'] #.*默认为贪婪匹配 print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b'] #.*?为非贪婪匹配:推荐使用 print(re.findall('a.*?b','a1b22222222b')) #['a1b'] #+ print(re.findall('ab+','a')) #[] print(re.findall('ab+','abbb')) #['abbb'] #{n,m} print(re.findall('ab{2}','abbb')) #['abb'] print(re.findall('ab{2,4}','abbb')) #['abb'] print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+' print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*' #[] print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾 print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b'] print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b'] print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反,所以结果为['a=b'] print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反,所以结果为['a=b'] #\# print(re.findall('a\\c','a\c')) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常 print(re.findall(r'a\\c','a\c')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义 print(re.findall('a\\\\c','a\c')) #同上面的意思一样,和上面的结果一样都是['a\\c'] #():分组 print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab'] print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容 print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com'] print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>'))#['href="http://www.baidu.com"'] #| print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company')) # 这里加?:是去优先级,findall会匹配成功但是只显示组里的内容。
# ===========================re模块提供的方法介绍=========================== import re #1 print(re.findall('e','alex make love') ) #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里 #2 print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。 #3 print(re.match('e','alex make love')) #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match #4 print(re.split('[ab]','abcd')) #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割 #5 print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换所有 print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),结果带有总共替换的个数 #6 obj=re.compile('\d{2}') print(obj.search('abc123eeee').group()) #12 print(obj.findall('abc123eeee')) #['12'],重用了obj
1 import re 2 print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) #['h1'] 3 print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").group()) #<h1>hello</h1> 4 print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").groupdict()) #<h1>hello</h1> 5 6 print(re.search(r"<(\w+)>\w+</(\w+)>","<h1>hello</h1>").group()) 7 print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>").group()) 8 9 补充一
1 import re 2 3 print(re.findall(r'-?\d+\.?\d*',"1-12*(60+(-40.35/5)-(-4*3))")) #找出所有数字['1', '-12', '60', '-40.35', '5', '-4', '3'] 4 5 6 #使用|,先匹配的先生效,|左边是匹配小数,而findall最终结果是查看分组,所有即使匹配成功小数也不会存入结果 7 #而不是小数时,就去匹配(-?\d+),匹配到的自然就是,非小数的数,在此处即整数 8 print(re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整数['1', '-2', '60', '', '5', '-4', '3'] 9 10 补充二
#计算器作业参考:http://www.cnblogs.com/wupeiqi/articles/4949995.html expression='1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))' content=re.search('\(([\-\+\*\/]*\d+\.?\d*)+\)',expression).group() #(-3-40.0/5)
1 #为何同样的表达式search与findall却有不同结果: 2 print(re.search('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))").group()) #(-40.35/5) 3 print(re.findall('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))")) #['/5', '*3'] 4 5 #看这个例子:(\d)+相当于(\d)(\d)(\d)(\d)...,是一系列分组 6 print(re.search('(\d)+','123').group()) #group的作用是将所有组拼接到一起显示出来 7 print(re.findall('(\d)+','123')) #findall结果是组内的结果,且是最后一个组的结果 8 9 search与findall
1 #_*_coding:utf-8_*_ 2 __author__ = 'Linhaifeng' 3 #在线调试工具:tool.oschina.net/regex/# 4 import re 5 6 s=''' 7 http://www.baidu.com 8 egon@oldboyedu.com 9 你好 10 010-3141 11 ''' 12 13 #最常规匹配 14 # content='Hello 123 456 World_This is a Regex Demo' 15 # res=re.match('Hello\s\d\d\d\s\d{3}\s\w{10}.*Demo',content) 16 # print(res) 17 # print(res.group()) 18 # print(res.span()) 19 20 #泛匹配 21 # content='Hello 123 456 World_This is a Regex Demo' 22 # res=re.match('^Hello.*Demo',content) 23 # print(res.group()) 24 25 26 #匹配目标,获得指定数据 27 28 # content='Hello 123 456 World_This is a Regex Demo' 29 # res=re.match('^Hello\s(\d+)\s(\d+)\s.*Demo',content) 30 # print(res.group()) #取所有匹配的内容 31 # print(res.group(1)) #取匹配的第一个括号内的内容 32 # print(res.group(2)) #去陪陪的第二个括号内的内容 33 34 35 36 #贪婪匹配:.*代表匹配尽可能多的字符 37 # import re 38 # content='Hello 123 456 World_This is a Regex Demo' 39 # 40 # res=re.match('^He.*(\d+).*Demo$',content) 41 # print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字 42 43 44 #非贪婪匹配:?匹配尽可能少的字符 45 # import re 46 # content='Hello 123 456 World_This is a Regex Demo' 47 # 48 # res=re.match('^He.*?(\d+).*Demo$',content) 49 # print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字 50 51 52 #匹配模式:.不能匹配换行符 53 content='''Hello 123456 World_This 54 is a Regex Demo 55 ''' 56 # res=re.match('He.*?(\d+).*?Demo$',content) 57 # print(res) #输出None 58 59 # res=re.match('He.*?(\d+).*?Demo$',content,re.S) #re.S让.可以匹配换行符 60 # print(res) 61 # print(res.group(1)) 62 63 64 #转义:\ 65 66 # content='price is $5.00' 67 # res=re.match('price is $5.00',content) 68 # print(res) 69 # 70 # res=re.match('price is \$5\.00',content) 71 # print(res) 72 73 74 #总结:尽量精简,详细的如下 75 # 尽量使用泛匹配模式.* 76 # 尽量使用非贪婪模式:.*? 77 # 使用括号得到匹配目标:用group(n)去取得结果 78 # 有换行符就用re.S:修改模式 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 #re.search:会扫描整个字符串,不会从头开始,找到第一个匹配的结果就会返回 95 96 # import re 97 # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings' 98 # 99 # res=re.match('Hello.*?(\d+).*?Demo',content) 100 # print(res) #输出结果为None 101 102 # 103 # import re 104 # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings' 105 # 106 # res=re.search('Hello.*?(\d+).*?Demo',content) # 107 # print(res.group(1)) #输出结果为 108 109 110 111 #re.search:只要一个结果,匹配演练, 112 import re 113 content=''' 114 <tbody> 115 <tr id="4766303201494371851675" class="even "><td><div class="hd"><span class="num">1</span><div class="rk "><span class="u-icn u-icn-75"></span></div></div></td><td class="rank"><div class="f-cb"><div class="tt"><a href="/song?id=476630320"><img class="rpic" src="http://p1.music.126.net/Wl7T1LBRhZFg0O26nnR2iQ==/19217264230385030.jpg?param=50y50&quality=100"></a><span data-res-id="476630320" " 116 # res=re.search('<a\shref=.*?<b\stitle="(.*?)".*?b>',content) 117 # print(res.group(1)) 118 119 120 #re.findall:找到符合条件的所有结果 121 # res=re.findall('<a\shref=.*?<b\stitle="(.*?)".*?b>',content) 122 # for i in res: 123 # print(i) 124 125 126 127 #re.sub:字符串替换 128 import re 129 content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings' 130 131 # content=re.sub('\d+','',content) 132 # print(content) 133 134 135 #用\1取得第一个括号的内容 136 #用法:将123与456换位置 137 # import re 138 # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings' 139 # 140 # # content=re.sub('(Extra.*?)(\d+)(\s)(\d+)(.*?strings)',r'\1\4\3\2\5',content) 141 # content=re.sub('(\d+)(\s)(\d+)',r'\3\2\1',content) 142 # print(content) 143 144 145 146 147 # import re 148 # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings' 149 # 150 # res=re.search('Extra.*?(\d+).*strings',content) 151 # print(res.group(1)) 152 153 154 # import requests,re 155 # respone=requests.get('https://book.douban.com/').text 156 157 # print(respone) 158 # print('======'*1000) 159 # print('======'*1000) 160 # print('======'*1000) 161 # print('======'*1000) 162 # res=re.findall('<li.*?cover.*?href="(.*?)".*?title="(.*?)">.*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span.*?</li>',respone,re.S) 163 # # res=re.findall('<li.*?cover.*?href="(.*?)".*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span>.*?</li>',respone,re.S) 164 # 165 # 166 # for i in res: 167 # print('%s %s %s %s' %(i[0].strip(),i[1].strip(),i[2].strip(),i[3].strip()))
match
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
# match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None match(pattern, string, flags=0) # pattern: 正则模型 # string : 要匹配的字符串 # falgs : 匹配模式 X VERBOSE Ignore whitespace and comments for nicer looking RE's. I IGNORECASE Perform case-insensitive matching. M MULTILINE "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. S DOTALL "." matches any character at all, including the newline. A ASCII For string patterns, make \w, \W, \b, \B, \d, \D match the corresponding ASCII character categories (rather than the whole Unicode categories, which is the default). For bytes patterns, this flag is the only available behaviour and needn't be specified. L LOCALE Make \w, \W, \b, \B, dependent on the current locale. U UNICODE For compatibility only. Ignored for string patterns (it is the default), and forbidden for bytes patterns. |
1 # 无分组 2 r = re.match("h\w+", origin) 3 print(r.group()) # 获取匹配到的所有结果 4 print(r.groups()) # 获取模型中匹配到的分组结果 5 print(r.groupdict()) # 获取模型中匹配到的分组结果 6 7 # 有分组 8 9 # 为何要有分组?提取匹配成功的指定内容(先匹配成功全部正则,再匹配成功的局部内容提取出来) 10 11 r = re.match("h(\w+).*(?P<name>\d)$", origin) 12 print(r.group()) # 获取匹配到的所有结果 13 print(r.groups()) # 获取模型中匹配到的分组结果 14 print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
search
|
1
2
|
# search,浏览整个字符串去匹配第一个,未匹配成功返回None# search(pattern, string, flags=0) |
1 #无分组 2 r = re.search("a\w+", "oraigin") 3 print(r.group()) # 获取匹配到的所有结果 4 print(r.groups()) # 获取模型中匹配到的分组结果 5 print(r.groupdict()) # 获取模型中匹配到的分组结果 6 # 有分组 7 r = re.search("(a\w+).*(?P<ret>\d)$", "aor124657iggfs123i124n214214") 8 print(r.group()) # 获取匹配到的所有结果 9 print(r.groups()) # 获取模型中匹配到的分组结果 10 print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
findall
|
1
2
3
|
# findall,获取非重复的匹配列表;如果有一个组则以列表形式返回,且每一个匹配均是字符串;如果模型中有多个组,则以列表形式返回,且每一个匹配均是元祖;# 空的匹配也会包含在结果中#findall(pattern, string, flags=0) |
1 # 无分组 2 r = re.findall("a\w+",origin) 3 print(r) 4 5 # 有分组 6 origin = "hello alex bcd abcd lge acd 19" 7 r = re.findall("a((\w*)c)(d)", origin) 8 print(r)
sub
|
1
2
3
4
5
6
7
8
|
# sub,替换匹配成功的指定位置字符串sub(pattern, repl, string, count=0, flags=0)# pattern: 正则模型# repl : 要替换的字符串或可执行对象# string : 要匹配的字符串# count : 指定匹配个数# flags : 匹配模式 |
1 # 与分组无关 2 3 origin = "hello alex bcd alex lge alex acd 19" 4 r = re.sub("a\w+", "999", origin, 2) 5 print(r)
Split
|
1
2
3
4
5
6
7
|
# split,根据正则匹配分割字符串split(pattern, string, maxsplit=0, flags=0)# pattern: 正则模型# string : 要匹配的字符串# maxsplit:指定分割个数# flags : 匹配模式 |
1 # 无分组 2 origin = "hello alex bcd alex lge alex acd 19" 3 r = re.split("alex", origin, 1) 4 print(r) 5 6 # 有分组 7 8 origin = "hello alex bcd alex lge alex acd 19" 9 r1 = re.split("(alex)", origin, 1) 10 print(r1) 11 r2 = re.split("(al(ex))", origin, 1) 12 print(r2)
1 IP: 2 ^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$ 3 手机号: 4 ^1[3|4|5|8][0-9]\d{8}$ 5 邮箱: 6 [a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+
finditer
import re ret = re.finditer("\d","as123kd3ja6k754ld") print(ret) #打印结果是一个迭代器<callable_iterator object at 0x0000000000B37278> print(next(ret).group())
print(next(ret).group())
六、序列化json&pickle模块
之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval就不管用了,所以eval的重点还是通常用来执行一个字符串表达式,并返回表达式的值。
1 import json 2 x="[null,true,false,1]" 3 print(eval(x)) #报错,无法解析null类型,而json就可以 4 print(json.loads(x))
什么是序列化?
我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
为什么要序列化?
1:持久保存状态
需知一个软件/程序的执行就在处理一系列状态的变化,在编程语言中,'状态'会以各种各样有结构的数据类型(也可简单的理解为变量)的形式被保存在内存中。
内存是无法永久保存数据的,当程序运行了一段时间,我们断电或者重启程序,内存中关于这个程序的之前一段时间的数据(有结构)都被清空了。
在断电或重启程序之前将程序当前内存中所有的数据都保存下来(保存到文件中),以便于下次程序执行能够从文件中载入之前的数据,然后继续执行,这就是序列化。
具体的来说,你玩使命召唤闯到了第13关,你保存游戏状态,关机走人,下次再玩,还能从上次的位置开始继续闯关。或如,虚拟机状态的挂起等。
2:跨平台数据交互
序列化之后,不仅可以把序列化后的内容写入磁盘,还可以通过网络传输到别的机器上,如果收发的双方约定好实用一种序列化的格式,那么便打破了平台/语言差异化带来的限制,实现了跨平台数据交互。
反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。
如何序列化之json和pickle:
json
如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。
JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:


import json dic={'name':'alvin','age':23,'sex':'male'} print(type(dic))#<class 'dict'> j=json.dumps(dic) print(type(j))#<class 'str'> f=open('序列化对象','w') f.write(j) #-------------------等价于json.dump(dic,f) f.close() #-----------------------------反序列化<br> import json f=open('序列化对象') data=json.loads(f.read())# 等价于data=json.load(f)
----------------------------------json内部是怎么处理数据类型的-------------------------------------
dic={'name':'alex'} #---->首先将数据内部的引号变成双引号{"name":"alex"}----->再统一将隐形的其转换为str '{"name":"alex"}'
i=8 #---->'8'
s='hello' #---->"hello"------>'"hello"'
l=[11,22] #---->"[11,22]"
json只认识双引,他会把你数据结构里的引号都变成双引号,然后再隐形的为数据加上引号变成str。
1 import json 2 #dct="{'1':111}"#json 不认单引号 3 #dct=str({"1":111})#报错,因为生成的数据还是单引号:{'one': 1} 4 5 dct='{"1":"111"}' 6 print(json.loads(dct)) 7 8 #conclusion: 9 # 无论数据是怎样创建的,只要满足json格式,就可以json.loads出来,不一定非要dumps的数据才能loads 10 11 注意点
pickle

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保存那些不重要的数据,不能成功地反序列化也没关系。
总结:
Python中用于序列化的两个模块
- json 用于【字符串】和 【python基本数据类型】 间进行转换
- pickle 用于【python特有的类型】 和 【python基本数据类型】间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load

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()
七、configparser
configparser用于处理特定格式的文件,其本质上是利用open来操作文件。
1 # 注释1 2 ; 注释2 3 4 [section1] # 节点 5 k1 = v1 # 值 6 k2:v2 # 值 7 8 [section2] # 节点 9 k1 = v1 # 值
1、获取所有节点
|
1
2
3
4
5
6
|
import configparserconfig = configparser.ConfigParser()config.read('xxxooo', encoding='utf-8')ret = config.sections()print(ret) |
2、获取指定节点下所有的键值对
|
1
2
3
4
5
6
|
import configparserconfig = configparser.ConfigParser()config.read('xxxooo', encoding='utf-8')ret = config.items('section1')print(ret) |
3、获取指定节点下所有的建
|
1
2
3
4
5
6
|
import configparserconfig = configparser.ConfigParser()config.read('xxxooo', encoding='utf-8')ret = config.options('section1')print(ret) |
4、获取指定节点下指定key的值
|
1
2
3
4
5
6
7
8
9
10
11
12
|
import configparserconfig = configparser.ConfigParser()config.read('xxxooo', encoding='utf-8')v = config.get('section1', 'k1')# v = config.getint('section1', 'k1')# v = config.getfloat('section1', 'k1')# v = config.getboolean('section1', 'k1')print(v) |
5、检查、删除、添加节点
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import configparserconfig = configparser.ConfigParser()config.read('xxxooo', encoding='utf-8')# 检查has_sec = config.has_section('section1')print(has_sec)# 添加节点config.add_section("SEC_1")config.write(open('xxxooo', 'w'))# 删除节点config.remove_section("SEC_1")config.write(open('xxxooo', 'w')) |
6、检查、删除、设置指定组内的键值对
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import configparserconfig = configparser.ConfigParser()config.read('xxxooo', encoding='utf-8')# 检查has_opt = config.has_option('section1', 'k1')print(has_opt)# 删除config.remove_option('section1', 'k1')config.write(open('xxxooo', 'w'))# 设置config.set('section1', 'k10', "123")config.write(open('xxxooo', 'w')) |
示例:
配置文件如下:
# 注释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') print(val1) #18 #查看标题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'))
1 import configparser 2 3 config = configparser.ConfigParser() 4 config["DEFAULT"] = {'ServerAliveInterval': '45', 5 'Compression': 'yes', 6 'CompressionLevel': '9'} 7 8 config['bitbucket.org'] = {} 9 config['bitbucket.org']['User'] = 'hg' 10 config['topsecret.server.com'] = {} 11 topsecret = config['topsecret.server.com'] 12 topsecret['Host Port'] = '50022' # mutates the parser 13 topsecret['ForwardX11'] = 'no' # same here 14 config['DEFAULT']['ForwardX11'] = 'yes' 15 with open('example.ini', 'w') as configfile: 16 config.write(configfile) 17 18 基于上述方法添加一个ini文档
八、XML
XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2026</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2026</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
1、解析XML
1 from xml.etree import ElementTree as ET 2 3 4 # 打开文件,读取XML内容 5 str_xml = open('xo.xml', 'r').read() 6 7 # 将字符串解析成xml特殊对象,root代指xml文件的根节点 8 root = ET.XML(str_xml)
1 from xml.etree import ElementTree as ET 2 3 # 直接解析xml文件 4 tree = ET.parse("xo.xml") 5 6 # 获取xml文件的根节点 7 root = tree.getroot()
2、操作XML
XML格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:
1 class Element: 2 """An XML element. 3 4 This class is the reference implementation of the Element interface. 5 6 An element's length is its number of subelements. That means if you 7 want to check if an element is truly empty, you should check BOTH 8 its length AND its text attribute. 9 10 The element tag, attribute names, and attribute values can be either 11 bytes or strings. 12 13 *tag* is the element name. *attrib* is an optional dictionary containing 14 element attributes. *extra* are additional element attributes given as 15 keyword arguments. 16 17 Example form: 18 <tag attrib>text<child/>...</tag>tail 19 20 """ 21 22 当前节点的标签名 23 tag = None 24 """The element's name.""" 25 26 当前节点的属性 27 28 attrib = None 29 """Dictionary of the element's attributes.""" 30 31 当前节点的内容 32 text = None 33 """ 34 Text before first subelement. This is either a string or the value None. 35 Note that if there is no text, this attribute may be either 36 None or the empty string, depending on the parser. 37 38 """ 39 40 tail = None 41 """ 42 Text after this element's end tag, but before the next sibling element's 43 start tag. This is either a string or the value None. Note that if there 44 was no text, this attribute may be either None or an empty string, 45 depending on the parser. 46 47 """ 48 49 def __init__(self, tag, attrib={}, **extra): 50 if not isinstance(attrib, dict): 51 raise TypeError("attrib must be dict, not %s" % ( 52 attrib.__class__.__name__,)) 53 attrib = attrib.copy() 54 attrib.update(extra) 55 self.tag = tag 56 self.attrib = attrib 57 self._children = [] 58 59 def __repr__(self): 60 return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self)) 61 62 def makeelement(self, tag, attrib): 63 创建一个新节点 64 """Create a new element with the same type. 65 66 *tag* is a string containing the element name. 67 *attrib* is a dictionary containing the element attributes. 68 69 Do not call this method, use the SubElement factory function instead. 70 71 """ 72 return self.__class__(tag, attrib) 73 74 def copy(self): 75 """Return copy of current element. 76 77 This creates a shallow copy. Subelements will be shared with the 78 original tree. 79 80 """ 81 elem = self.makeelement(self.tag, self.attrib) 82 elem.text = self.text 83 elem.tail = self.tail 84 elem[:] = self 85 return elem 86 87 def __len__(self): 88 return len(self._children) 89 90 def __bool__(self): 91 warnings.warn( 92 "The behavior of this method will change in future versions. " 93 "Use specific 'len(elem)' or 'elem is not None' test instead.", 94 FutureWarning, stacklevel=2 95 ) 96 return len(self._children) != 0 # emulate old behaviour, for now 97 98 def __getitem__(self, index): 99 return self._children[index] 100 101 def __setitem__(self, index, element): 102 # if isinstance(index, slice): 103 # for elt in element: 104 # assert iselement(elt) 105 # else: 106 # assert iselement(element) 107 self._children[index] = element 108 109 def __delitem__(self, index): 110 del self._children[index] 111 112 def append(self, subelement): 113 为当前节点追加一个子节点 114 """Add *subelement* to the end of this element. 115 116 The new element will appear in document order after the last existing 117 subelement (or directly after the text, if it's the first subelement), 118 but before the end tag for this element. 119 120 """ 121 self._assert_is_element(subelement) 122 self._children.append(subelement) 123 124 def extend(self, elements): 125 为当前节点扩展 n 个子节点 126 """Append subelements from a sequence. 127 128 *elements* is a sequence with zero or more elements. 129 130 """ 131 for element in elements: 132 self._assert_is_element(element) 133 self._children.extend(elements) 134 135 def insert(self, index, subelement): 136 在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置 137 """Insert *subelement* at position *index*.""" 138 self._assert_is_element(subelement) 139 self._children.insert(index, subelement) 140 141 def _assert_is_element(self, e): 142 # Need to refer to the actual Python implementation, not the 143 # shadowing C implementation. 144 if not isinstance(e, _Element_Py): 145 raise TypeError('expected an Element, not %s' % type(e).__name__) 146 147 def remove(self, subelement): 148 在当前节点在子节点中删除某个节点 149 """Remove matching subelement. 150 151 Unlike the find methods, this method compares elements based on 152 identity, NOT ON tag value or contents. To remove subelements by 153 other means, the easiest way is to use a list comprehension to 154 select what elements to keep, and then use slice assignment to update 155 the parent element. 156 157 ValueError is raised if a matching element could not be found. 158 159 """ 160 # assert iselement(element) 161 self._children.remove(subelement) 162 163 def getchildren(self): 164 获取所有的子节点(废弃) 165 """(Deprecated) Return all subelements. 166 167 Elements are returned in document order. 168 169 """ 170 warnings.warn( 171 "This method will be removed in future versions. " 172 "Use 'list(elem)' or iteration over elem instead.", 173 DeprecationWarning, stacklevel=2 174 ) 175 return self._children 176 177 def find(self, path, namespaces=None): 178 获取第一个寻找到的子节点 179 """Find first matching element by tag name or path. 180 181 *path* is a string having either an element tag or an XPath, 182 *namespaces* is an optional mapping from namespace prefix to full name. 183 184 Return the first matching element, or None if no element was found. 185 186 """ 187 return ElementPath.find(self, path, namespaces) 188 189 def findtext(self, path, default=None, namespaces=None): 190 获取第一个寻找到的子节点的内容 191 """Find text for first matching element by tag name or path. 192 193 *path* is a string having either an element tag or an XPath, 194 *default* is the value to return if the element was not found, 195 *namespaces* is an optional mapping from namespace prefix to full name. 196 197 Return text content of first matching element, or default value if 198 none was found. Note that if an element is found having no text 199 content, the empty string is returned. 200 201 """ 202 return ElementPath.findtext(self, path, default, namespaces) 203 204 def findall(self, path, namespaces=None): 205 获取所有的子节点 206 """Find all matching subelements by tag name or path. 207 208 *path* is a string having either an element tag or an XPath, 209 *namespaces* is an optional mapping from namespace prefix to full name. 210 211 Returns list containing all matching elements in document order. 212 213 """ 214 return ElementPath.findall(self, path, namespaces) 215 216 def iterfind(self, path, namespaces=None): 217 获取所有指定的节点,并创建一个迭代器(可以被for循环) 218 """Find all matching subelements by tag name or path. 219 220 *path* is a string having either an element tag or an XPath, 221 *namespaces* is an optional mapping from namespace prefix to full name. 222 223 Return an iterable yielding all matching elements in document order. 224 225 """ 226 return ElementPath.iterfind(self, path, namespaces) 227 228 def clear(self): 229 清空节点 230 """Reset element. 231 232 This function removes all subelements, clears all attributes, and sets 233 the text and tail attributes to None. 234 235 """ 236 self.attrib.clear() 237 self._children = [] 238 self.text = self.tail = None 239 240 def get(self, key, default=None): 241 获取当前节点的属性值 242 """Get element attribute. 243 244 Equivalent to attrib.get, but some implementations may handle this a 245 bit more efficiently. *key* is what attribute to look for, and 246 *default* is what to return if the attribute was not found. 247 248 Returns a string containing the attribute value, or the default if 249 attribute was not found. 250 251 """ 252 return self.attrib.get(key, default) 253 254 def set(self, key, value): 255 为当前节点设置属性值 256 """Set element attribute. 257 258 Equivalent to attrib[key] = value, but some implementations may handle 259 this a bit more efficiently. *key* is what attribute to set, and 260 *value* is the attribute value to set it to. 261 262 """ 263 self.attrib[key] = value 264 265 def keys(self): 266 获取当前节点的所有属性的 key 267 268 """Get list of attribute names. 269 270 Names are returned in an arbitrary order, just like an ordinary 271 Python dict. Equivalent to attrib.keys() 272 273 """ 274 return self.attrib.keys() 275 276 def items(self): 277 获取当前节点的所有属性值,每个属性都是一个键值对 278 """Get element attributes as a sequence. 279 280 The attributes are returned in arbitrary order. Equivalent to 281 attrib.items(). 282 283 Return a list of (name, value) tuples. 284 285 """ 286 return self.attrib.items() 287 288 def iter(self, tag=None): 289 在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。 290 """Create tree iterator. 291 292 The iterator loops over the element and all subelements in document 293 order, returning all elements with a matching tag. 294 295 If the tree structure is modified during iteration, new or removed 296 elements may or may not be included. To get a stable set, use the 297 list() function on the iterator, and loop over the resulting list. 298 299 *tag* is what tags to look for (default is to return all elements) 300 301 Return an iterator containing all the matching elements. 302 303 """ 304 if tag == "*": 305 tag = None 306 if tag is None or self.tag == tag: 307 yield self 308 for e in self._children: 309 yield from e.iter(tag) 310 311 # compatibility 312 def getiterator(self, tag=None): 313 # Change for a DeprecationWarning in 1.4 314 warnings.warn( 315 "This method will be removed in future versions. " 316 "Use 'elem.iter()' or 'list(elem.iter())' instead.", 317 PendingDeprecationWarning, stacklevel=2 318 ) 319 return list(self.iter(tag)) 320 321 def itertext(self): 322 在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。 323 """Create text iterator. 324 325 The iterator loops over the element and all subelements in document 326 order, returning all inner text. 327 328 """ 329 tag = self.tag 330 if not isinstance(tag, str) and tag is not None: 331 return 332 if self.text: 333 yield self.text 334 for e in self: 335 yield from e.itertext() 336 if e.tail: 337 yield e.tail 338 339 节点功能一览表
由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so 可以利用以上方法进行操作xml文件。
a. 遍历XML文档的所有内容
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式一 ############ 4 """ 5 # 打开文件,读取XML内容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 将字符串解析成xml特殊对象,root代指xml文件的根节点 9 root = ET.XML(str_xml) 10 """ 11 ############ 解析方式二 ############ 12 13 # 直接解析xml文件 14 tree = ET.parse("xo.xml") 15 16 # 获取xml文件的根节点 17 root = tree.getroot() 18 19 20 ### 操作 21 22 # 顶层标签 23 print(root.tag) 24 25 26 # 遍历XML中所有的year节点 27 for node in root.iter('year'): 28 # 节点的标签名称和内容 29 print(node.tag, node.text)
b、遍历XML中指定的节点
View Codec、修改节点内容
由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式一 ############ 4 5 # 打开文件,读取XML内容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 将字符串解析成xml特殊对象,root代指xml文件的根节点 9 root = ET.XML(str_xml) 10 11 ############ 操作 ############ 12 13 # 顶层标签 14 print(root.tag) 15 16 # 循环所有的year节点 17 for node in root.iter('year'): 18 # 将year节点中的内容自增一 19 new_year = int(node.text) + 1 20 node.text = str(new_year) 21 22 # 设置属性 23 node.set('name', 'alex') 24 node.set('age', '18') 25 # 删除属性 26 del node.attrib['name'] 27 28 29 ############ 保存文件 ############ 30 tree = ET.ElementTree(root) 31 tree.write("newnew.xml", encoding='utf-8')
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式二 ############ 4 5 # 直接解析xml文件 6 tree = ET.parse("xo.xml") 7 8 # 获取xml文件的根节点 9 root = tree.getroot() 10 11 ############ 操作 ############ 12 13 # 顶层标签 14 print(root.tag) 15 16 # 循环所有的year节点 17 for node in root.iter('year'): 18 # 将year节点中的内容自增一 19 new_year = int(node.text) + 1 20 node.text = str(new_year) 21 22 # 设置属性 23 node.set('name', 'alex') 24 node.set('age', '18') 25 # 删除属性 26 del node.attrib['name'] 27 28 29 ############ 保存文件 ############ 30 tree.write("newnew.xml", encoding='utf-8')
d、删除节点
1 from xml.etree import ElementTree as ET 2 3 ############ 解析字符串方式打开 ############ 4 5 # 打开文件,读取XML内容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 将字符串解析成xml特殊对象,root代指xml文件的根节点 9 root = ET.XML(str_xml) 10 11 ############ 操作 ############ 12 13 # 顶层标签 14 print(root.tag) 15 16 # 遍历data下的所有country节点 17 for country in root.findall('country'): 18 # 获取每一个country节点下rank节点的内容 19 rank = int(country.find('rank').text) 20 21 if rank > 50: 22 # 删除指定country节点 23 root.remove(country) 24 25 ############ 保存文件 ############ 26 tree = ET.ElementTree(root) 27 tree.write("newnew.xml", encoding='utf-8')
1 from xml.etree import ElementTree as ET 2 3 ############ 解析文件方式 ############ 4 5 # 直接解析xml文件 6 tree = ET.parse("xo.xml") 7 8 # 获取xml文件的根节点 9 root = tree.getroot() 10 11 ############ 操作 ############ 12 13 # 顶层标签 14 print(root.tag) 15 16 # 遍历data下的所有country节点 17 for country in root.findall('country'): 18 # 获取每一个country节点下rank节点的内容 19 rank = int(country.find('rank').text) 20 21 if rank > 50: 22 # 删除指定country节点 23 root.remove(country) 24 25 ############ 保存文件 ############ 26 tree.write("newnew.xml", encoding='utf-8')
3、创建XML文档
1 from xml.etree import ElementTree as ET 2 3 4 # 创建根节点 5 root = ET.Element("famliy") 6 7 8 # 创建节点大儿子 9 son1 = ET.Element('son', {'name': '儿1'}) 10 # 创建小儿子 11 son2 = ET.Element('son', {"name": '儿2'}) 12 13 # 在大儿子中创建两个孙子 14 grandson1 = ET.Element('grandson', {'name': '儿11'}) 15 grandson2 = ET.Element('grandson', {'name': '儿12'}) 16 son1.append(grandson1) 17 son1.append(grandson2) 18 19 20 # 把儿子添加到根节点中 21 root.append(son1) 22 root.append(son1) 23 24 tree = ET.ElementTree(root) 25 tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
1 from xml.etree import ElementTree as ET 2 3 # 创建根节点 4 root = ET.Element("famliy") 5 6 7 # 创建大儿子 8 # son1 = ET.Element('son', {'name': '儿1'}) 9 son1 = root.makeelement('son', {'name': '儿1'}) 10 # 创建小儿子 11 # son2 = ET.Element('son', {"name": '儿2'}) 12 son2 = root.makeelement('son', {"name": '儿2'}) 13 14 # 在大儿子中创建两个孙子 15 # grandson1 = ET.Element('grandson', {'name': '儿11'}) 16 grandson1 = son1.makeelement('grandson', {'name': '儿11'}) 17 # grandson2 = ET.Element('grandson', {'name': '儿12'}) 18 grandson2 = son1.makeelement('grandson', {'name': '儿12'}) 19 20 son1.append(grandson1) 21 son1.append(grandson2) 22 23 24 # 把儿子添加到根节点中 25 root.append(son1) 26 root.append(son1) 27 28 tree = ET.ElementTree(root) 29 tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
1 from xml.etree import ElementTree as ET 2 3 4 # 创建根节点 5 root = ET.Element("famliy") 6 7 8 # 创建节点大儿子 9 son1 = ET.SubElement(root, "son", attrib={'name': '儿1'}) 10 # 创建小儿子 11 son2 = ET.SubElement(root, "son", attrib={"name": "儿2"}) 12 13 # 在大儿子中创建一个孙子 14 grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'}) 15 grandson1.text = '孙子' 16 17 18 et = ET.ElementTree(root) #生成文档对象 19 et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False) 20 21 创建方式(三)
由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:
1 from xml.etree import ElementTree as ET 2 from xml.dom import minidom 3 4 5 def prettify(elem): 6 """将节点转换成字符串,并添加缩进。 7 """ 8 rough_string = ET.tostring(elem, 'utf-8') 9 reparsed = minidom.parseString(rough_string) 10 return reparsed.toprettyxml(indent="\t") 11 12 # 创建根节点 13 root = ET.Element("famliy") 14 15 16 # 创建大儿子 17 # son1 = ET.Element('son', {'name': '儿1'}) 18 son1 = root.makeelement('son', {'name': '儿1'}) 19 # 创建小儿子 20 # son2 = ET.Element('son', {"name": '儿2'}) 21 son2 = root.makeelement('son', {"name": '儿2'}) 22 23 # 在大儿子中创建两个孙子 24 # grandson1 = ET.Element('grandson', {'name': '儿11'}) 25 grandson1 = son1.makeelement('grandson', {'name': '儿11'}) 26 # grandson2 = ET.Element('grandson', {'name': '儿12'}) 27 grandson2 = son1.makeelement('grandson', {'name': '儿12'}) 28 29 son1.append(grandson1) 30 son1.append(grandson2) 31 32 33 # 把儿子添加到根节点中 34 root.append(son1) 35 root.append(son1) 36 37 38 raw_str = prettify(root) 39 40 f = open("xxxoo.xml",'w',encoding='utf-8') 41 f.write(raw_str) 42 f.close()
4、命名空间
详细介绍,http://www.w3school.com.cn/xml/xml_namespaces.asp
1 from xml.etree import ElementTree as ET 2 3 ET.register_namespace('com',"http://www.company.com") #some name 4 5 # build a tree structure 6 root = ET.Element("{http://www.company.com}STUFF") 7 body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF", attrib={"{http://www.company.com}hhh": "123"}) 8 body.text = "STUFF EVERYWHERE!" 9 10 # wrap it in an ElementTree instance, and save as XML 11 tree = ET.ElementTree(root) 12 13 tree.write("page.xml", 14 xml_declaration=True, 15 encoding='utf-8', 16 method="xml")
九、requests
Python标准库中提供了:urllib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。
1 import urllib.request 2 3 4 f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508') 5 result = f.read().decode('utf-8')
1 import urllib.request 2 3 req = urllib.request.Request('http://www.example.com/') 4 req.add_header('Referer', 'http://www.python.org/') 5 r = urllib.request.urlopen(req) 6 7 result = f.read().decode('utf-8')
注:更多见Python官方文档:https://docs.python.org/3.5/library/urllib.request.html#module-urllib.request
Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作。
1、安装模块
|
1
|
pip3 install requests |
2、使用模块
1 # 1、无参数实例 2 3 import requests 4 5 ret = requests.get('https://github.com/timeline.json') 6 7 print(ret.url) 8 print(ret.text) 9 10 11 12 # 2、有参数实例 13 14 import requests 15 16 payload = {'key1': 'value1', 'key2': 'value2'} 17 ret = requests.get("http://httpbin.org/get", params=payload) 18 19 print(ret.url) 20 print(ret.text) 21 22 GET请求
1 # 1、基本POST实例 2 3 import requests 4 5 payload = {'key1': 'value1', 'key2': 'value2'} 6 ret = requests.post("http://httpbin.org/post", data=payload) 7 8 print(ret.text) 9 10 11 # 2、发送请求头和数据实例 12 13 import requests 14 import json 15 16 url = 'https://api.github.com/some/endpoint' 17 payload = {'some': 'data'} 18 headers = {'content-type': 'application/json'} 19 20 ret = requests.post(url, data=json.dumps(payload), headers=headers) 21 22 print(ret.text) 23 print(ret.cookies)
1 requests.get(url, params=None, **kwargs) 2 requests.post(url, data=None, json=None, **kwargs) 3 requests.put(url, data=None, **kwargs) 4 requests.head(url, **kwargs) 5 requests.delete(url, **kwargs) 6 requests.patch(url, data=None, **kwargs) 7 requests.options(url, **kwargs) 8 9 # 以上方法均是在此方法的基础上构建 10 requests.request(method, url, **kwargs)
更多requests模块相关的文档见:http://cn.python-requests.org/zh_CN/latest/
3、Http请求和XML实例
实例:检测QQ账号是否在线
1 import urllib 2 import requests 3 from xml.etree import ElementTree as ET 4 5 # 使用内置模块urllib发送HTTP请求,或者XML格式内容 6 """ 7 f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508') 8 result = f.read().decode('utf-8') 9 """ 10 11 12 # 使用第三方模块requests发送HTTP请求,或者XML格式内容 13 r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508') 14 result = r.text 15 16 # 解析XML格式内容 17 node = ET.XML(result) 18 19 # 获取内容 20 if node.text == "Y": 21 print("在线") 22 else: 23 print("离线")
实例:查看火车停靠信息
1 import urllib 2 import requests 3 from xml.etree import ElementTree as ET 4 5 # 使用内置模块urllib发送HTTP请求,或者XML格式内容 6 """ 7 f = urllib.request.urlopen('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=') 8 result = f.read().decode('utf-8') 9 """ 10 11 # 使用第三方模块requests发送HTTP请求,或者XML格式内容 12 r = requests.get('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=') 13 result = r.text 14 15 # 解析XML格式内容 16 root = ET.XML(result) 17 for node in root.iter('TrainDetailInfo'): 18 print(node.find('TrainStation').text,node.find('StartTime').text,node.tag,node.attrib)
注:更多接口http://www.cnblogs.com/wupeiqi/archive/2012/11/18/2776014.html
十、logging
用于便捷记录日志且线程安全的模块
1、单文件日志
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import logging logging.basicConfig(filename='log.log',#将输出从屏幕改到log.log文件,默认是屏幕 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',#设置日志打印的格式 datefmt='%Y-%m-%d %H:%M:%S %p', level=10 #设置日志级别或者是level=logging.DEBUG filemode='w'#将模式改为写(替换)模式,默认追加) logging.debug('debug')logging.info('info')logging.warning('warning')logging.error('error')logging.critical('critical')logging.log(10,'log') |
补充:
1 def logger(): 2 logger=logging.getLogger() #创建一个logger用户默认不设置子用户.logger=logging.getLogger('mylogger')定义了一个子用户 3 4 5 fh=logging.FileHandler("test_log") #定义一个fh的用户只能向文件发送内容需要有一个参数,文件名 6 ch=logging.StreamHandler() #定义一个ch的用户只能向屏幕发送内容 7 8 fm=logging.Formatter("%(asctime)s %(message)s") #定义一个对象用来设置格式 9 10 fh.setFormatter(fm) #让fc吃掉fm 11 ch.setFormatter(fm) #让ch吃掉fm 12 13 logger.addHandler(fh) logger将fh的功能吃掉 14 logger.addHandler(ch) logger将ch的功能吃掉 15 logger.setLevel("DEBUG") 16 17 return logger
2、多文件日志
对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象。
1 # 定义文件 2 file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8') 3 fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s") 4 file_1_1.setFormatter(fmt) 5 6 file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8') 7 fmt = logging.Formatter() 8 file_1_2.setFormatter(fmt) 9 10 # 定义日志 11 logger1 = logging.Logger('s1', level=logging.ERROR) 12 logger1.addHandler(file_1_1) 13 logger1.addHandler(file_1_2) 14 15 16 # 写日志 17 logger1.critical('1111')
1 # 定义文件 2 file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8') 3 fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s") 4 file_1_1.setFormatter(fmt) 5 6 file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8') 7 fmt = logging.Formatter() 8 file_1_2.setFormatter(fmt) 9 10 # 定义日志 11 logger1 = logging.Logger('s1', level=logging.ERROR) 12 logger1.addHandler(file_1_1) 13 logger1.addHandler(file_1_2) 14 15 16 # 写日志 17 logger1.critical('1111')
如上述创建的两个日志对象
- 当使用【logger1】写日志时,会将相应的内容写入 l1_1.log 和 l1_2.log 文件中
- 当使用【logger2】写日志时,会将相应的内容写入 l2_1.log 文件中
另外:
1 日志级别
CRITICAL = 50 #FATAL = CRITICAL ERROR = 40 WARNING = 30 #WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 #不设置
2 默认级别为warning,默认打印到终端
import logging logging.debug('调试debug') logging.info('消息info') logging.warning('警告warn') logging.error('错误error') logging.critical('严重critical') ''' WARNING:root:警告warn ERROR:root:错误error CRITICAL:root:严重critical '''
3 为logging模块指定全局配置,针对所有logger有效,控制打印到文件中
1 可在logging.basicConfig()函数中通过具体参数来更改logging模块默认行为,可用参数有 2 filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。 3 filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。 4 format:指定handler使用的日志显示格式。 5 datefmt:指定日期时间格式。 6 level:设置rootlogger(后边会讲解具体概念)的日志级别 7 stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。 8 9 10 11 #格式 12 %(name)s:Logger的名字,并非用户名,详细查看 13 14 %(levelno)s:数字形式的日志级别 15 16 %(levelname)s:文本形式的日志级别 17 18 %(pathname)s:调用日志输出函数的模块的完整路径名,可能没有 19 20 %(filename)s:调用日志输出函数的模块的文件名 21 22 %(module)s:调用日志输出函数的模块名 23 24 %(funcName)s:调用日志输出函数的函数名 25 26 %(lineno)d:调用日志输出函数的语句所在的代码行 27 28 %(created)f:当前时间,用UNIX标准的表示时间的浮 点数表示 29 30 %(relativeCreated)d:输出日志信息时的,自Logger创建以 来的毫秒数 31 32 %(asctime)s:字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 33 34 %(thread)d:线程ID。可能没有 35 36 %(threadName)s:线程名。可能没有 37 38 %(process)d:进程ID。可能没有 39 40 %(message)s:用户输出的消息 41 42 43 44 logging.basicConfig()
1 #======介绍 2 可在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有 3 filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。 4 filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。 5 format:指定handler使用的日志显示格式。 6 datefmt:指定日期时间格式。 7 level:设置rootlogger(后边会讲解具体概念)的日志级别 8 stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。 9 10 11 format参数中可能用到的格式化串: 12 %(name)s Logger的名字 13 %(levelno)s 数字形式的日志级别 14 %(levelname)s 文本形式的日志级别 15 %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有 16 %(filename)s 调用日志输出函数的模块的文件名 17 %(module)s 调用日志输出函数的模块名 18 %(funcName)s 调用日志输出函数的函数名 19 %(lineno)d 调用日志输出函数的语句所在的代码行 20 %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示 21 %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 22 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 23 %(thread)d 线程ID。可能没有 24 %(threadName)s 线程名。可能没有 25 %(process)d 进程ID。可能没有 26 %(message)s用户输出的消息 27 28 29 30 31 #========使用 32 import logging 33 logging.basicConfig(filename='access.log', 34 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 35 datefmt='%Y-%m-%d %H:%M:%S %p', 36 level=10) 37 38 logging.debug('调试debug') 39 logging.info('消息info') 40 logging.warning('警告warn') 41 logging.error('错误error') 42 logging.critical('严重critical') 43 44 45 46 47 48 #========结果 49 access.log内容: 50 2017-07-28 20:32:17 PM - root - DEBUG -test: 调试debug 51 2017-07-28 20:32:17 PM - root - INFO -test: 消息info 52 2017-07-28 20:32:17 PM - root - WARNING -test: 警告warn 53 2017-07-28 20:32:17 PM - root - ERROR -test: 错误error 54 2017-07-28 20:32:17 PM - root - CRITICAL -test: 严重critical 55 56 part2: 可以为logging模块指定模块级的配置,即所有logger的配置
4 logging模块的Formatter,Handler,Logger,Filter对象
#logger:产生日志的对象 #Filter:过滤日志的对象 #Handler:接收日志然后控制打印到不同的地方,FileHandler用来打印到文件中,StreamHandler用来打印到终端 #Formatter对象:可以定制不同的日志格式对象,然后绑定给不同的Handler对象使用,以此来控制不同的Handler的日志格式
1 ''' 2 critical=50 3 error =40 4 warning =30 5 info = 20 6 debug =10 7 ''' 8 9 10 import logging 11 12 #1、logger对象:负责产生日志,然后交给Filter过滤,然后交给不同的Handler输出 13 logger=logging.getLogger(__file__) 14 15 #2、Filter对象:不常用,略 16 17 #3、Handler对象:接收logger传来的日志,然后控制输出 18 h1=logging.FileHandler('t1.log') #打印到文件 19 h2=logging.FileHandler('t2.log') #打印到文件 20 h3=logging.StreamHandler() #打印到终端 21 22 #4、Formatter对象:日志格式 23 formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 24 datefmt='%Y-%m-%d %H:%M:%S %p',) 25 26 formmater2=logging.Formatter('%(asctime)s : %(message)s', 27 datefmt='%Y-%m-%d %H:%M:%S %p',) 28 29 formmater3=logging.Formatter('%(name)s %(message)s',) 30 31 32 #5、为Handler对象绑定格式 33 h1.setFormatter(formmater1) 34 h2.setFormatter(formmater2) 35 h3.setFormatter(formmater3) 36 37 #6、将Handler添加给logger并设置日志级别 38 logger.addHandler(h1) 39 logger.addHandler(h2) 40 logger.addHandler(h3) 41 logger.setLevel(10) 42 43 #7、测试 44 logger.debug('debug') 45 logger.info('info') 46 logger.warning('warning') 47 logger.error('error') 48 logger.critical('critical')
5 Logger与Handler的级别
logger是第一级过滤,然后才能到handler,我们可以给logger和handler同时设置level,但是需要注意的是
1 Logger is also the first to filter the message based on a level — if you set the logger to INFO, and all handlers to DEBUG, you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself. If you set logger to DEBUG, but all handlers to INFO, you won't receive any DEBUG messages either — because while the logger says "ok, process this", the handlers reject it (DEBUG < INFO). 2 3 4 5 #验证 6 import logging 7 8 9 form=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 10 datefmt='%Y-%m-%d %H:%M:%S %p',) 11 12 ch=logging.StreamHandler() 13 14 ch.setFormatter(form) 15 # ch.setLevel(10) 16 ch.setLevel(20) 17 18 l1=logging.getLogger('root') 19 # l1.setLevel(20) 20 l1.setLevel(10) 21 l1.addHandler(ch) 22 23 l1.debug('l1 debug') 24 25 重要,重要,重要!!!
6 Logger的继承(了解)
1 import logging 2 3 formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 4 datefmt='%Y-%m-%d %H:%M:%S %p',) 5 6 ch=logging.StreamHandler() 7 ch.setFormatter(formatter) 8 9 10 logger1=logging.getLogger('root') 11 logger2=logging.getLogger('root.child1') 12 logger3=logging.getLogger('root.child1.child2') 13 14 15 logger1.addHandler(ch) 16 logger2.addHandler(ch) 17 logger3.addHandler(ch) 18 logger1.setLevel(10) 19 logger2.setLevel(10) 20 logger3.setLevel(10) 21 22 logger1.debug('log1 debug') 23 logger2.debug('log2 debug') 24 logger3.debug('log3 debug') 25 ''' 26 2017-07-28 22:22:05 PM - root - DEBUG -test: log1 debug 27 2017-07-28 22:22:05 PM - root.child1 - DEBUG -test: log2 debug 28 2017-07-28 22:22:05 PM - root.child1 - DEBUG -test: log2 debug 29 2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug 30 2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug 31 2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug 32 '''
7 应用
1 """ 2 logging配置 3 """ 4 5 import os 6 import logging.config 7 8 # 定义三种日志输出格式 开始 9 10 standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \ 11 '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字 12 13 simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' 14 15 id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s' 16 17 # 定义日志输出格式 结束 18 19 logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录 20 21 logfile_name = 'all2.log' # log文件名 22 23 # 如果不存在定义的日志目录就创建一个 24 if not os.path.isdir(logfile_dir): 25 os.mkdir(logfile_dir) 26 27 # log文件的全路径 28 logfile_path = os.path.join(logfile_dir, logfile_name) 29 30 # log配置字典 31 LOGGING_DIC = { 32 'version': 1, 33 'disable_existing_loggers': False, 34 'formatters': { 35 'standard': { 36 'format': standard_format 37 }, 38 'simple': { 39 'format': simple_format 40 }, 41 }, 42 'filters': {}, 43 'handlers': { 44 #打印到终端的日志 45 'console': { 46 'level': 'DEBUG', 47 'class': 'logging.StreamHandler', # 打印到屏幕 48 'formatter': 'simple' 49 }, 50 #打印到文件的日志,收集info及以上的日志 51 'default': { 52 'level': 'DEBUG', 53 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件 54 'formatter': 'standard', 55 'filename': logfile_path, # 日志文件 56 'maxBytes': 1024*1024*5, # 日志大小 5M 57 'backupCount': 5, 58 'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了 59 }, 60 }, 61 'loggers': { 62 #logging.getLogger(__name__)拿到的logger配置 63 '': { 64 'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕 65 'level': 'DEBUG', 66 'propagate': True, # 向上(更高level的logger)传递 67 }, 68 }, 69 } 70 71 72 def load_my_logging_cfg(): 73 logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置 74 logger = logging.getLogger(__name__) # 生成一个log实例 75 logger.info('It works!') # 记录该文件的运行状态 76 77 if __name__ == '__main__': 78 load_my_logging_cfg() 79 80 logging配置文件
1 """ 2 MyLogging Test 3 """ 4 5 import time 6 import logging 7 import my_logging # 导入自定义的logging配置 8 9 logger = logging.getLogger(__name__) # 生成logger实例 10 11 12 def demo(): 13 logger.debug("start range... time:{}".format(time.time())) 14 logger.info("中文测试开始。。。") 15 for i in range(10): 16 logger.debug("i:{}".format(i)) 17 time.sleep(0.2) 18 else: 19 logger.debug("over range... time:{}".format(time.time())) 20 logger.info("中文测试结束。。。") 21 22 if __name__ == "__main__": 23 my_logging.load_my_logging_cfg() # 在你程序文件的入口加载自定义logging配置 24 demo() 25 26 使用
1 注意注意注意: 2 3 4 #1、有了上述方式我们的好处是:所有与logging模块有关的配置都写到字典中就可以了,更加清晰,方便管理 5 6 7 #2、我们需要解决的问题是: 8 1、从字典加载配置:logging.config.dictConfig(settings.LOGGING_DIC) 9 10 2、拿到logger对象来产生日志 11 logger对象都是配置到字典的loggers 键对应的子字典中的 12 按照我们对logging模块的理解,要想获取某个东西都是通过名字,也就是key来获取的 13 于是我们要获取不同的logger对象就是 14 logger=logging.getLogger('loggers子字典的key名') 15 16 17 但问题是:如果我们想要不同logger名的logger对象都共用一段配置,那么肯定不能在loggers子字典中定义n个key 18 'loggers': { 19 'l1': { 20 'handlers': ['default', 'console'], # 21 'level': 'DEBUG', 22 'propagate': True, # 向上(更高level的logger)传递 23 }, 24 'l2: { 25 'handlers': ['default', 'console' ], 26 'level': 'DEBUG', 27 'propagate': False, # 向上(更高level的logger)传递 28 }, 29 'l3': { 30 'handlers': ['default', 'console'], # 31 'level': 'DEBUG', 32 'propagate': True, # 向上(更高level的logger)传递 33 }, 34 35 } 36 37 38 #我们的解决方式是,定义一个空的key 39 'loggers': { 40 '': { 41 'handlers': ['default', 'console'], 42 'level': 'DEBUG', 43 'propagate': True, 44 }, 45 46 } 47 48 这样我们再取logger对象时 49 logging.getLogger(__name__),不同的文件__name__不同,这保证了打印日志时标识信息不同,但是拿着该名字去loggers里找key名时却发现找不到,于是默认使用key=''的配置 50 51 !!!关于如何拿到logger对象的详细解释!!!
另外一个django的配置,瞄一眼就可以,跟上面的一样
1 #logging_config.py 2 LOGGING = { 3 'version': 1, 4 'disable_existing_loggers': False, 5 'formatters': { 6 'standard': { 7 'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' 8 '[%(levelname)s][%(message)s]' 9 }, 10 'simple': { 11 'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' 12 }, 13 'collect': { 14 'format': '%(message)s' 15 } 16 }, 17 'filters': { 18 'require_debug_true': { 19 '()': 'django.utils.log.RequireDebugTrue', 20 }, 21 }, 22 'handlers': { 23 #打印到终端的日志 24 'console': { 25 'level': 'DEBUG', 26 'filters': ['require_debug_true'], 27 'class': 'logging.StreamHandler', 28 'formatter': 'simple' 29 }, 30 #打印到文件的日志,收集info及以上的日志 31 'default': { 32 'level': 'INFO', 33 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切 34 'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # 日志文件 35 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M 36 'backupCount': 3, 37 'formatter': 'standard', 38 'encoding': 'utf-8', 39 }, 40 #打印到文件的日志:收集错误及以上的日志 41 'error': { 42 'level': 'ERROR', 43 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切 44 'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"), # 日志文件 45 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M 46 'backupCount': 5, 47 'formatter': 'standard', 48 'encoding': 'utf-8', 49 }, 50 #打印到文件的日志 51 'collect': { 52 'level': 'INFO', 53 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切 54 'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"), 55 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M 56 'backupCount': 5, 57 'formatter': 'collect', 58 'encoding': "utf-8" 59 } 60 }, 61 'loggers': { 62 #logging.getLogger(__name__)拿到的logger配置 63 '': { 64 'handlers': ['default', 'console', 'error'], 65 'level': 'DEBUG', 66 'propagate': True, 67 }, 68 #logging.getLogger('collect')拿到的logger配置 69 'collect': { 70 'handlers': ['console', 'collect'], 71 'level': 'INFO', 72 } 73 }, 74 } 75 76 77 # ----------- 78 # 用法:拿到俩个logger 79 80 logger = logging.getLogger(__name__) #线上正常的日志 81 collect_logger = logging.getLogger("collect") #领导说,需要为领导们单独定制领导们看的日志
十一、系统命令
可以执行shell命令的相关模块和函数有:
- os.system
- os.spawn*
- os.popen* --废弃
- popen2.* --废弃
- commands.* --废弃,3.x中被移除
1 import commands 2 3 result = commands.getoutput('cmd') 4 result = commands.getstatus('cmd') 5 result = commands.getstatusoutput('cmd')
以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。
call
执行命令,返回状态码
|
1
2
|
ret = subprocess.call(["ls", "-l"], shell=False)ret = subprocess.call("ls -l", shell=True) |
check_call
执行命令,如果执行状态码是 0 ,则返回0,否则抛异常
|
1
2
|
subprocess.check_call(["ls", "-l"])subprocess.check_call("exit 1", shell=True) |
check_output
执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常
|
1
2
|
subprocess.check_output(["echo", "Hello World!"])subprocess.check_output("exit 1", shell=True) |
subprocess.Popen(...)
用于执行复杂的系统命令
参数:
- 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()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
1 import subprocess 2 ret1 = subprocess.Popen(["mkdir","t1"]) 3 ret2 = subprocess.Popen("mkdir t2", shell=True)
终端输入的命令分为两种:
- 输入即可得到输出,如:ifconfig
- 输入进行某环境,依赖再输入,如:python
1 import subprocess 2 3 obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
1 import subprocess 2 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 4 obj.stdin.write("print(1)\n") 5 obj.stdin.write("print(2)") 6 obj.stdin.close() 7 8 cmd_out = obj.stdout.read() 9 obj.stdout.close() 10 cmd_error = obj.stderr.read() 11 obj.stderr.close() 12 13 print(cmd_out) 14 print(cmd_error)
1 import subprocess 2 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 4 obj.stdin.write("print(1)\n") 5 obj.stdin.write("print(2)") 6 7 out_error_list = obj.communicate() 8 print(out_error_list)
1 import subprocess 2 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 4 out_error_list = obj.communicate('print("hello")') 5 print(out_error_list)
十二、shutil
高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中
|
1
2
3
|
import shutilshutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w')) |
shutil.copyfile(src, dst)
拷贝文件
|
1
|
shutil.copyfile('f1.log', 'f2.log') |
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变
|
1
|
shutil.copymode('f1.log', 'f2.log') |
shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
|
1
|
shutil.copystat('f1.log', 'f2.log') |
shutil.copy(src, dst)
拷贝文件和权限
|
1
2
3
|
import shutilshutil.copy('f1.log', 'f2.log') |
shutil.copy2(src, dst)
拷贝文件和状态信息
|
1
2
3
|
import shutilshutil.copy2('f1.log', 'f2.log') |
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹
|
1
2
3
|
import shutilshutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'
#目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
|
1 import shutil 2 3 shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
|
1
2
3
|
import shutilshutil.rmtree('folder1') |
shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。
|
1
2
3
|
import shutilshutil.move('folder1', 'folder3') |
shutil.make_archive(base_name, format,...)
创建压缩包并返回文件路径,例如:zip、tar
创建压缩包并返回文件路径,例如:zip、tar
- base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如:www =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/ - format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
- root_dir: 要压缩的文件夹路径(默认当前目录)
- owner: 用户,默认当前用户
- group: 组,默认当前组
- logger: 用于记录日志,通常是logging.Logger对象
|
1
2
3
4
5
6
7
8
|
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录import shutilret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test') #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录import shutilret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test') |
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
1 import zipfile 2 3 # 压缩 4 z = zipfile.ZipFile('laxi.zip', 'w') 5 z.write('a.log') 6 z.write('data.data') 7 z.close() 8 9 # 解压 10 z = zipfile.ZipFile('laxi.zip', 'r') 11 z.extractall() 12 z.close()
1 import tarfile 2 3 # 压缩 4 tar = tarfile.open('your.tar','w') 5 tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log') 6 tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log') 7 tar.close() 8 9 # 解压 10 tar = tarfile.open('your.tar','r') 11 tar.extractall() # 可设置解压地址 12 tar.close()
十三、paramiko
paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。
1、下载安装
|
1
2
3
|
pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycryptopip3 install pycryptopip3 install paramiko |
2、模块使用
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 import paramiko 5 6 ssh = paramiko.SSHClient() 7 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 8 ssh.connect('192.168.1.108', 22, 'alex', '123') 9 stdin, stdout, stderr = ssh.exec_command('df') 10 print stdout.read() 11 ssh.close();
1 import paramiko 2 3 private_key_path = '/home/auto/.ssh/id_rsa' 4 key = paramiko.RSAKey.from_private_key_file(private_key_path) 5 6 ssh = paramiko.SSHClient() 7 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 8 ssh.connect('主机名 ', 端口, '用户名', key) 9 10 stdin, stdout, stderr = ssh.exec_command('df') 11 print stdout.read() 12 ssh.close() 13 14 执行命令 - 密钥
1 import os,sys 2 import paramiko 3 4 t = paramiko.Transport(('182.92.219.86',22)) 5 t.connect(username='wupeiqi',password='123') 6 sftp = paramiko.SFTPClient.from_transport(t) 7 sftp.put('/tmp/test.py','/tmp/test.py') 8 t.close() 9 10 11 import os,sys 12 import paramiko 13 14 t = paramiko.Transport(('182.92.219.86',22)) 15 t.connect(username='wupeiqi',password='123') 16 sftp = paramiko.SFTPClient.from_transport(t) 17 sftp.get('/tmp/test.py','/tmp/test2.py') 18 t.close()
1 import paramiko 2 3 pravie_key_path = '/home/auto/.ssh/id_rsa' 4 key = paramiko.RSAKey.from_private_key_file(pravie_key_path) 5 6 t = paramiko.Transport(('182.92.219.86',22)) 7 t.connect(username='wupeiqi',pkey=key) 8 9 sftp = paramiko.SFTPClient.from_transport(t) 10 sftp.put('/tmp/test3.py','/tmp/test3.py') 11 12 t.close() 13 14 import paramiko 15 16 pravie_key_path = '/home/auto/.ssh/id_rsa' 17 key = paramiko.RSAKey.from_private_key_file(pravie_key_path) 18 19 t = paramiko.Transport(('182.92.219.86',22)) 20 t.connect(username='wupeiqi',pkey=key) 21 22 sftp = paramiko.SFTPClient.from_transport(t) 23 sftp.get('/tmp/test3.py','/tmp/test4.py') 24 25 t.close() 26 27 上传或下载文件 - 密钥
十四、time&datetime
时间相关的操作,时间有三种表示方式:
- 时间戳 1970年1月1日之后的秒,即:time.time() 给计算机看的做计算用
- 格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d %H-%M-%S') 给人看的
- 结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime() 可以通过 . 调用下面的具体方法
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
print time.time()输出一个时间戳print time.mktime(time.localtime()) print time.gmtime() #可加时间戳参数print time.localtime() #输出一个结构化时间(元组)可加时间戳参数print time.strptime('2014-11-11', '%Y-%m-%d') print time.strftime('%Y-%m-%d') #默认当前时间print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间print time.asctime()print time.asctime(time.localtime())print time.ctime(time.time()) import datetime'''datetime.date:表示日期的类。常用的属性有year, month, daydatetime.time:表示时间的类。常用的属性有hour, minute, second, microseconddatetime.datetime:表示日期时间datetime.timedelta:表示时间间隔,即两个时间点之间的长度timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])strftime("%Y-%m-%d")'''import datetimeprint datetime.datetime.now()print datetime.datetime.now() - datetime.timedelta(days=5) |
1 %Y Year with century as a decimal number. 2 %m Month as a decimal number [01,12]. 3 %d Day of the month as a decimal number [01,31]. 4 %H Hour (24-hour clock) as a decimal number [00,23]. 5 %M Minute as a decimal number [00,59]. 6 %S Second as a decimal number [00,61]. 7 %z Time zone offset from UTC. 8 %a Locale's abbreviated weekday name. 9 %A Locale's full weekday name. 10 %b Locale's abbreviated month name. 11 %B Locale's full month name. 12 %c Locale's appropriate date and time representation. 13 %I Hour (12-hour clock) as a decimal number [01,12]. 14 %p Locale's equivalent of either AM or PM.
其中计算机认识的时间只能是'时间戳'格式,而程序员可处理的或者说人类能看懂的时间有: '格式化的时间字符串','结构化的时间' ,于是有了下图的转换关系

#--------------------------按图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"。

#--------------------------按图2转换时间 # asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。 # 如果没有参数,将会将time.localtime()作为参数传入。 print(time.asctime())#Sun Sep 11 00:43:43 2016 # ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为 # None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。 print(time.ctime()) # Sun Sep 11 00:46:38 2016 print(time.ctime(time.time())) # Sun Sep 11 00:46:38 2016
1 #--------------------------其他用法 2 # sleep(secs) 3 # 线程推迟指定的时间运行,单位为秒。
1 #时间加减 2 import datetime 3 4 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925 5 #print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19 6 # print(datetime.datetime.now() ) 7 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天 8 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天 9 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时 10 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 11 12 13 # 14 # c_time = datetime.datetime.now() 15 # print(c_time.replace(minute=3,hour=2)) #时间替换 16 17 datetime模块
综合练习与扩展
1、匹配标签
import re ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>") #还可以在分组中利用?<name>的形式给分组起名字 #获取的匹配结果可以直接用group('名字')拿到对应的值 print(ret.group('tag_name')) #结果 :h1 print(ret.group()) #结果 :<h1>hello</h1> ret = re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>") #如果不给组起名字,也可以用\序号来找到对应的组,表示要找的内容和前面的组内容一致 #获取的匹配结果可以直接用group(序号)拿到对应的值 print(ret.group(1)) print(ret.group()) #结果 :<h1>hello</h1>
2、匹配整数
import re ret=re.findall(r"\d+","1-2*(60+(-40.35/5)-(-4*3))") print(ret) #['1', '2', '60', '40', '35', '5', '4', '3'] ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))") print(ret) #['1', '-2', '60', '', '5', '-4', '3'] ret.remove("") print(ret) #['1', '-2', '60', '5', '-4', '3']
3、数字匹配
1、 匹配一段文本中的每行的邮箱 http://blog.csdn.net/make164492212/article/details/51656638 2、 匹配一段文本中的每行的时间字符串,比如:‘1990-07-12’; 分别取出1年的12个月(^(0?[1-9]|1[0-2])$)、 一个月的31天:^((0?[1-9])|((1|2)[0-9])|30|31)$ 3、 匹配qq号。(腾讯QQ号从10000开始) [1,9][0,9]{4,} 4、 匹配一个浮点数。 ^(-?\d+)(\.\d+)?$ 或者 -?\d+\.?\d* 5、 匹配汉字。 ^[\u4e00-\u9fa5]{0,}$ 6、 匹配出所有整数
4、爬虫练习
import requests import re import json def getPage(url): response=requests.get(url) return response.text def parsePage(s): com=re.compile('<div class="item">.*?<div class="pic">.*?<em .*?>(?P<id>\d+).*?<span class="title">(?P<title>.*?)</span>' '.*?<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?<span>(?P<comment_num>.*?)评价</span>',re.S) ret=com.finditer(s) for i in ret: yield { "id":i.group("id"), "title":i.group("title"), "rating_num":i.group("rating_num"), "comment_num":i.group("comment_num"), } def main(num): url='https://movie.douban.com/top250?start=%s&filter='%num response_html=getPage(url) ret=parsePage(response_html) print(ret) f=open("move_info7","a",encoding="utf8") for obj in ret: print(obj) data=json.dumps(obj,ensure_ascii=False) f.write(data+"\n") if __name__ == '__main__': count=0 for i in range(10): main(count) count+=25
import re import json from urllib.request import urlopen def getPage(url): response = urlopen(url) return response.read().decode('utf-8') def parsePage(s): com = re.compile( '<div class="item">.*?<div class="pic">.*?<em .*?>(?P<id>\d+).*?<span class="title">(?P<title>.*?)</span>' '.*?<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?<span>(?P<comment_num>.*?)评价</span>', re.S) ret = com.finditer(s) for i in ret: yield { "id": i.group("id"), "title": i.group("title"), "rating_num": i.group("rating_num"), "comment_num": i.group("comment_num"), } def main(num): url = 'https://movie.douban.com/top250?start=%s&filter=' % num response_html = getPage(url) ret = parsePage(response_html) print(ret) f = open("move_info7", "a", encoding="utf8") for obj in ret: print(obj) data = str(obj) f.write(data + "\n") count = 0 for i in range(10): main(count) count += 25 简化版
flags有很多可选值: re.I(IGNORECASE)忽略大小写,括号内是完整的写法 re.M(MULTILINE)多行模式,改变^和$的行为 re.S(DOTALL)点可以匹配任意字符,包括换行符 re.L(LOCALE)做本地化识别的匹配,表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境,不推荐使用 re.U(UNICODE) 使用\w \W \s \S \d \D使用取决于unicode定义的字符属性。在python3中默认使用该flag re.X(VERBOSE)冗长模式,该模式下pattern字符串可以是多行的,忽略空白字符,并可以添加注释 flags
在线测试工具 http://tool.chinaz.com/regex/
练习题:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 """ 4 该计算器思路: 5 1、递归寻找表达式中只含有 数字和运算符的表达式,并计算结果 6 2、由于整数计算会忽略小数,所有的数字都认为是浮点型操作,以此来保留小数 7 使用技术: 8 1、正则表达式 9 2、递归 10 11 执行流程如下: 12 ******************** 请计算表达式: 1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) ******************** 13 before: ['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] 14 -40.0/5=-8.0 15 after: ['1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] 16 ========== 上一次计算结束 ========== 17 before: ['1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] 18 9-2*5/3+7/3*99/4*2998+10*568/14=173545.880953 19 after: ['1-2*((60-30+-8.0*173545.880953)-(-4*3)/(16-3*2))'] 20 ========== 上一次计算结束 ========== 21 before: ['1-2*((60-30+-8.0*173545.880953)-(-4*3)/(16-3*2))'] 22 60-30+-8.0*173545.880953=-1388337.04762 23 after: ['1-2*(-1388337.04762-(-4*3)/(16-3*2))'] 24 ========== 上一次计算结束 ========== 25 before: ['1-2*(-1388337.04762-(-4*3)/(16-3*2))'] 26 -4*3=-12.0 27 after: ['1-2*(-1388337.04762--12.0/(16-3*2))'] 28 ========== 上一次计算结束 ========== 29 before: ['1-2*(-1388337.04762--12.0/(16-3*2))'] 30 16-3*2=10.0 31 after: ['1-2*(-1388337.04762--12.0/10.0)'] 32 ========== 上一次计算结束 ========== 33 before: ['1-2*(-1388337.04762--12.0/10.0)'] 34 -1388337.04762--12.0/10.0=-1388335.84762 35 after: ['1-2*-1388335.84762'] 36 ========== 上一次计算结束 ========== 37 我的计算结果: 2776672.69524 38 """ 39 40 41 import re 42 43 44 def compute_mul_div(arg): 45 """ 操作乘除 46 :param expression:表达式 47 :return:计算结果 48 """ 49 50 val = arg[0] 51 mch = re.search('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val) 52 if not mch: 53 return 54 content = re.search('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val).group() 55 56 if len(content.split('*'))>1: 57 n1, n2 = content.split('*') 58 value = float(n1) * float(n2) 59 else: 60 n1, n2 = content.split('/') 61 value = float(n1) / float(n2) 62 63 before, after = re.split('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val, 1) 64 new_str = "%s%s%s" % (before,value,after) 65 arg[0] = new_str 66 compute_mul_div(arg) 67 68 69 def compute_add_sub(arg): 70 """ 操作加减 71 :param expression:表达式 72 :return:计算结果 73 """ 74 while True: 75 if arg[0].__contains__('+-') or arg[0].__contains__("++") or arg[0].__contains__('-+') or arg[0].__contains__("--"): 76 arg[0] = arg[0].replace('+-','-') 77 arg[0] = arg[0].replace('++','+') 78 arg[0] = arg[0].replace('-+','-') 79 arg[0] = arg[0].replace('--','+') 80 else: 81 break 82 83 if arg[0].startswith('-'): 84 arg[1] += 1 85 arg[0] = arg[0].replace('-','&') 86 arg[0] = arg[0].replace('+','-') 87 arg[0] = arg[0].replace('&','+') 88 arg[0] = arg[0][1:] 89 val = arg[0] 90 mch = re.search('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val) 91 if not mch: 92 return 93 content = re.search('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val).group() 94 if len(content.split('+'))>1: 95 n1, n2 = content.split('+') 96 value = float(n1) + float(n2) 97 else: 98 n1, n2 = content.split('-') 99 value = float(n1) - float(n2) 100 101 before, after = re.split('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val, 1) 102 new_str = "%s%s%s" % (before,value,after) 103 arg[0] = new_str 104 compute_add_sub(arg) 105 106 107 def compute(expression): 108 """ 操作加减乘除 109 :param expression:表达式 110 :return:计算结果 111 """ 112 inp = [expression,0] 113 114 # 处理表达式中的乘除 115 compute_mul_div(inp) 116 117 # 处理 118 compute_add_sub(inp) 119 if divmod(inp[1],2)[1] == 1: 120 result = float(inp[0]) 121 result = result * -1 122 else: 123 result = float(inp[0]) 124 return result 125 126 127 def exec_bracket(expression): 128 """ 递归处理括号,并计算 129 :param expression: 表达式 130 :return:最终计算结果 131 """ 132 # 如果表达式中已经没有括号,则直接调用负责计算的函数,将表达式结果返回,如:2*1-82+444 133 if not re.search('\(([\+\-\*\/]*\d+\.*\d*){2,}\)', expression): 134 final = compute(expression) 135 return final 136 # 获取 第一个 只含有 数字/小数 和 操作符 的括号 137 # 如: 138 # ['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] 139 # 找出:(-40.0/5) 140 content = re.search('\(([\+\-\*\/]*\d+\.*\d*){2,}\)', expression).group() 141 142 # 分割表达式,即: 143 # 将['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] 144 # 分割更三部分:['1-2*((60-30+( (-40.0/5) *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] 145 before, nothing, after = re.split('\(([\+\-\*\/]*\d+\.*\d*){2,}\)', expression, 1) 146 147 print 'before:',expression 148 content = content[1:len(content)-1] 149 150 # 计算,提取的表示 (-40.0/5),并活的结果,即:-40.0/5=-8.0 151 ret = compute(content) 152 153 print '%s=%s' %( content, ret) 154 155 # 将执行结果拼接,['1-2*((60-30+( -8.0 *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] 156 expression = "%s%s%s" %(before, ret, after) 157 print 'after:',expression 158 print "="*10,'上一次计算结束',"="*10 159 160 # 循环继续下次括号处理操作,本次携带者的是已被处理后的表达式,即: 161 # ['1-2*((60-30+ -8.0 *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] 162 163 # 如此周而复始的操作,直到表达式中不再含有括号 164 return exec_bracket(expression) 165 166 167 168 # 使用 __name__ 的目的: 169 # 只有执行 python index.py 时,以下代码才执行 170 # 如果其他人导入该模块,以下代码不执行 171 if __name__ == "__main__": 172 #print '*'*20,"请计算表达式:", "1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )" ,'*'*20 173 #inpp = '1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) ' 174 inpp = "1-2*-30/-12*(-20+200*-3/-200*-300-100)" 175 #inpp = "1-5*980.0" 176 inpp = re.sub('\s*','',inpp) 177 # 表达式保存在列表中 178 result = exec_bracket(inpp) 179 print result
1、通过HTTP请求和XML实现获取电视节目
API:http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx
2、通过HTTP请求和JSON实现获取天气状况
API:http://wthrcdn.etouch.cn/weather_mini?city=北京
你现在所遭遇的每一个不幸,都来自一个不肯努力的曾经!
Victor


浙公网安备 33010602011771号