在计算机程序的开发过程当中,随着程序代码越写越多,在一个文件里代码就会愈来愈长,愈来愈不容易维护。html
为了编写可维护的代码,咱们把不少函数分组,分别放到不一样的文件里,这样,每一个文件包含的代码就相对较少,不少编程语言都采用这种组织代码的方式。在Python中,一个.py文件就称之为一个模块(Module)。node
使用模块有什么好处?python
最大的好处是大大提升了代码的可维护性。linux
其次,编写代码没必要从零开始。当一个模块编写完毕,就能够被其余地方引用。咱们在编写程序的时候,也常常引用其余模块,包括Python内置的模块和来自第三方的模块。程序员
因此,模块一共三种:web
另外,使用模块还能够避免函数名和变量名冲突。相同名字的函数和变量彻底能够分别存在不一样的模块中,所以,咱们本身在编写模块时,没必要考虑名字会与其余模块冲突。可是也要注意,尽可能不要与内置函数名字冲突。正则表达式
1 import 语句算法
import module1[, module2[,... moduleN]
当咱们使用import语句的时候,Python解释器是怎样找到对应的文件的呢?答案就是解释器有本身的搜索路径,存在sys.path里。shell
['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
所以若像我同样在当前目录下存在与要引入模块同名的文件,就会把要引入的模块屏蔽掉。django
2 from…import 语句
from modname import name1[, name2[, ... nameN]]
这个声明不会把整个modulename模块导入到当前的命名空间中,只会将它里面的name1或name2单个引入到执行这个声明的模块的全局符号表。
3 From…import* 语句
from modname import *
这提供了一个简单的方法来导入一个模块中的全部项目。然而这种声明不应被过多地使用。大多数状况, Python程序员不使用这种方法,由于引入的其它来源的命名,极可能覆盖了已有的定义。
4 运行本质
#1 import test #2 from test import add
不管1仍是2,首先经过sys.path找到test.py,而后执行test脚本(所有执行),区别是1会将test这个变量名加载到名字空间,而2只会将add这个变量名加载进来。
若是不一样的人编写的模块名相同怎么办?为了不模块名冲突,Python又引入了按目录来组织模块的方法,称为包(Package)。
举个例子,一个abc.py
的文件就是一个名字叫abc
的模块,一个xyz.py
的文件就是一个名字叫xyz
的模块。
如今,假设咱们的abc
和xyz
这两个模块名字与其余模块冲突了,因而咱们能够经过包来组织模块,避免冲突。方法是选择一个顶层包名:
引入了包之后,只要顶层的包名不与别人冲突,那全部模块都不会与别人冲突。如今,view.py
模块的名字就变成了hello_django.app01.views
,相似的,manage.py
的模块名则是hello_django.manage。
请注意,每个包目录下面都会有一个__init__.py
的文件,这个文件是必须存在的,不然,Python就把这个目录当成普通目录(文件夹),而不是一个包。__init__.py
能够是空文件,也能够有Python代码,由于__init__.py
自己就是一个模块,而它的模块名就是对应包的名字。
调用包就是执行包下的__init__.py文件
1--------------
在nod1里import hello是找不到的,有同窗说能够找到呀,那是由于你的pycharm为你把myapp这一层路径加入到了sys.path里面,因此能够找到,然而程序一旦在命令行运行,则报错。有同窗问那怎么办?简单啊,本身把这个路径加进去不就OK啦:
import sys,os BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) import hello hello.hello1()
2 --------------
if __name__=='__main__': print('ok')
“Make a .py both importable and executable”
若是咱们是直接执行某个.py文件的时候,该文件中那么”__name__ == '__main__'“是True,可是咱们若是从另一个.py文件经过import导入该文件的时候,这时__name__的值就是咱们这个py文件的名字而不是__main__。
这个功能还有一个用处:调试代码的时候,在”if __name__ == '__main__'“中加入一些咱们的调试代码,咱们可让外部模块调用的时候不执行咱们的调试代码,可是若是咱们想排查问题的时候,直接执行该模块文件,调试代码可以正常运行!s
3
##-------------cal.py def add(x,y): return x+y ##-------------main.py import cal #from module import cal def main(): cal.add(1,2) ##--------------bin.py from module import main main.main()
# from module import cal 改为 from . import cal一样能够,这是由于bin.py是咱们的执行脚本, # sys.path里有bin.py的当前环境。即/Users/yuanhao/Desktop/whaterver/project/web这层路径, # 不管import what , 解释器都会按这个路径找。因此当执行到main.py时,import cal会找不到,由于 # sys.path里没有/Users/yuanhao/Desktop/whaterver/project/web/module这个路径,而 # from module/. import cal 时,解释器就能够找到了。
在Python中,一般有这几种方式来表示时间:
import time # 1 time() :返回当前时间的时间戳 time.time() #1473525444.037215 #---------------------------------------------------------- # 2 localtime([secs]) # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。 time.localtime() #time.struct_time(tm_year=2016, tm_mon=9, tm_mday=11, tm_hour=0, # tm_min=38, tm_sec=39, tm_wday=6, tm_yday=255, tm_isdst=0) time.localtime(1473525444.037215) #---------------------------------------------------------- # 3 gmtime([secs]) 和localtime()方法相似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。 #---------------------------------------------------------- # 4 mktime(t) : 将一个struct_time转化为时间戳。 print(time.mktime(time.localtime()))#1473525749.0 #---------------------------------------------------------- # 5 asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。 # 若是没有参数,将会将time.localtime()做为参数传入。 print(time.asctime())#Sun Sep 11 00:43:43 2016 #---------------------------------------------------------- # 6 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 # 7 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 # 8 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"。 # 9 sleep(secs) # 线程推迟指定的时间运行,单位为秒。 # 10 clock() # 这个须要注意,在不一样的系统上含义不一样。在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间戳)。 # 而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次以后的调用是自第一次调用之后到如今的运行 # 时间,即两次时间差。
help(time)
help(time.asctime)
1 import random 2 3 print(random.random())#(0,1)----float 4 5 print(random.randint(1,3)) #[1,3] 6 7 print(random.randrange(1,3)) #[1,3) 8 9 print(random.choice([1,'23',[4,5]]))#23 10 11 print(random.sample([1,'23',[4,5]],2))#[[4, 5], '23'] 12 13 print(random.uniform(1,3))#1.927109612082716 14 15 16 item=[1,3,5,7,9] 17 random.shuffle(item) 18 print(item)
import random def v_code(): code = '' for i in range(5): num=random.randint(0,9) alf=chr(random.randint(65,90)) add=random.choice([num,alf]) code += str(add) return code print(v_code())
os模块是与操做系统交互的一个接口
os.getcwd() 获取当前工做目录,即当前python脚本工做的目录路径 os.chdir("dirname") 改变当前脚本工做目录;至关于shell下cd os.curdir 返回当前目录: ('.') os.pardir 获取当前目录的父目录字符串名:('..') os.makedirs('dirname1/dirname2') 可生成多层递归目录 os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 os.mkdir('dirname') 生成单级目录;至关于shell中mkdir dirname os.rmdir('dirname') 删除单级空目录,若目录不为空则没法删除,报错;至关于shell中rmdir dirname os.listdir('dirname') 列出指定目录下的全部文件和子目录,包括隐藏文件,并以列表方式打印 os.remove() 删除一个文件 os.rename("oldname","newname") 重命名文件/目录 os.stat('path/filename') 获取文件/目录信息 os.sep 输出操做系统特定的路径分隔符,win下为"\\",Linux下为"/" os.linesep 输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n" os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为: os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix' os.system("bash command") 运行shell命令,直接显示 os.environ 获取系统环境变量 os.path.abspath(path) 返回path规范化的绝对路径 os.path.split(path) 将path分割成目录和文件名二元组返回 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 os.path.exists(path) 若是path存在,返回True;若是path不存在,返回False os.path.isabs(path) 若是path是绝对路径,返回True os.path.isfile(path) 若是path是一个存在的文件,返回True。不然返回False os.path.isdir(path) 若是path是一个存在的目录,则返回True。不然返回False os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径以前的参数将被忽略 os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
1 sys.argv 命令行参数List,第一个元素是程序自己路径 2 sys.exit(n) 退出程序,正常退出时exit(0) 3 sys.version 获取Python解释程序的版本信息 4 sys.maxint 最大的Int值 5 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 6 sys.platform 返回操做系统平台名称
进度条:
import sys,time for i in range(10): sys.stdout.write('#') time.sleep(1) sys.stdout.flush()
以前咱们学习过用eval内置方法能够将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval就无论用了,因此eval的重点仍是一般用来执行一个字符串表达式,并返回表达式的值。
1 import json 2 x="[null,true,false,1]" 3 print(eval(x)) 4 print(json.loads(x))
咱们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其余语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
序列化以后,就能够把序列化后的内容写入磁盘,或者经过网络传输到别的机器上。
反过来,把变量内容从序列化的对象从新读到内存里称之为反序列化,即unpickling。
若是咱们要在不一样的编程语言之间传递对象,就必须把对象序列化为标准格式,好比XML,但更好的方法是序列化为JSON,由于JSON表示出来就是一个字符串,能够被全部语言读取,也能够方便地存储到磁盘或者经过网络传输。JSON不只是标准格式,而且比XML更快,并且能够直接在Web页面中读取,很是方便。
JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应以下:
1 #----------------------------序列化 2 import json 3 4 dic={'name':'alvin','age':23,'sex':'male'} 5 print(type(dic))#<class 'dict'> 6 7 j=json.dumps(dic) 8 print(type(j))#<class 'str'> 9 10 11 f=open('序列化对象','w') 12 f.write(j) #-------------------等价于json.dump(dic,f) 13 f.close() 14 #-----------------------------反序列化<br> 15 import json 16 f=open('序列化对象') 17 data=json.loads(f.read())# 等价于data=json.load(f)
import json #dct="{'1':111}"#json 不认单引号 #dct=str({"1":111})#报错,由于生成的数据仍是单引号:{'one': 1} dct='{"1":"111"}' print(json.loads(dct)) #conclusion: # 不管数据是怎样建立的,只要知足json格式,就能够json.loads出来,不必定非要dumps的数据才能loads
##----------------------------序列化 import pickle dic={'name':'alvin','age':23,'sex':'male'} print(type(dic))#<class 'dict'> j=pickle.dumps(dic) print(type(j))#<class 'bytes'> f=open('序列化对象_pickle','wb')#注意是w是写入str,wb是写入bytes,j是'bytes' f.write(j) #-------------------等价于pickle.dump(dic,f) f.close() #-------------------------反序列化 import pickle f=open('序列化对象_pickle','rb') data=pickle.loads(f.read())# 等价于data=pickle.load(f) print(data['age'])
Pickle的问题和全部其余编程语言特有的序列化问题同样,就是它只能用于Python,而且可能不一样版本的Python彼此都不兼容,所以,只能用Pickle保存那些不重要的数据,不能成功地反序列化也不要紧。
shelve模块比pickle模块简单,只有一个open函数,返回相似字典的对象,可读可写;key必须为字符串,而值能够是python所支持的数据类型
1 import shelve 2 3 f = shelve.open(r'shelve.txt') 4 5 # f['stu1_info']={'name':'alex','age':'18'} 6 # f['stu2_info']={'name':'alvin','age':'20'} 7 # f['school_info']={'website':'oldboyedu.com','city':'beijing'} 8 # 9 # 10 # f.close() 11 12 print(f.get('stu_info')['age'])
xml是实现不一样语言或程序之间进行数据交换的协议,跟json差很少,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,你们只能选择用xml呀,至今不少传统公司如金融行业的不少系统的接口还主要是xml。
xml的格式以下,就是经过<>节点来区别数据结构的:
<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data>
xml协议在各个语言里的都 是支持的,在python中能够用如下模块操做xml:
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() print(root.tag) #遍历xml文档 for child in root: print(child.tag, child.attrib) for i in child: print(i.tag,i.text) #只遍历year 节点 for node in root.iter('year'): print(node.tag,node.text) #--------------------------------------- import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() #修改 for node in root.iter('year'): new_year = int(node.text) + 1 node.text = str(new_year) node.set("updated","yes") tree.write("xmltest.xml") #删除node for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('output.xml')
本身建立xml文档:
import xml.etree.ElementTree as ET new_xml = ET.Element("namelist") name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) age = ET.SubElement(name,"age",attrib={"checked":"no"}) sex = ET.SubElement(name,"sex") sex.text = '33' name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) age = ET.SubElement(name2,"age") age.text = '19' et = ET.ElementTree(new_xml) #生成文档对象 et.write("test.xml", encoding="utf-8",xml_declaration=True) ET.dump(new_xml) #打印生成的格式
来看一个好多软件的常见文档格式以下:
1 [DEFAULT] 2 ServerAliveInterval = 45 3 Compression = yes 4 CompressionLevel = 9 5 ForwardX11 = yes 6 7 [bitbucket.org] 8 User = hg 9 10 [topsecret.server.com] 11 Port = 50022 12 ForwardX11 = no
若是想用python生成一个这样的文档怎么作呢?
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'<br> 15 with open('example.ini', 'w') as configfile: 16 config.write(configfile)
import configparser config = configparser.ConfigParser() #---------------------------------------------查 print(config.sections()) #[] config.read('example.ini') print(config.sections()) #['bitbucket.org', 'topsecret.server.com'] print('bytebong.com' in config)# False print(config['bitbucket.org']['User']) # hg print(config['DEFAULT']['Compression']) #yes print(config['topsecret.server.com']['ForwardX11']) #no for key in config['bitbucket.org']: print(key) # user # serveraliveinterval # compression # compressionlevel # forwardx11 print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11'] print(config.items('bitbucket.org')) #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')] print(config.get('bitbucket.org','compression'))#yes #---------------------------------------------删,改,增(config.write(open('i.cfg', "w"))) config.add_section('yuan') config.remove_section('topsecret.server.com') config.remove_option('bitbucket.org','user') config.set('bitbucket.org','k1','11111') config.write(open('i.cfg', "w"))
用于加密相关的操做,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
1 import hashlib 2 3 m=hashlib.md5()# m=hashlib.sha256() 4 5 m.update('hello'.encode('utf8')) 6 print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592 7 8 m.update('alvin'.encode('utf8')) 9 10 print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af 11 12 m2=hashlib.md5() 13 m2.update('helloalvin'.encode('utf8')) 14 print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af
以上加密算法虽然依然很是厉害,但时候存在缺陷,即:经过撞库能够反解。因此,有必要对加密算法中添加自定义key再来作加密。
1 import hashlib 2 3 # ######## 256 ######## 4 5 hash = hashlib.sha256('898oaFs09f'.encode('utf8')) 6 hash.update('alvin'.encode('utf8')) 7 print (hash.hexdigest())#e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7
python 还有一个 hmac 模块,它内部对咱们建立 key 和 内容 再进行处理而后再加密:
1 import hmac 2 h = hmac.new('alvin'.encode('utf8')) 3 h.update('hello'.encode('utf8')) 4 print (h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940
当咱们须要调用系统的命令的时候,最早考虑的os模块。用os.system()和os.popen()来进行操做。可是这两个命令过于简单,不能完成一些复杂的操做,如给运行的命令提供输入或者读取命令的输出,判断该命令的运行状态,管理多个命令的并行等等。这时subprocess中的Popen命令就能有效的完成咱们须要的操做。
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
This module intends to replace several other, older modules and functions, such as: os.system、os.spawn*、os.popen*、popen2.*、commands.*
这个模块一个类:Popen。
1 #Popen它的构造函数以下: 2 3 subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None,stderr=None, preexec_fn=None, close_fds=False, shell=False,<br> cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
# 参数args能够是字符串或者序列类型(如:list,元组),用于指定进程的可执行文件及其参数。 # 若是是序列类型,第一个元素一般是可执行文件的路径。咱们也能够显式的使用executeable参 # 数来指定可执行文件的路径。在windows操做系统上,Popen经过调用CreateProcess()来创 # 建子进程,CreateProcess接收一个字符串参数,若是args是序列类型,系统将会经过 # list2cmdline()函数将序列类型转换为字符串。 # # # 参数bufsize:指定缓冲。我到如今还不清楚这个参数的具体含义,望各个大牛指点。 # # 参数executable用于指定可执行程序。通常状况下咱们经过args参数来设置所要运行的程序。如 # 果将参数shell设为True,executable将指定程序使用的shell。在windows平台下,默认的 # shell由COMSPEC环境变量来指定。 # # 参数stdin, stdout, stderr分别表示程序的标准输入、输出、错误句柄。他们能够是PIPE, # 文件描述符或文件对象,也能够设置为None,表示从父进程继承。 # # 参数preexec_fn只在Unix平台下有效,用于指定一个可执行对象(callable object),它将 # 在子进程运行以前被调用。 # # 参数Close_sfs:在windows平台下,若是close_fds被设置为True,则新建立的子进程将不会 # 继承父进程的输入、输出、错误管道。咱们不能将close_fds设置为True同时重定向子进程的标准 # 输入、输出与错误(stdin, stdout, stderr)。 # # 若是参数shell设为true,程序将经过shell来执行。 # # 参数cwd用于设置子进程的当前目录。 # # 参数env是字典类型,用于指定子进程的环境变量。若是env = None,子进程的环境变量将从父 # 进程中继承。 # # 参数Universal_newlines:不一样操做系统下,文本的换行符是不同的。如:windows下 # 用’/r/n’表示换,而Linux下用’/n’。若是将此参数设置为True,Python统一把这些换行符当 # 做’/n’来处理。 # # 参数startupinfo与createionflags只在windows下用效,它们将被传递给底层的 # CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等。
1 import subprocess 2 3 a=subprocess.Popen('ls')# 建立一个新的进程,与主进程不一样步 4 5 print('>>>>>>>',a)#a是Popen的一个实例对象 6 7 ''' 8 >>>>>>> <subprocess.Popen object at 0x10185f860> 9 __init__.py 10 __pycache__ 11 log.py 12 main.py 13 14 ''' 15 16 # subprocess.Popen('ls -l',shell=True) 17 18 # subprocess.Popen(['ls','-l'])
在建立Popen对象时,subprocess.PIPE能够初始化stdin, stdout或stderr参数。表示与子进程通讯的标准流。
1 import subprocess 2 3 # subprocess.Popen('ls') 4 p=subprocess.Popen('ls',stdout=subprocess.PIPE)#结果跑哪去啦? 5 6 print(p.stdout.read())#这这呢:b'__pycache__\nhello.py\nok.py\nweb\n'
这是由于subprocess建立了子进程,结果本在子进程中,if 想要执行结果转到主进程中,就得须要一个管道,即 : stdout=subprocess.PIPE
建立Popen对象时,用于初始化stderr参数,表示将错误经过标准输出流输出。
Popen.poll() 用于检查子进程是否已经结束。设置并返回returncode属性。 Popen.wait() 等待子进程结束。设置并返回returncode属性。 Popen.communicate(input=None) 与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。 Communicate()返回一个元组:(stdoutdata, stderrdata)。注意:若是但愿经过进程的stdin向其发送数据,在建立Popen对象的时候,参数stdin必须被设置为PIPE。一样,如 果但愿从stdout和stderr获取数据,必须将stdout和stderr设置为PIPE。 Popen.send_signal(signal) 向子进程发送信号。 Popen.terminate() 中止(stop)子进程。在windows平台下,该方法将调用Windows API TerminateProcess()来结束子进程。 Popen.kill() 杀死子进程。 Popen.stdin 若是在建立Popen对象是,参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象用于策子进程发送指令。不然返回None。 Popen.stdout 若是在建立Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。不然返回 None。 Popen.stderr 若是在建立Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。不然返回 None。 Popen.pid 获取子进程的进程ID。 Popen.returncode 获取进程的返回值。若是进程尚未结束,返回None。
1 supprocess模块提供了一些函数,方便咱们用于建立进程来实现一些简单的功能。 2 3 subprocess.call(*popenargs, **kwargs) 4 运行命令。该函数将一直等待到子进程运行结束,并返回进程的returncode。若是子进程不须要进行交 互,就可使用该函数来建立。 5 6 subprocess.check_call(*popenargs, **kwargs) 7 与subprocess.call(*popenargs, **kwargs)功能同样,只是若是子进程返回的returncode不为0的话,将触发CalledProcessError异常。在异常对象中,包 括进程的returncode信息。 8 9 check_output(*popenargs, **kwargs) 10 与call()方法相似,以byte string的方式返回子进程的输出,若是子进程的返回值不是0,它抛出CalledProcessError异常,这个异常中的returncode包含返回码,output属性包含已有的输出。 11 12 getstatusoutput(cmd)/getoutput(cmd) 13 这两个函数仅仅在Unix下可用,它们在shell中执行指定的命令cmd,前者返回(status, output),后者返回output。其中,这里的output包括子进程的stdout和stderr。
import subprocess #1 # subprocess.call('ls',shell=True) ''' hello.py ok.py web ''' # data=subprocess.call('ls',shell=True) # print(data) ''' hello.py ok.py web 0 ''' #2 # subprocess.check_call('ls',shell=True) ''' hello.py ok.py web ''' # data=subprocess.check_call('ls',shell=True) # print(data) ''' hello.py ok.py web 0 ''' # 两个函数区别:只是若是子进程返回的returncode不为0的话,将触发CalledProcessError异常 #3 # subprocess.check_output('ls')#无结果 # data=subprocess.check_output('ls') # print(data) #b'hello.py\nok.py\nweb\n'
终端输入的命令分为两种:
须要交互的命令示例
待续
一 (简单应用)
import logging logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
输出:
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
可见,默认状况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET),默认的日志格式为日志级别:Logger名称:用户输出消息。
二 灵活配置日志级别,日志格式,输出位置
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='/tmp/test.log', filemode='w') logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
查看输出:
cat /tmp/test.log
Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message
Mon, 05 May 2014 16:29:53 test_logging.py[line:10] INFO info message
Mon, 05 May 2014 16:29:53 test_logging.py[line:11] WARNING warning message
Mon, 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message
Mon, 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message
可见在logging.basicConfig()函数中可经过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名建立FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream建立StreamHandler。能够指定输出到sys.stderr,sys.stdout或者文件(f=open('test.log','w')),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger建立以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息
三 logger对象
上述几个例子中咱们了解到了logging.debug()、logging.info()、logging.warning()、logging.error()、logging.critical()(分别用以记录不一样级别的日志信息),logging.basicConfig()(用默认日志格式(Formatter)为日志系统创建一个默认的流处理器(StreamHandler),设置基础配置(如日志级别等)并加到root logger(根Logger)中)这几个logging模块级别的函数,另外还有一个模块级别的函数是logging.getLogger([name])(返回一个logger对象,若是没有指定名字将返回root logger)
先看一个最简单的过程:
import logging logger = logging.getLogger() # 建立一个handler,用于写入日志文件 fh = logging.FileHandler('test.log') # 再建立一个handler,用于输出到控制台 ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) #logger对象能够添加多个fh和ch对象 logger.addHandler(ch) logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')
先简单介绍一下,logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。
(1)
Logger是一个树形层级结构,输出信息以前都要得到一个Logger(若是没有显示的获取则自动建立并使用root Logger,如第一个例子所示)。
logger = logging.getLogger()返回一个默认的Logger也即root Logger,并应用默认的日志级别、Handler和Formatter设置。
固然也能够经过Logger.setLevel(lel)指定最低的日志级别,可用的日志级别有logging.DEBUG、logging.INFO、logging.WARNING、logging.ERROR、logging.CRITICAL。
Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical()输出不一样级别的日志,只有日志等级大于或等于设置的日志级别的日志才会被输出。
logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')
只输出了
2014-05-06 12:54:43,222 - root - WARNING - logger warning message
2014-05-06 12:54:43,223 - root - ERROR - logger error message
2014-05-06 12:54:43,224 - root - CRITICAL - logger critical message
从这个输出能够看出logger = logging.getLogger()返回的Logger名为root。这里没有用logger.setLevel(logging.Debug)显示的为logger设置日志级别,因此使用默认的日志级别WARNIING,故结果只输出了大于等于WARNIING级别的信息。
(2) 若是咱们再建立两个logger对象:
################################################## logger1 = logging.getLogger('mylogger') logger1.setLevel(logging.DEBUG) logger2 = logging.getLogger('mylogger') logger2.setLevel(logging.INFO) logger1.addHandler(fh) logger1.addHandler(ch) logger2.addHandler(fh) logger2.addHandler(ch) logger1.debug('logger1 debug message') logger1.info('logger1 info message') logger1.warning('logger1 warning message') logger1.error('logger1 error message') logger1.critical('logger1 critical message') logger2.debug('logger2 debug message') logger2.info('logger2 info message') logger2.warning('logger2 warning message') logger2.error('logger2 error message') logger2.critical('logger2 critical message')
结果:
这里有两个个问题:
<1>咱们明明经过logger1.setLevel(logging.DEBUG)将logger1的日志级别设置为了DEBUG,为什么显示的时候没有显示出DEBUG级别的日志信息,而是从INFO级别的日志开始显示呢?
原来logger1和logger2对应的是同一个Logger实例,只要logging.getLogger(name)中名称参数name相同则返回的Logger实例就是同一个,且仅有一个,也即name与Logger实例一一对应。在logger2实例中经过logger2.setLevel(logging.INFO)设置mylogger的日志级别为logging.INFO,因此最后logger1的输出听从了后来设置的日志级别。
<2>为何logger一、logger2对应的每一个输出分别显示两次?
这是由于咱们经过logger = logging.getLogger()显示的建立了root Logger,而logger1 = logging.getLogger('mylogger')建立了root Logger的孩子(root.)mylogger,logger2一样。而孩子,孙子,重孙……既会将消息分发给他的handler进行处理也会传递给全部的祖先Logger处理。
ok,那么如今咱们把
# logger.addHandler(fh)
# logger.addHandler(ch) 注释掉,咱们再来看效果:
由于咱们注释了logger对象显示的位置,因此才用了默认方式,即标准输出方式。由于它的父级没有设置文件显示方式,因此在这里只打印了一次。
孩子,孙子,重孙……可逐层继承来自祖先的日志级别、Handler、Filter设置,也能够经过Logger.setLevel(lel)、Logger.addHandler(hdlr)、Logger.removeHandler(hdlr)、Logger.addFilter(filt)、Logger.removeFilter(filt)。设置本身特别的日志级别、Handler、Filter。若不设置则使用继承来的值。
<3>Filter
限制只有知足过滤规则的日志才会输出。
好比咱们定义了filter = logging.Filter('a.b.c'),并将这个Filter添加到了一个Handler上,则使用该Handler的Logger中只有名字带 a.b.c前缀的Logger才能输出其日志。
filter = logging.Filter('mylogger')
logger.addFilter(filter)
这是只对logger这个对象进行筛选
若是想对全部的对象进行筛选,则:
filter = logging.Filter('mylogger')
fh.addFilter(filter)
ch.addFilter(filter)
这样,全部添加fh或者ch的logger对象都会进行筛选。
完整代码1:
import logging logger = logging.getLogger() # 建立一个handler,用于写入日志文件 fh = logging.FileHandler('test.log') # 再建立一个handler,用于输出到控制台 ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # 定义一个filter filter = logging.Filter('mylogger') fh.addFilter(filter) ch.addFilter(filter) # logger.addFilter(filter) logger.addHandler(fh) logger.addHandler(ch) logger.setLevel(logging.DEBUG) logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message') ################################################## logger1 = logging.getLogger('mylogger') logger1.setLevel(logging.DEBUG) logger2 = logging.getLogger('mylogger') logger2.setLevel(logging.INFO) logger1.addHandler(fh) logger1.addHandler(ch) logger2.addHandler(fh) logger2.addHandler(ch) logger1.debug('logger1 debug message') logger1.info('logger1 info message') logger1.warning('logger1 warning message') logger1.error('logger1 error message') logger1.critical('logger1 critical message') logger2.debug('logger2 debug message') logger2.info('logger2 info message') logger2.warning('logger2 warning message') logger2.error('logger2 error message') logger2.critical('logger2 critical message')
完整代码2:
#coding:utf-8 import logging # 建立一个logger logger = logging.getLogger() logger1 = logging.getLogger('mylogger') logger1.setLevel(logging.DEBUG) logger2 = logging.getLogger('mylogger') logger2.setLevel(logging.INFO) logger3 = logging.getLogger('mylogger.child1') logger3.setLevel(logging.WARNING) logger4 = logging.getLogger('mylogger.child1.child2') logger4.setLevel(logging.DEBUG) logger5 = logging.getLogger('mylogger.child1.child2.child3') logger5.setLevel(logging.DEBUG) # 建立一个handler,用于写入日志文件 fh = logging.FileHandler('/tmp/test.log') # 再建立一个handler,用于输出到控制台 ch = logging.StreamHandler() # 定义handler的输出格式formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) #定义一个filter #filter = logging.Filter('mylogger.child1.child2') #fh.addFilter(filter) # 给logger添加handler #logger.addFilter(filter) logger.addHandler(fh) logger.addHandler(ch) #logger1.addFilter(filter) logger1.addHandler(fh) logger1.addHandler(ch) logger2.addHandler(fh) logger2.addHandler(ch) #logger3.addFilter(filter) logger3.addHandler(fh) logger3.addHandler(ch) #logger4.addFilter(filter) logger4.addHandler(fh) logger4.addHandler(ch) logger5.addHandler(fh) logger5.addHandler(ch) # 记录一条日志 logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message') logger1.debug('logger1 debug message') logger1.info('logger1 info message') logger1.warning('logger1 warning message') logger1.error('logger1 error message') logger1.critical('logger1 critical message') logger2.debug('logger2 debug message') logger2.info('logger2 info message') logger2.warning('logger2 warning message') logger2.error('logger2 error message') logger2.critical('logger2 critical message') logger3.debug('logger3 debug message') logger3.info('logger3 info message') logger3.warning('logger3 warning message') logger3.error('logger3 error message') logger3.critical('logger3 critical message') logger4.debug('logger4 debug message') logger4.info('logger4 info message') logger4.warning('logger4 warning message') logger4.error('logger4 error message') logger4.critical('logger4 critical message') logger5.debug('logger5 debug message') logger5.info('logger5 info message') logger5.warning('logger5 warning message') logger5.error('logger5 error message') logger5.critical('logger5 critical message')
应用:
import os import time import logging from config import settings def get_logger(card_num, struct_time): if struct_time.tm_mday < 23: file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon, 22) else: file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon+1, 22) file_handler = logging.FileHandler( os.path.join(settings.USER_DIR_FOLDER, card_num, 'record', file_name), encoding='utf-8' ) fmt = logging.Formatter(fmt="%(asctime)s : %(message)s") file_handler.setFormatter(fmt) logger1 = logging.Logger('user_logger', level=logging.INFO) logger1.addHandler(file_handler) return logger1
就其本质而言,正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并经过 re 模块实现。正则表达式模式被编译成一系列的字节码,而后由用 C 编写的匹配引擎执行。
字符匹配(普通字符,元字符):
1 普通字符:大多数字符和字母都会和自身匹配
>>> re.findall('alvin','yuanaleSxalexwupeiqi')
['alvin']
2 元字符:. ^ $ * + ? { } [ ] | ( ) \
1 import re 2 3 ret=re.findall('a..in','helloalvin') 4 print(ret)#['alvin'] 5 6 7 ret=re.findall('^a...n','alvinhelloawwwn') 8 print(ret)#['alvin'] 9 10 11 ret=re.findall('a...n$','alvinhelloawwwn') 12 print(ret)#['awwwn'] 13 14 15 ret=re.findall('a...n$','alvinhelloawwwn') 16 print(ret)#['awwwn'] 17 18 19 ret=re.findall('abc*','abcccc')#贪婪匹配[0,+oo] 20 print(ret)#['abcccc'] 21 22 ret=re.findall('abc+','abccc')#[1,+oo] 23 print(ret)#['abccc'] 24 25 ret=re.findall('abc?','abccc')#[0,1] 26 print(ret)#['abc'] 27 28 29 ret=re.findall('abc{1,4}','abccc') 30 print(ret)#['abccc'] 贪婪匹配
注意:前面的*,+,?等都是贪婪匹配,也就是尽量匹配,后面加?号使其变成惰性匹配
1 ret=re.findall('abc*?','abcccccc') 2 print(ret)#['ab']
1 #--------------------------------------------字符集[] 2 ret=re.findall('a[bc]d','acd') 3 print(ret)#['acd'] 4 5 ret=re.findall('[a-z]','acd') 6 print(ret)#['a', 'c', 'd'] 7 8 ret=re.findall('[.*+]','a.cd+') 9 print(ret)#['.', '+'] 10 11 #在字符集里有功能的符号: - ^ \ 12 13 ret=re.findall('[1-9]','45dha3') 14 print(ret)#['4', '5', '3'] 15 16 ret=re.findall('[^ab]','45bdha3') 17 print(ret)#['4', '5', 'd', 'h', '3'] 18 19 ret=re.findall('[\d]','45bdha3') 20 print(ret)#['4', '5', '3']
反斜杠后边跟元字符去除特殊功能,好比\.
反斜杠后边跟普通字符实现特殊功能,好比\d
\d 匹配任何十进制数;它至关于类 [0-9]。
\D 匹配任何非数字字符;它至关于类 [^0-9]。
\s 匹配任何空白字符;它至关于类 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它至关于类 [^ \t\n\r\f\v]。
\w 匹配任何字母数字字符;它至关于类 [a-zA-Z0-9_]。
\W 匹配任何非字母数字字符;它至关于类 [^a-zA-Z0-9_]
\b 匹配一个特殊字符边界,好比空格 ,&,#等
1 ret=re.findall('I\b','I am LIST') 2 print(ret)#[] 3 ret=re.findall(r'I\b','I am LIST') 4 print(ret)#['I']
如今咱们聊一聊\,先看下面两个匹配:
1 #-----------------------------eg1: 2 import re 3 ret=re.findall('c\l','abc\le') 4 print(ret)#[] 5 ret=re.findall('c\\l','abc\le') 6 print(ret)#[] 7 ret=re.findall('c\\\\l','abc\le') 8 print(ret)#['c\\l'] 9 ret=re.findall(r'c\\l','abc\le') 10 print(ret)#['c\\l'] 11 12 #-----------------------------eg2: 13 #之因此选择\b是由于\b在ASCII表中是有意义的 14 m = re.findall('\bblow', 'blow') 15 print(m) 16 m = re.findall(r'\bblow', 'blow') 17 print(m)
1 m = re.findall(r'(ad)+', 'add') 2 print(m) 3 4 ret=re.search('(?P<id>\d{2})/(?P<name>\w{3})','23/com') 5 print(ret.group())#23/com 6 print(ret.group('id'))#23
1 ret=re.search('(ab)|\d','rabhdg8sd') 2 print(ret.group())#ab
1 import re 2 #1 3 re.findall('a','alvin yuan') #返回全部知足匹配条件的结果,放在列表里 4 #2 5 re.search('a','alvin yuan').group() #函数会在字符串内查找模式匹配,只到找到第一个匹配而后返回一个包含匹配信息的对象,该对象能够 6 # 经过调用group()方法获得匹配的字符串,若是字符串没有匹配,则返回None。 7 8 #3 9 re.match('a','abc').group() #同search,不过尽在字符串开始处进行匹配 10 11 #4 12 ret=re.split('[ab]','abcd') #先按'a'分割获得''和'bcd',在对''和'bcd'分别按'b'分割 13 print(ret)#['', '', 'cd'] 14 15 #5 16 ret=re.sub('\d','abc','alvin5yuan6',1) 17 print(ret)#alvinabcyuan6 18 ret=re.subn('\d','abc','alvin5yuan6') 19 print(ret)#('alvinabcyuanabc', 2) 20 21 #6 22 obj=re.compile('\d{3}') 23 ret=obj.search('abc123eeee') 24 print(ret.group())#123
1 import re 2 ret=re.finditer('\d','ds3sy4784a') 3 print(ret) #<callable_iterator object at 0x10195f940> 4 5 print(next(ret).group()) 6 print(next(ret).group())
注意:
1 import re 2 3 ret=re.findall('www.(baidu|oldboy).com','www.oldboy.com') 4 print(ret)#['oldboy'] 这是由于findall会优先把匹配结果组里内容返回,若是想要匹配结果,取消权限便可 5 6 ret=re.findall('www.(?:baidu|oldboy).com','www.oldboy.com') 7 print(ret)#['www.oldboy.com']
补充:
import re print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>"))
#匹配出全部的整数 import re #ret=re.findall(r"\d+{0}]","1-2*(60+(-40.35/5)-(-4*3))") ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))") ret.remove("") print(ret)
转自:
python模块(转自Yuan先生)
https://www.cnblogs.com/guojintao/articles/9070485.html
我的公众号:度一聊,不按期推送干货,及有用资源。