Python开发【第六篇】:模块
模块,用一砣代码实现了某个功能的代码集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操作相关的模块
模块分为三种:
- 自定义模块
- 第三方模块
- 内置模块
自定义模块
1、定义模块
情景一:
情景二:
情景三:
2、导入模块
Python之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法:
1
2
3
4
|
import module from module.xx.xx import xx from 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 sys print 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 sys import os project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_path) |
模块
内置模块是Python自带的功能,在使用内置模块相应的功能时,需要【先导入】再【使用】
一、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
用于提供系统级别的操作:
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脚本工作的目录路径 os.chdir( "dirname" ) 改变当前脚本工作目录;相当于shell下cd os.curdir 返回当前目录: ( '.' ) os.pardir 获取当前目录的父目录字符串名:( '..' ) os.makedirs( 'dir1/dir2' ) 可生成多层递归目录 os.removedirs( 'dirname1' ) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 os.mkdir( 'dirname' ) 生成单级目录;相当于shell中mkdir dirname os.rmdir( 'dirname' ) 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname os.listdir( 'dirname' ) 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 os.remove() 删除一个文件 os.rename( "oldname" , "new" ) 重命名文件 / 目录 os.stat( 'path/filename' ) 获取文件 / 目录信息 os.sep 操作系统特定的路径分隔符,win下为 "\\",Linux下为" / " os.linesep 当前平台使用的行终止符,win下为 "\t\n" ,Linux下为 "\n" os.pathsep 用于分割文件路径的字符串 os.name 字符串指示当前使用平台。win - > 'nt' ; Linux - > 'posix' os.system( "bash command" ) 运行shell命令,直接显示 os.environ 获取系统环境变量 os.path.abspath(path) 返回path规范化的绝对路径 os.path.split(path) 将path分割成目录和文件名二元组返回 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 os.path.exists(path) 如果path存在,返回 True ;如果path不存在,返回 False os.path.isabs(path) 如果path是绝对路径,返回 True os.path.isfile(path) 如果path是一个存在的文件,返回 True 。否则返回 False os.path.isdir(path) 如果path是一个存在的目录,则返回 True 。否则返回 False os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间 |
三、hashlib
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
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()) |
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义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 hmac h = hmac.new(bytes( '898oaFs09f' ,encoding = "utf-8" )) h.update(bytes( 'admin' ,encoding = "utf-8" )) print (h.hexdigest()) |
四、random
1
2
3
4
5
|
import random print (random.random()) print (random.randint( 1 , 2 )) print (random.randrange( 1 , 10 )) |
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
五、re
python中re模块提供了正则表达式相关操作
字符:
. 匹配除换行符以外的任意字符
\w 匹配字母或数字或下划线或汉字
\s 匹配任意的空白符
\d 匹配数字
\b 匹配单词的开始或结束
^ 匹配字符串的开始
$ 匹配字符串的结束
次数:
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次
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 3 r = re.search("a\w+", origin) 4 print(r.group()) # 获取匹配到的所有结果 5 print(r.groups()) # 获取模型中匹配到的分组结果 6 print(r.groupdict()) # 获取模型中匹配到的分组结果 7 8 # 有分组 9 10 r = re.search("a(\w+).*(?P<name>\d)$", origin) 11 print(r.group()) # 获取匹配到的所有结果 12 print(r.groups()) # 获取模型中匹配到的分组结果 13 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_-]+)+
六、序列化
Python中用于序列化的两个模块
- json 用于【字符串】和 【python基本数据类型】 间进行转换
- pickle 用于【python特有的类型】 和 【python基本数据类型】间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
七、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 configparser config = configparser.ConfigParser() config.read( 'xxxooo' , encoding = 'utf-8' ) ret = config.sections() print (ret) |
2、获取指定节点下所有的键值对
1
2
3
4
5
6
|
import configparser config = configparser.ConfigParser() config.read( 'xxxooo' , encoding = 'utf-8' ) ret = config.items( 'section1' ) print (ret) |
3、获取指定节点下所有的建
1
2
3
4
5
6
|
import configparser config = 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 configparser config = 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 configparser config = 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 configparser config = 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' )) |
八、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)
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
由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so 可以利用以上方法进行操作xml文件。
a. 遍历XML文档的所有内容
View Code1 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文档的第二层 27 for child in root: 28 # 第二层节点的标签名称和标签属性 29 print(child.tag, child.attrib) 30 # 遍历XML文档的第三层 31 for i in child: 32 # 第二层节点的标签名称和内容 33 print(i.tag,i.text)b、遍历XML中指定的节点
View Code1 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)c、修改节点内容
由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。
解析字符串方式,修改,保存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)
由于原生保存的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、命名空间
详细介绍,猛击这里
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)
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)
注:更多接口猛击这里
十、logging
用于便捷记录日志且线程安全的模块
1、单文件日志
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import logging logging.basicConfig(filename = 'log.log' , format = '%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s' , datefmt = '%Y-%m-%d %H:%M:%S %p' , level = 10 ) logging.debug( 'debug' ) logging.info( 'info' ) logging.warning( 'warning' ) logging.error( 'error' ) logging.critical( 'critical' ) logging.log( 10 , 'log' ) |
日志等级:
CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0
注:只有【当前写等级】大于【日志等级】时,日志文件才被记录。
日志记录格式:
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_2_1 = logging.FileHandler('l2_1.log', 'a') 3 fmt = logging.Formatter() 4 file_2_1.setFormatter(fmt) 5 6 # 定义日志 7 logger2 = logging.Logger('s2', level=logging.INFO) 8 logger2.addHandler(file_2_1)
如上述创建的两个日志对象
- 当使用【logger1】写日志时,会将相应的内容写入 l1_1.log 和 l1_2.log 文件中
- 当使用【logger2】写日志时,会将相应的内容写入 l2_1.log 文件中
十一、系统命令
可以执行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 shutil shutil.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 shutil shutil.copy( 'f1.log' , 'f2.log' ) |
shutil.copy2(src, dst)
拷贝文件和状态信息
1
2
3
|
import shutil shutil.copy2( 'f1.log' , 'f2.log' ) |
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹
1
2
3
|
import shutil shutil.copytree( 'folder1' , 'folder2' , ignore = shutil.ignore_patterns( '*.pyc' , 'tmp*' )) |
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 shutil shutil.rmtree( 'folder1' ) |
shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。
1
2
3
|
import shutil shutil.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 shutil ret = shutil.make_archive( "wwwwwwwwww" , 'gztar' , root_dir = '/Users/wupeiqi/Downloads/test' ) #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录 import shutil ret = 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,所以先下载安装pycrypto pip3 install pycrypto pip3 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()
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()
十四、time
时间相关的操作,时间有三种表示方式:
- 时间戳 1970年1月1日之后的秒,即:time.time()
- 格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d')
- 结构化时间 元组包含了:年、日、星期等... 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, day datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond datetime.datetime:表示日期时间 datetime.timedelta:表示时间间隔,即两个时间点之间的长度 timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) strftime("%Y-%m-%d") ''' import datetime print 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、通过HTTP请求和XML实现获取电视节目
API:http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx
2、通过HTTP请求和JSON实现获取天气状况
API:http://wthrcdn.etouch.cn/weather_mini?city=北京