Python学习--模块

Posted on 2016-11-21 19:16  wy2333  阅读(134)  评论(0)    收藏  举报

模块

1.1

模块可以是一个Python文件,也可以为一个包含多个Python文件的文件夹,模块主要分为3大类:

自定义模块、第三方模块、内置模块

内置模块:Python自带,在Python文件的Lib目录下,在任何Python文件中都能够导入

第三方模块:需要安装,安装在Lib文件site-packages目录下,安装后能导入

安装1.通过软件进行安装,setuptools---pip---pip install 库名

     2.下载源码,通过setup.py文件进行安装

自定义模块:根据自己需要所写的Python文件

模块的导入:import 模块名

                 from....import....

                 import....as.....

处于同一目录下的文件能进行导入,能导入的文件路径可以通过sys.path所对应的列表进行查看与添加

1.2 全局变量

Python文件在运行时,可以自动的生成一些全局变量,通过内置函数vars(),进行查看,主要有

1 __doc__        #对文件进行注释,用"""   """表示
2 __file__       #获取当前文件的路径
3 __name__       #获取文件名称,若是正在运行的文件,则__name__="__main__",否则为文件名,用于入口文件判断
4 __package__    #获取被导入模块所在的文件夹,正在运行的文件返回None

1.3 内置模块

1.3.1 sys模块

sys模块用于与Python解释器相关的操作

1 import sys
2 sys.argv             #获取参数列表,第一项为当前文件名
3 sys.path             #获取所有能导入的路径列表,通过append添加路径
4 sys.platform         #获取操作的当前系统
5 sys.stdout.write()   #向屏幕输出内容
6 sys.stdin.write()    #写入内容

1.3.2 os模块

os模块用于与系统相关的操作

 1 os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径
 2 os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd
 3 os.curdir                   返回当前目录: ('.')
 4 os.pardir                   获取当前目录的父目录字符串名:('..')
 5 os.makedirs('dir1/dir2')    可生成多层递归目录
 6 os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
 7 os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname
 8 os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
 9 os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
10 os.remove()                 删除一个文件
11 os.rename("oldname","new")  重命名文件/目录
12 os.stat('path/filename')    获取文件/目录信息
13 os.sep                      操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
14 os.linesep                  当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
15 os.pathsep                  用于分割文件路径的字符串
16 os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'
17 os.system("bash command")   运行shell命令,直接显示
18 os.environ                  获取系统环境变量
19 os.path.abspath(path)       返回path规范化的绝对路径
20 os.path.split(path)         将path分割成目录和文件名二元组返回
21 os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素
22 os.path.basename(path)      返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
23 os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False
24 os.path.isabs(path)         如果path是绝对路径,返回True
25 os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False
26 os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False
27 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
28 os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间
29 os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间

1.3.3 hashlib模块

hashlib模块用于加密,其中包括多种算法,如主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

1 import hashlib
2 hash = hashlib.md5()
3 ret = hash.update("123")
4 print hash.hexdigest()
202cb962ac59075b964b07152d234b70
 1 hash = hashlib.sha1()
 2 hash.update(bytes('admin', encoding='utf-8'))
 3 print(hash.hexdigest())
 4  
 5 # ######## sha256 ########
 6  
 7 hash = hashlib.sha256()
 8 hash.update(bytes('admin', encoding='utf-8'))
 9 print(hash.hexdigest())
10  
11  
12 # ######## sha384 ########
13  
14 hash = hashlib.sha384()
15 hash.update(bytes('admin', encoding='utf-8'))
16 print(hash.hexdigest())
17  
18 # ######## sha512 ########
19  
20 hash = hashlib.sha512()
21 hash.update(bytes('admin', encoding='utf-8'))
22 print(hash.hexdigest())

 

md5的加密算法不能反解,但是可以通过撞库进行破解,因此可以增加自定义的字符串进行加严

1 import hashlib
2 hash = hashlib.md5("retcdrhj")
3 ret = hash.update("123")
4 print hash.hexdigest()
5 
6 1c5adecb6ecb47fa778e68cad9001b6c

1.3.4 time 模块与datetime模块

time模块

1 time.sleep()       #使程序暂停   time.sleep(5)--暂停5s
2 time.ctime()       #返回当前时间,年-月-日 时-分-秒 字符串形式    Mon Nov 21 18:43:23 2016
3 time.time()        #返回时间戳,从1970.01.01至今的秒数          1479725003.67
4 time.gmtime()      #返回struct_time字典,以0时区为标准          time.struct_time(tm_year=2016, tm_mon=11, tm_mday=21, tm_hour=10, tm_min=43, tm_sec=                                                                 23, tm_wday=0, tm_yday=326, tm_isdst=0)
5 time.localtime()   #返回struct_time字典,以系统时间标准          time.struct_time(tm_year=2016, tm_mon=11, tm_mday=21, tm_hour=18, tm_min=43, tm_sec                                                                   =23, tm_wday=0, tm_yday=326, tm_isdst=0)
6 time.strftime()    #将struct_time 结构转化为字符串形式的时间
7 time.strptime()    #将字符串 转化为struct_time

 

datetime 模块

1 import datetime
2 datetime.date.today()               #获取当前日期
3 datetime.datetime.fromtimestamp()   #将时间戳转化为日期
4 datetime.timedelta()                #days= /hours= /weeks= /seconds= 

1.3.5 pickel 模块与json模块

用于序列化   pickel---将所有的对象转化为字符串(只在Python才有)    json----将字典转化字符串,序列化(任何语言中都存在)

json 用于多平台,多语言之间进行交互,处理字典、列表与类字典、列表字符串之间的转化

当本地与服务器间进行连接时,通过http协议,本地发送请求request(get/post等8种方式),服务器返回response(为一个字符串,可能是HTML、json、xml形式)

json模块就是用来处理json类型的字符串的

 1 import json

2 json.loads()  ----- 将字符串转化为字典、列表

3 json.dumps()--------将列表、字典转化为字符串

1 json.load()---------直接加文件,将文件中字符串进行转化

2 json.dump()--------直接将字符串写入文件中  

1.3.6 requests模块

requests模块:Python解释器通过此模块模拟浏览器向服务器发送请求,请求request

r = requests.get(网址)

r.encoding("utf-8"),   r.text

1.3.7 xml模块

1.ET类型

通过et.ET()、et.parse()创建

具有getroot(), tree.write()等方法

2.element类型

创建方式:et.element(), 节点.makeelement(), et.subelement("父节点”)------(tag, {})-标签名、属性

方法:tag, attrib, get, set, iter, find, findall 

1 1.解析
2 #以字符串方式进行解析
3 from xml.etree import ElementTree as et
4 ret = open("first.xml","r")   
5 root = et.XML(ret)  --------得到根节点,Element类型
tree = et.EelmentTree(root)---得到ET类型
6 #以文件方式进行解析 7 from xml.etree import ElementTree as et 8 tree = et.parse("first.xml")-----得到ElementTree类型 9 root = tree.getroot()------------得到根节点
  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
节点方法
1 f = open("first.xml", "r+").read()
2 ret = et.XML(f)
3 print ret.tag
4 for node in ret:
5     print node.find("year").text
6     node.find("year").text = str(int(node.find("year").text)+1)
7     node.remove(node.find("rank"))
8 tree = et.ElementTree(ret)
9 tree.write("outer.xml")

1.3.8 configparser模块

configparser模块用于处理一些特殊的文件格式,比如软件的配置文件

 1 # 注释1
 2 ;  注释2
 3  
 4 [section1] # 节点
 5 k1 = v1    #
 6 k2:v2       #
 7  
 8 [section2] # 节点
 9 k1 = v1    #
 1 import configparser
 2 1.获取所有子节点
 3 config = configparser.ConfigParser()
 4 config.read('xxxooo', encoding='utf-8')
 5 ret = config.sections()
 6 print(ret)
 7 2.获取所有子节点的键值对
 8 config = configparser.ConfigParser()
 9 config.read('xxxooo', encoding='utf-8')
10 ret = config.items('section1')
11 print(ret)
12 3.获取指定子节点的键
13 config = configparser.ConfigParser()
14 config.read('xxxooo', encoding='utf-8')
15 ret = config.options('section1')
16 print(ret)
17 4.获取指定节点下指定key的值
18 onfig = configparser.ConfigParser()
19 config.read('xxxooo', encoding='utf-8')  
20 v = config.get('section1', 'k1')
21 # v = config.getint('section1', 'k1')
22 # v = config.getfloat('section1', 'k1')
23 # v = config.getboolean('section1', 'k1')
24  
25 print(v)
26 5.检查、删除、添加节
27 mport configparser
28  
29 config = configparser.ConfigParser()
30 config.read('xxxooo', encoding='utf-8')
31  
32  
33 # 检查
34 has_sec = config.has_section('section1')
35 print(has_sec)
36  
37 # 添加节点
38 config.add_section("SEC_1")
39 config.write(open('xxxooo', 'w'))
40  
41 # 删除节点
42 config.remove_section("SEC_1")
43 config.write(open('xxxooo', 'w'))
44 6.检查、删除、设置指定组内的键值对
45 import configparser
46  
47 config = configparser.ConfigParser()
48 config.read('xxxooo', encoding='utf-8')
49  
50 # 检查
51 has_opt = config.has_option('section1', 'k1')
52 print(has_opt)
53  
54 # 删除
55 config.remove_option('section1', 'k1')
56 config.write(open('xxxooo', 'w'))
57  
58 # 设置
59 config.set('section1', 'k10', "123")
60 config.write(open('xxxooo', 'w'))
方法

1.3.9 shutil模块

用于处理高级文件、文件夹、压缩包的处理

 1 shutil.copyfileobj(fsrc, fdst[, length])
 2 将文件内容拷贝到另一个文件中
 3 import shutil 
 4 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
 5 
 6 shutil.copyfile(src, dst)
 7 拷贝文件
 8 shutil.copyfile('f1.log', 'f2.log')
 9 
10 shutil.copymode(src, dst)
11 仅拷贝权限 内容、组、用户均不变
12 shutil.copymode('f1.log', 'f2.log')
13 
14 shutil.copystat(src, dst)
15 仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
16 shutil.copystat('f1.log', 'f2.log')
17 
18 shutil.copy(src, dst)
19 拷贝文件和权限
20 import shutil 
21 shutil.copy('f1.log', 'f2.log')
22 
23 shutil.copy2(src, dst)
24 拷贝文件和状态信息
25 import shutil 
26 shutil.copy2('f1.log', 'f2.log')
27 shutil.ignore_patterns(*patterns)
28 
29 shutil.copytree(src, dst, symlinks=False, ignore=None)
30 递归的去拷贝文件夹
31 import shutil
32 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil
 1 shutil.rmtree(path[, ignore_errors[, onerror]])
 2 递归的去删除文件
 3 import shutil 
 4 shutil.rmtree('folder1')
 5 
 6 shutil.move(src, dst)
 7 递归的去移动文件,它类似mv命令,其实就是重命名。
 8 import shutil
 9 shutil.move('folder1', 'folder3')
10 
11 shutil.make_archive(base_name, format,...)
12 创建压缩包并返回文件路径,例如:zip、tar
13 创建压缩包并返回文件路径,例如:zip、tar
14 base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
15 如:www                        =>保存至当前路径
16 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
17 format:    压缩包种类,“zip”, “tar”, “bztar”,“gztar”
18 root_dir:    要压缩的文件夹路径(默认当前目录)
19 owner:    用户,默认当前用户
20 group:    组,默认当前组
21 logger:    用于记录日志,通常是logging.Logger对象
22 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
23 import shutil
24 ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
25     
26 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
27 import shutil
28 ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
29 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()
13 复制代码

1.3.10 subprocess 模块

通过Python解释器对shell进行操作

 1 call 
 2 执行命令,返回状态码
 3 ret = subprocess.call(["ls", "-l"], shell=False)
 4 ret = subprocess.call("ls -l", shell=True)
 5 
 6 check_call
 7 执行命令,如果执行状态码是 0 ,则返回0,否则抛异常
 8 subprocess.check_call(["ls", "-l"])
 9 subprocess.check_call("exit 1", shell=True)
10 
11 check_output
12 执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常
13 subprocess.check_output(["echo", "Hello World!"])
14 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)
 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)
Popen方式
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)
communicate-读取方式

 logging 模块

用于处理日志文件,创建日志文件,记录使用时错误信息,线程安全

 1 import logging
 2  
 3 logging.basicConfig(filename='log.log',
 4                     format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',   ------配置文件(文件名、格式、等级)
 5                     datefmt='%Y-%m-%d %H:%M:%S %p',
 6                     level=10)
 7  
 8 logging.debug('debug')
 9 logging.info('info')
10 logging.warning('warning')
11 logging.error('error')
12 logging.critical('critical')
13 logging.log(10,'log')

等级:只有等级达到才会记录

1 CRITICAL = 50
2 FATAL = CRITICAL
3 ERROR = 40
4 WARNING = 30
5 WARN = WARNING
6 INFO = 20
7 DEBUG = 10
8 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
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)
多个文件2

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3