模块
2016-05-21 13:08
351 查看
2、sys用于提供对解释器相关的操作
sys.exit(n)退出程序,正常退出时exit(0)
sys.version获取Python解释程序的版本信息
sys.maxint最大的Int值
sys.path返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform返回操作系统平台名称
sys.stdout.write('please:')
val=sys.stdin.readline()[:-1]
3.hashlib#加密
文件中对密码进行加密defmd5(pwd):
hash=hashlib.md5(bytes('xx7',encoding='utf-8'))
hash.update(bytes(pwd,encoding='utf-8'))
returnhash.hexdigest()
deflogin(usr,pwd):#登陆
withopen('db','r')asf:
forlineinf:
u,p=line.strip().split('|')
ifu==usrandp==md5(pwd):#和加密后的密码进行比较
returnTrue
else:
returnFalse
defregister(usr,pwd):#注册
withopen('db','a')asf:
temp=usr+'|'+md5(pwd)#写入加密后的密码
f.write(temp)
usr=input('usr:')
pwd=input('pwd:')
inp=input('1.register2.login')
ifinp=='1':
register(usr,pwd)
elifinp=='2':
r=login(usr,pwd)
ifr:
print('ok')
else:
print('no')
4.json&pickle模块
Python中用于序列化的两个模块json用于【字符串】和【python基本数据类型】间进行转换
pickle用于【python特有的类型】和【python基本数据类型】间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
json.loads()#将字符串转换成python基本数据类型便于读取#注意:json.loads()如果内容是字典,里面必须是双引号
json.dumps#将python的基本数据类型转换成字符串便于写入文件
li="[11,22,33,44,55,66,77,88,99]"
dic='{"5":"inviload"}'#中间必须是双引号
print(json.loads(li))
print(json.loads(dic))
dic1={"5":"inviload"}
print(json.dumps(dic1),type(json.dumps(dic1)))
5.系统自带的全局变量
__doc__文件注释__file__当前文件路径
__package__指定文件所在的包,用.分割当前文件None
__cached__缓存当前文件None
__name__主文件__name__=="__main__",否则,等于模块名
目录的拼接,添加同一级文件夹到path
添加bin目录到path
6.第三方模块的安装
下载安装:1.将pip目录添加在系统环境变量中2.pip3installrequests
源码安装:1.下载,解压,终端进入目录,执行pythonsetup.pyinstall
7.requests模块
r=requests.get('http://www.weather.com.cn/adat/sk/101010500.html')#获取文件内容
r.encoding='utf-8'
result=r.text#提取文件内容
print(result)
importrequests
ret=requests.get('https://github.com/timeline.json')
print(ret.url)
print(ret.text)
#2、有参数实例
importrequests
payload={'key1':'value1','key2':'value2'}
ret=requests.get("http://httpbin.org/get",params=payload)
print(ret.url)
print(ret.text)
GET请求
importrequests
payload={'key1':'value1','key2':'value2'}
ret=requests.post("http://httpbin.org/post",data=payload)
print(ret.text)
#2、发送请求头和数据实例
importrequests
importjson
url='https://api.github.com/some/endpoint'
payload={'some':'data'}
headers={'content-type':'application/json'}
ret=requests.post(url,data=json.dumps(payload),headers=headers)
print(ret.text)
print(ret.cookies)
POST请求
requests.post(url,data=None,json=None,**kwargs)
requests.put(url,data=None,**kwargs)
requests.head(url,**kwargs)
requests.delete(url,**kwargs)
requests.patch(url,data=None,**kwargs)
requests.options(url,**kwargs)
#以上方法均是在此方法的基础上构建
requests.request(method,url,**kwargs)
其他请求
8.Http请求和XML实例
实例:检测QQ账号是否在线importrequests
fromxml.etreeimportElementTreeasET
#使用内置模块urllib发送HTTP请求,或者XML格式内容
"""
f=urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
result=f.read().decode('utf-8')#结果为字符串
"""
#使用第三方模块requests发送HTTP请求,或者XML格式内容
r=requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
result=r.text
#解析XML格式内容
node=ET.XML(result)
#获取内容
ifnode.text=="Y":
print("在线")
else:
print("离线")
实例:查看火车停靠信息
importrequests
fromxml.etreeimportElementTreeasET
#使用内置模块urllib发送HTTP请求,或者XML格式内容
"""
f=urllib.request.urlopen('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
result=f.read().decode('utf-8')
"""
#使用第三方模块requests发送HTTP请求,或者XML格式内容
r=requests.get('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
result=r.text
#解析XML格式内容
root=ET.XML(result)
fornodeinroot.iter('TrainDetailInfo'):#.iter遍历每一个节点
print(node.find('TrainStation').text,node.find('StartTime').text,node.tag,node.attrib)#.text提取值.tag获取标签名.attrib获取标签属性
set添加属性 del删除属性
fromxml.etreeimportElementTree
tree=ElementTree.parse('fist.xml')#一种可以保存的打开方式
root=tree.getroot()#获取根节点
print(root.get)#获取元素属性
fornodeinroot.iter('year'):
new_year=int(node.text)+1
node.text=str(new_year)
node.set('name','alex')#设置属性
delnode.attrib['name']#删除属性
tree.write('fist.xml')#重新写入文件
创建XML文档
#创建根节点
new_xml=ET.Element("namelist")
#创建根节点的子节点
name1=ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age1=ET.SubElement(name1,"age",attrib={"checked":"no"})
sex1=ET.SubElement(name1,"sex")
sex1.text='33'
#创建根节点的子节点
name2=ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age2=ET.SubElement(name2,"age")
age2.text='19'
et=ET.ElementTree(new_xml)#生成文档对象
et.write("test.xml",encoding="utf-8",xml_declaration=True)
创建结果
<nameenrolled="yes">
<agechecked="no"/>
<sex>33</sex>
</name>
<nameenrolled="no">
<age>19</age>
</name>
</namelist>
XML补充
8.1、解析XML利用ElementTree.xml将字符串解析成xml对象
#打开文件,读取XML内容
str_xml=open('xo.xml','r').read()
#将字符串解析成xml特殊对象,root代指xml文件的根节点
root=ET.XML(str_xml)
利用ElementTree.XML将字符串解析成xml对象
利用ElementTree.parse将文件直接解析成xml对象
#直接解析xml文件
tree=ET.parse("xo.xml")
#获取xml文件的根节点
root=tree.getroot()
利用ElementTree.parse将文件直接解析成xml对象
8.2操作XML
XML格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:
"""AnXMLelement.
ThisclassisthereferenceimplementationoftheElementinterface.
Anelement'slengthisitsnumberofsubelements.Thatmeansifyou
wanttocheckifanelementistrulyempty,youshouldcheckBOTH
itslengthANDitstextattribute.
Theelementtag,attributenames,andattributevaluescanbeeither
bytesorstrings.
*tag*istheelementname.*attrib*isanoptionaldictionarycontaining
elementattributes.*extra*areadditionalelementattributesgivenas
keywordarguments.
Exampleform:
<tagattrib>text<child/>...</tag>tail
"""
当前节点的标签名
tag=None
"""Theelement'sname."""
当前节点的属性
attrib=None
"""Dictionaryoftheelement'sattributes."""
当前节点的内容
text=None
"""
Textbeforefirstsubelement.ThisiseitherastringorthevalueNone.
Notethatifthereisnotext,thisattributemaybeeither
Noneortheemptystring,dependingontheparser.
"""
tail=None
"""
Textafterthiselement'sendtag,butbeforethenextsiblingelement's
starttag.ThisiseitherastringorthevalueNone.Notethatifthere
wasnotext,thisattributemaybeeitherNoneoranemptystring,
dependingontheparser.
"""
def__init__(self,tag,attrib={},**extra):
ifnotisinstance(attrib,dict):
raiseTypeError("attribmustbedict,not%s"%(
attrib.__class__.__name__,))
attrib=attrib.copy()
attrib.update(extra)
self.tag=tag
self.attrib=attrib
self._children=[]
def__repr__(self):
return"<%s%rat%#x>"%(self.__class__.__name__,self.tag,id(self))
defmakeelement(self,tag,attrib):
创建一个新节点
"""Createanewelementwiththesametype.
*tag*isastringcontainingtheelementname.
*attrib*isadictionarycontainingtheelementattributes.
Donotcallthismethod,usetheSubElementfactoryfunctioninstead.
"""
returnself.__class__(tag,attrib)
defcopy(self):
"""Returncopyofcurrentelement.
Thiscreatesashallowcopy.Subelementswillbesharedwiththe
originaltree.
"""
elem=self.makeelement(self.tag,self.attrib)
elem.text=self.text
elem.tail=self.tail
elem[:]=self
returnelem
def__len__(self):
returnlen(self._children)
def__bool__(self):
warnings.warn(
"Thebehaviorofthismethodwillchangeinfutureversions."
"Usespecific'len(elem)'or'elemisnotNone'testinstead.",
FutureWarning,stacklevel=2
)
returnlen(self._children)!=0#emulateoldbehaviour,fornow
def__getitem__(self,index):
returnself._children[index]
def__setitem__(self,index,element):
#ifisinstance(index,slice):
#foreltinelement:
#assertiselement(elt)
#else:
#assertiselement(element)
self._children[index]=element
def__delitem__(self,index):
delself._children[index]
defappend(self,subelement):
为当前节点追加一个子节点
"""Add*subelement*totheendofthiselement.
Thenewelementwillappearindocumentorderafterthelastexisting
subelement(ordirectlyafterthetext,ifit'sthefirstsubelement),
butbeforetheendtagforthiselement.
"""
self._assert_is_element(subelement)
self._children.append(subelement)
defextend(self,elements):
为当前节点扩展n个子节点
"""Appendsubelementsfromasequence.
*elements*isasequencewithzeroormoreelements.
"""
forelementinelements:
self._assert_is_element(element)
self._children.extend(elements)
definsert(self,index,subelement):
在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
"""Insert*subelement*atposition*index*."""
self._assert_is_element(subelement)
self._children.insert(index,subelement)
def_assert_is_element(self,e):
#NeedtorefertotheactualPythonimplementation,notthe
#shadowingCimplementation.
ifnotisinstance(e,_Element_Py):
raiseTypeError('expectedanElement,not%s'%type(e).__name__)
defremove(self,subelement):
在当前节点在子节点中删除某个节点
"""Removematchingsubelement.
Unlikethefindmethods,thismethodcompareselementsbasedon
identity,NOTONtagvalueorcontents.Toremovesubelementsby
othermeans,theeasiestwayistousealistcomprehensionto
selectwhatelementstokeep,andthenusesliceassignmenttoupdate
theparentelement.
ValueErrorisraisedifamatchingelementcouldnotbefound.
"""
#assertiselement(element)
self._children.remove(subelement)
defgetchildren(self):
获取所有的子节点(废弃)
"""(Deprecated)Returnallsubelements.
Elementsarereturnedindocumentorder.
"""
warnings.warn(
"Thismethodwillberemovedinfutureversions."
"Use'list(elem)'oriterationovereleminstead.",
DeprecationWarning,stacklevel=2
)
returnself._children
deffind(self,path,namespaces=None):
获取第一个寻找到的子节点
"""Findfirstmatchingelementbytagnameorpath.
*path*isastringhavingeitheranelementtagoranXPath,
*namespaces*isanoptionalmappingfromnamespaceprefixtofullname.
Returnthefirstmatchingelement,orNoneifnoelementwasfound.
"""
returnElementPath.find(self,path,namespaces)
deffindtext(self,path,default=None,namespaces=None):
获取第一个寻找到的子节点的内容
"""Findtextforfirstmatchingelementbytagnameorpath.
*path*isastringhavingeitheranelementtagoranXPath,
*default*isthevaluetoreturniftheelementwasnotfound,
*namespaces*isanoptionalmappingfromnamespaceprefixtofullname.
Returntextcontentoffirstmatchingelement,ordefaultvalueif
nonewasfound.Notethatifanelementisfoundhavingnotext
content,theemptystringisreturned.
"""
returnElementPath.findtext(self,path,default,namespaces)
deffindall(self,path,namespaces=None):
获取所有的子节点
"""Findallmatchingsubelementsbytagnameorpath.
*path*isastringhavingeitheranelementtagoranXPath,
*namespaces*isanoptionalmappingfromnamespaceprefixtofullname.
Returnslistcontainingallmatchingelementsindocumentorder.
"""
returnElementPath.findall(self,path,namespaces)
defiterfind(self,path,namespaces=None):
获取所有指定的节点,并创建一个迭代器(可以被for循环)
"""Findallmatchingsubelementsbytagnameorpath.
*path*isastringhavingeitheranelementtagoranXPath,
*namespaces*isanoptionalmappingfromnamespaceprefixtofullname.
Returnaniterableyieldingallmatchingelementsindocumentorder.
"""
returnElementPath.iterfind(self,path,namespaces)
defclear(self):
清空节点
"""Resetelement.
Thisfunctionremovesallsubelements,clearsallattributes,andsets
thetextandtailattributestoNone.
"""
self.attrib.clear()
self._children=[]
self.text=self.tail=None
defget(self,key,default=None):
获取当前节点的属性值
"""Getelementattribute.
Equivalenttoattrib.get,butsomeimplementationsmayhandlethisa
bitmoreefficiently.*key*iswhatattributetolookfor,and
*default*iswhattoreturniftheattributewasnotfound.
Returnsastringcontainingtheattributevalue,orthedefaultif
attributewasnotfound.
"""
returnself.attrib.get(key,default)
defset(self,key,value):
为当前节点设置属性值
"""Setelementattribute.
Equivalenttoattrib[key]=value,butsomeimplementationsmayhandle
thisabitmoreefficiently.*key*iswhatattributetoset,and
*value*istheattributevaluetosetitto.
"""
self.attrib[key]=value
defkeys(self):
获取当前节点的所有属性的key
"""Getlistofattributenames.
Namesarereturnedinanarbitraryorder,justlikeanordinary
Pythondict.Equivalenttoattrib.keys()
"""
returnself.attrib.keys()
defitems(self):
获取当前节点的所有属性值,每个属性都是一个键值对
"""Getelementattributesasasequence.
Theattributesarereturnedinarbitraryorder.Equivalentto
attrib.items().
Returnalistof(name,value)tuples.
"""
returnself.attrib.items()
defiter(self,tag=None):
在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
"""Createtreeiterator.
Theiteratorloopsovertheelementandallsubelementsindocument
order,returningallelementswithamatchingtag.
Ifthetreestructureismodifiedduringiteration,neworremoved
elementsmayormaynotbeincluded.Togetastableset,usethe
list()functionontheiterator,andloopovertheresultinglist.
*tag*iswhattagstolookfor(defaultistoreturnallelements)
Returnaniteratorcontainingallthematchingelements.
"""
iftag=="*":
tag=None
iftagisNoneorself.tag==tag:
yieldself
foreinself._children:
yieldfrome.iter(tag)
#compatibility
defgetiterator(self,tag=None):
#ChangeforaDeprecationWarningin1.4
warnings.warn(
"Thismethodwillberemovedinfutureversions."
"Use'elem.iter()'or'list(elem.iter())'instead.",
PendingDeprecationWarning,stacklevel=2
)
returnlist(self.iter(tag))
defitertext(self):
在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
"""Createtextiterator.
Theiteratorloopsovertheelementandallsubelementsindocument
order,returningallinnertext.
"""
tag=self.tag
ifnotisinstance(tag,str)andtagisnotNone:
return
ifself.text:
yieldself.text
foreinself:
yieldfrome.itertext()
ife.tail:
yielde.tail
节点功能一览表
由于每个节点都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so可以利用以上方法进行操作xml文件。
a.遍历XML文档的所有内容
############解析方式一############
"""
#打开文件,读取XML内容
str_xml=open('xo.xml','r').read()
#将字符串解析成xml特殊对象,root代指xml文件的根节点
root=ET.XML(str_xml)
"""
############解析方式二############
#直接解析xml文件
tree=ET.parse("xo.xml")
#获取xml文件的根节点
root=tree.getroot()
###操作
#顶层标签
print(root.tag)
#遍历XML文档的第二层
forchildinroot:
#第二层节点的标签名称和标签属性
print(child.tag,child.attrib)
#遍历XML文档的第三层
foriinchild:
#第二层节点的标签名称和内容
print(i.tag,i.text)
b、遍历XML中指定的节点
############解析方式一############
"""
#打开文件,读取XML内容
str_xml=open('xo.xml','r').read()
#将字符串解析成xml特殊对象,root代指xml文件的根节点
root=ET.XML(str_xml)
"""
############解析方式二############
#直接解析xml文件
tree=ET.parse("xo.xml")
#获取xml文件的根节点
root=tree.getroot()
###操作
#顶层标签
print(root.tag)
#遍历XML中所有的year节点
fornodeinroot.iter('year'):
#节点的标签名称和内容
print(node.tag,node.text)
c、修改节点内容
由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。
解析字符串方式,修改,保存
############解析方式一############
#打开文件,读取XML内容
str_xml=open('xo.xml','r').read()
#将字符串解析成xml特殊对象,root代指xml文件的根节点
root=ET.XML(str_xml)
############操作############
#顶层标签
print(root.tag)
#循环所有的year节点
fornodeinroot.iter('year'):
#将year节点中的内容自增一
new_year=int(node.text)+1
node.text=str(new_year)
#设置属性
node.set('name','alex')
node.set('age','18')
#删除属性
delnode.attrib['name']
############保存文件############
tree=ET.ElementTree(root)
tree.write("newnew.xml",encoding='utf-8')
解析字符串方式,修改,保存
解析文件方式,修改,保存
############解析方式二############
#直接解析xml文件
tree=ET.parse("xo.xml")
#获取xml文件的根节点
root=tree.getroot()
############操作############
#顶层标签
print(root.tag)
#循环所有的year节点
fornodeinroot.iter('year'):
#将year节点中的内容自增一
new_year=int(node.text)+1
node.text=str(new_year)
#设置属性
node.set('name','alex')
node.set('age','18')
#删除属性
delnode.attrib['name']
############保存文件############
tree.write("newnew.xml",encoding='utf-8')
解析文件方式,修改,保存
d、删除节点
解析字符串方式,删除,保存
############解析字符串方式打开############
#打开文件,读取XML内容
str_xml=open('xo.xml','r').read()
#将字符串解析成xml特殊对象,root代指xml文件的根节点
root=ET.XML(str_xml)
############操作############
#顶层标签
print(root.tag)
#遍历data下的所有country节点
forcountryinroot.findall('country'):
#获取每一个country节点下rank节点的内容
rank=int(country.find('rank').text)
ifrank>50:
#删除指定country节点
root.remove(country)
############保存文件############
tree=ET.ElementTree(root)
tree.write("newnew.xml",encoding='utf-8')
解析字符串方式打开,删除,保存
解析文件方式,删除,保存
############解析文件方式############
#直接解析xml文件
tree=ET.parse("xo.xml")
#获取xml文件的根节点
root=tree.getroot()
############操作############
#顶层标签
print(root.tag)
#遍历data下的所有country节点
forcountryinroot.findall('country'):
#获取每一个country节点下rank节点的内容
rank=int(country.find('rank').text)
ifrank>50:
#删除指定country节点
root.remove(country)
############保存文件############
tree.write("newnew.xml",encoding='utf-8')
解析文件方式打开,删除,保存
3、创建XML文档
方式一:
#创建根节点
root=ET.Element("famliy")
#创建节点大儿子
son1=ET.Element('son',{'name':'儿1'})
#创建小儿子
son2=ET.Element('son',{"name":'儿2'})
#在大儿子中创建两个孙子
grandson1=ET.Element('grandson',{'name':'儿11'})
grandson2=ET.Element('grandson',{'name':'儿12'})
son1.append(grandson1)
son1.append(grandson2)
#把儿子添加到根节点中
root.append(son1)
root.append(son1)
tree=ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8',short_empty_elements=False)
创建方式(一)
方式二:
#创建根节点
root=ET.Element("famliy")
#创建大儿子
#son1=ET.Element('son',{'name':'儿1'})
son1=root.makeelement('son',{'name':'儿1'})
#创建小儿子
#son2=ET.Element('son',{"name":'儿2'})
son2=root.makeelement('son',{"name":'儿2'})
#在大儿子中创建两个孙子
#grandson1=ET.Element('grandson',{'name':'儿11'})
grandson1=son1.makeelement('grandson',{'name':'儿11'})
#grandson2=ET.Element('grandson',{'name':'儿12'})
grandson2=son1.makeelement('grandson',{'name':'儿12'})
son1.append(grandson1)
son1.append(grandson2)
#把儿子添加到根节点中
root.append(son1)
root.append(son1)
tree=ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8',short_empty_elements=False)
创建方式(二)
方式三:
#创建根节点
root=ET.Element("famliy")
#创建节点大儿子
son1=ET.SubElement(root,"son",attrib={'name':'儿1'})
#创建小儿子
son2=ET.SubElement(root,"son",attrib={"name":"儿2"})
#在大儿子中创建一个孙子
grandson1=ET.SubElement(son1,"age",attrib={'name':'儿11'})
grandson1.text='孙子'
et=ET.ElementTree(root)#生成文档对象
et.write("test.xml",encoding="utf-8",xml_declaration=True,short_empty_elements=False)
创建方式(三)
设置缩进
由于原生保存的XML时默认无缩进,如果想要设置缩进的话,需要修改保存方式:
fromxml.domimportminidom
defprettify(elem):
"""将节点转换成字符串,并添加缩进。
"""
rough_string=ET.tostring(elem,'utf-8')
reparsed=minidom.parseString(rough_string)
returnreparsed.toprettyxml(indent="\t")
#创建根节点
root=ET.Element("famliy")
#创建大儿子
#son1=ET.Element('son',{'name':'儿1'})
son1=root.makeelement('son',{'name':'儿1'})
#创建小儿子
#son2=ET.Element('son',{"name":'儿2'})
son2=root.makeelement('son',{"name":'儿2'})
#在大儿子中创建两个孙子
#grandson1=ET.Element('grandson',{'name':'儿11'})
grandson1=son1.makeelement('grandson',{'name':'儿11'})
#grandson2=ET.Element('grandson',{'name':'儿12'})
grandson2=son1.makeelement('grandson',{'name':'儿12'})
son1.append(grandson1)
son1.append(grandson2)
#把儿子添加到根节点中
root.append(son1)
root.append(son1)
raw_str=prettify(root)
f=open("xxxoo.xml",'w',encoding='utf-8')
f.write(raw_str)
f.close()
4、命名空间
ET.register_namespace('com',"http://www.company.com")#somename
#buildatreestructure
root=ET.Element("{http://www.company.com}STUFF")
body=ET.SubElement(root,"{http://www.company.com}MORE_STUFF",attrib={"{http://www.company.com}hhh":"123"})
body.text="STUFFEVERYWHERE!"
#wrapitinanElementTreeinstance,andsaveasXML
tree=ET.ElementTree(root)
tree.write("page.xml",
xml_declaration=True,
encoding='utf-8',
method="xml")
命名空间
9.time&datetime模块
importtime
importdatetime
print(time.clock())#返回处理器时间,3.3开始已废弃
print(time.process_time())#返回处理器时间,3.3开始已废弃
print(time.time())#返回当前系统时间戳
print(time.ctime())#输出TueJan2618:23:482016,当前系统时间
print(time.ctime(time.time()-86640))#将时间戳转为字符串格式
print(time.gmtime(time.time()-86640))#将时间戳转换成struct_time格式
print(time.localtime(time.time()-86640))#将时间戳转换成struct_time格式,但返回的本地时间
print(time.mktime(time.localtime()))#与time.localtime()功能相反,将struct_time格式转回成时间戳格式
#time.sleep(4)#sleep
print(time.strftime("%Y-%m-%d%H:%M:%S",time.gmtime()))#将struct_time格式转成指定的字符串格式
print(time.strptime("2016-01-28","%Y-%m-%d"))#将字符串格式转换成struct_time格式
#datetimemodule
print(datetime.date.today())#输出格式2016-01-26
print(datetime.date.fromtimestamp(time.time()-864400))#2016-01-16将时间戳转成日期格式
current_time=datetime.datetime.now()#
print(current_time)#输出2016-01-2619:04:30.335935
print(current_time.timetuple())#返回struct_time格式
#datetime.replace([year[,month[,day[,hour[,minute[,second[,microsecond[,tzinfo]]]]]]]])
print(current_time.replace(2014,9,12))#输出2014-09-1219:06:24.074900,返回当前时间,但指定的值将被替换
str_to_date=datetime.datetime.strptime("21/11/0616:30","%d/%m/%y%H:%M")#将字符串转换成日期格式
new_date=datetime.datetime.now()+datetime.timedelta(days=10)#比现在加10天
new_date=datetime.datetime.now()+datetime.timedelta(days=-10)#比现在减10天
new_date=datetime.datetime.now()+datetime.timedelta(hours=-10)#比现在减10小时
new_date=datetime.datetime.now()+datetime.timedelta(seconds=120)#比现在+120s
print(new_date)
Directive | Meaning | Notes |
---|---|---|
%a | Locale’sabbreviatedweekdayname. | |
%A | Locale’sfullweekdayname. | |
%b | Locale’sabbreviatedmonthname. | |
%B | Locale’sfullmonthname. | |
%c | Locale’sappropriatedateandtimerepresentation. | |
%d | Dayofthemonthasadecimalnumber[01,31]. | |
%H | Hour(24-hourclock)asadecimalnumber[00,23]. | |
%I | Hour(12-hourclock)asadecimalnumber[01,12]. | |
%j | Dayoftheyearasadecimalnumber[001,366]. | |
%m | Monthasadecimalnumber[01,12]. | |
%M | Minuteasadecimalnumber[00,59]. | |
%p | Locale’sequivalentofeitherAMorPM. | (1) |
%S | Secondasadecimalnumber[00,61]. | (2) |
%U | Weeknumberoftheyear(Sundayasthefirstdayoftheweek)asadecimalnumber[00,53].AlldaysinanewyearprecedingthefirstSundayareconsideredtobeinweek0. | (3) |
%w | Weekdayasadecimalnumber[0(Sunday),6]. | |
%W | Weeknumberoftheyear(Mondayasthefirstdayoftheweek)asadecimalnumber[00,53].AlldaysinanewyearprecedingthefirstMondayareconsideredtobeinweek0. | (3) |
%x | Locale’sappropriatedaterepresentation. | |
%X | Locale’sappropriatetimerepresentation. | |
%y | Yearwithoutcenturyasadecimalnumber[00,99]. | |
%Y | Yearwithcenturyasadecimalnumber. | |
%z | TimezoneoffsetindicatingapositiveornegativetimedifferencefromUTC/GMToftheform+HHMMor-HHMM,whereHrepresentsdecimalhourdigitsandMrepresentsdecimalminutedigits[-23:59,+23:59]. | |
%Z | Timezonename(nocharactersifnotimezoneexists). | |
%% | Aliteral'%'character. |
十、logging模块
用于便捷记录日志且线程安全的模块1、单文件日志
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)#一般写level=logging.INFO
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')
日志等级:
FATAL=CRITICAL
ERROR=40
WARNING=30
WARN=WARNING
INFO=20
DEBUG=10
NOTSET=0
注:只有【当前写等级】大于【日志等级】时,日志文件才被记录。
日志记录格式:
2、多文件日志
对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象。
日志1:
file_1_1=logging.FileHandler('l1_1.log','a')
fmt=logging.Formatter(fmt="%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s")
file_1_1.setFormatter(fmt)
file_1_2=logging.FileHandler('l1_2.log','a')
fmt=logging.Formatter()
file_1_2.setFormatter(fmt)
#定义日志
logger1=logging.Logger('s1',level=logging.ERROR)
logger1.addHandler(file_1_1)
logger1.addHandler(file_1_2)
#写日志
logger1.critical('1111')
日志(一)
日志2:
file_2_1=logging.FileHandler('l2_1.log','a')
fmt=logging.Formatter()
file_2_1.setFormatter(fmt)
#定义日志
logger2=logging.Logger('s2',level=logging.INFO)
logger2.addHandler(file_2_1)
日志(二)
如上述创建的两个日志对象
当使用【logger1】写日志时,会将相应的内容写入l1_1.log和l1_2.log文件中
当使用【logger2】写日志时,会将相应的内容写入l2_1.log文件中
十一、系统命令subprocess模块
call执行命令,返回状态码:正常返回0ret=subprocess.call("ls-l",shell=True)
check_call执行命令,如果执行状态码是0,则返回0,否则抛异常
subprocess.check_call("exit1",shell=True)
check_output执行命令,如果状态码是0,则返回执行结果,否则抛异常
subprocess.check_output("exit1",shell=True)
subprocess.Popen(...)
用于执行复杂的系统命令
参数:
args:shell命令,可以是字符串或者序列类型(如:list,元组)
bufsize:指定缓冲。0无缓冲,1行缓冲,其他缓冲区大小,负值系统缓冲
stdin,stdout,stderr:分别表示程序的标准输入、输出、错误句柄
preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callableobject),它将在子进程运行之前被调用
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()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
执行普通命令:
ret1=subprocess.Popen(["mkdir","t1"])
ret2=subprocess.Popen("mkdirt2",shell=True)
终端输入的命令分为两种:
输入即可得到输出,如:ifconfig
输入进行某环境,依赖再输入,如:python
obj=subprocess.Popen("mkdirt3",shell=True,cwd='/home/dev',)
obj=subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
out_error_list=obj.communicate()
print(out_error_list)
obj=subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
obj.stdin.close()
cmd_out=obj.stdout.read()
obj.stdout.close()
cmd_error=obj.stderr.read()
obj.stderr.close()
print(cmd_out)
print(cmd_error)
obj=subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
out_error_list=obj.communicate('print("hello")')
print(out_error_list)
十二、shutil
高级的文件、文件夹、压缩包处理模块[b]shutil.copyfileobj(fsrc,fdst[,length])[/b]
将文件内容拷贝到另一个文件中,可指定长度,复制模式w和a模式
shutil.copyfileobj(open('old.xml','r'),open('new.xml','w'))
shutil.copyfile(src,dst)
拷贝文件
shutil.copymode(src,dst)
仅拷贝权限。内容、组、用户均不变
shutil.copystat(src,dst)
拷贝状态的信息,包括:modebits,atime,mtime,flags
[b]shutil.copy(src,dst)[/b]
拷贝文件和权限
shutil.copy('f1.log','f2.log')
shutil.copy2(src,dst)
拷贝文件和状态信息
shutil.copy2('f1.log','f2.log')
[b]shutil.ignore_patterns(*patterns)
shutil.copytree(src,dst,symlinks=False,ignore=None)[/b]
递归的去拷贝文件夹
shutil.copytree('folder1','folder2',ignore=shutil.ignore_patterns('*.pyc','tmp*'))
shutil.copytree('f1','f2',symlinks=True,ignore=shutil.ignore_patterns('*.pyc','tmp*'))
shutil.rmtree(path[,ignore_errors[,onerror]])
递归的去删除文件
shutil.rmtree('folder1')
[b]shutil.move(src,dst)[/b]
递归的去移动文件,它类似mv命令,其实就是重命名
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对象
importshutil
ret=shutil.make_archive("wwwwwwwwww",'gztar',root_dir='/Users/wupeiqi/Downloads/test')
#将/Users/wupeiqi/Downloads/test下的文件打包放置/Users/wupeiqi/目录
importshutil
ret=shutil.make_archive("/Users/wupeiqi/wwwwwwwwww",'gztar',root_dir='/Users/wupeiqi/Downloads/test')
shutil对压缩包的处理是调用ZipFile和TarFile两个模块来进行的,详细:
zipfile解压缩
#压缩
z=zipfile.ZipFile('laxi.zip','w')
z.write('a.log')
z.write('data.data')
z.close()
#解压
z=zipfile.ZipFile('laxi.zip','r')
z.extractall()
z.close()
zipfile解压缩
tarfile解压缩
#压缩
tar=tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log',arcname='bbs2.log')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log',arcname='cmdb.log')
tar.close()
#解压
tar=tarfile.open('your.tar','r')
tar.extractall()#可设置解压地址
tar.close()
tarfile解压缩
十三、configparser配置文件处理
configparser用于处理特定格式的文件,其本质上是利用open来操作文件。指定格式:
;注释2
[section1]#节点
k1=v1#值
k2:v2#值
[section2]#节点
k1=v1#值
指定格式
1、获取所有节点
config=configparser.ConfigParser()
config.read('xxxooo',encoding='utf-8')
ret=config.sections()
print(ret)
2、获取指定节点下所有的键值对
config=configparser.ConfigParser()
config.read('xxxooo',encoding='utf-8')
ret=config.items('section1')
print(ret)
3.获取指定节点下所有的建
config=configparser.ConfigParser()
config.read('xxxooo',encoding='utf-8')
ret=config.options('section1')
print(ret)
4.获取指定节点下指定key的值
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.检查、删除、添加节点
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.检查、删除、设置指定组内的键值对
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'))
相关文章推荐
- 3306: 树
- Hive:从文件中加载执行语句
- flume的级别的架构使用--实际场景应用--可以用于分布式的服务形式的日志采集
- 最好听的钢琴曲排行榜 世界上最好听的钢琴曲
- Cocoapods快速安装
- Leetcode 263. Ugly Number
- springmvc+ehcache小案例
- Android学习系列(1)--------apk签名
- NYOJ 题目1238 最少换乘
- iOS-block三种应用场景
- 找水王
- 使用新版Eclips编写的APK(V 7包)放入Android源码中mmm编译,报错的两种解决办法
- runtime在开发中的用法
- Hive创建索引
- MFC创建模态对话框和非模态对话框(1)
- nginx 正则表达式
- Android6.0 PROTECTION_NORMAL类总结
- Linux系统资源监控--linux命令、nmon和spotlight
- java中string和int互相转化
- 什么是序列化?在什么情况下将类序列化?