python学习第五天

一 常用模块

定义:可以实现某种功能的.py结尾的python文件,文件名为test.py,则模块名为test

 

导入方法

import   模块名

import  模块名1,模块名2

from 模块名 import *           不建议使用这种方法,容易引起模块中的方法被程序中的同名方法覆盖的错误

from 模块名 import  方法名1,方法名2

from 模块名 import 方法名 as 别名

 

import本质

import 包名   执行包中的__init__.py

import 模块名   将模块中所有代码赋值给以这个模块名命名的变量

from 模块名 import 方法名    把指定方法的代码赋值给以这个方法名命名的变量

 

导入优化

使用from   import方式导入模块方法,加快程序运行速度

 

模块分类

标准模块

time模块

'''输出当前时间的时间戳'''

print(time.time())

'''程序停止几秒'''

# time.sleep(2)

'''时间戳转换为时间元组形式,以UTC时区为标准'''

print(time.gmtime())

'''时间戳转换为时间元组形式,以本地时区为标准'''

print(time.localtime())

x =time.localtime()

'''提取时间元组中的元素'''

print(x.tm_mday)

'''时间元组转换成时间戳'''

print(time.mktime(time.localtime()))

'''时间元组转换成格式化的时间'''

print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

'''格式化时间转换成指定格式的时间元组'''

print(time.strptime(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()),"%Y-%m-%d %H:%M:%S"))

'''时间元组转换成时间字符串'''

print(time.asctime(time.localtime()))

'''时间戳转换成时间字符串'''

print(time.ctime(time.time()))

 

 

datetime模块

'''获取当前时间'''

print(datetime.datetime.now())

'''获取当前日期几天前或几天后的时间,负数代表几天前,正数代表几天后'''

print(datetime.datetime.now()+datetime.timedelta(-1))

 

random模块

'''获取随机浮点数,范围0-1'''

print(random.random())

'''获取随机浮点数,范围自定义'''

print(random.uniform(3,6))

'''获取随机整数,范围自定义'''

print(random.randint(3,8))

'''获取随机整数,范围自定义,范围左闭右开'''

print(random.randrange(3,8))

'''在传入序列中获取一位随机值'''

print(random.choice([2,5,"a",9]))

'''在传入序列中取出指定位数的值,以列表形式返回'''

print(random.sample([2,5,"a",9],2))

'''将传入序列的顺序打乱'''

list =[2,5,"a",9]

random.shuffle(list)

print(list)

 

import random
checkcode =""
for i in range(4):
     current = random.randrange(0,4)
     if current == i:
        tmp = chr(random.randint(65,90))
     else:
        tmp = random.randint(0,9)
        checkcode += str(tmp)
print(checkcode)

以上代码实现输出四位验证码的功能

 

os模块

'''获取当前的操作目录'''
print(os.getcwd())
'''切换工作目录'''
os.chdir("/root")
'''递归的创建目录'''
# os.makedirs("/root/a/b/c/")
'''递归删除空目录'''
# os.removedirs("/root/a/b/c/")
'''创建目录,无法递归创建'''
# os.mkdir("/root/a/")
'''删除指定目录,无法递归删除'''
# os.rmdir("/root/a/")
'''列出指定目录下的所有内容'''
print(os.listdir("/root/"))
'''重命名文件或目录'''
# os.rename("/root/test.txt","/root/3-30.txt")
'''查看文件属性'''
print(os.stat("/root/3-30.txt"))
'''输出当前系统的路径分隔符'''
print(os.sep)
'''输出当前系统的换行符'''
print(os.linesep)
'''输出当前系统的文件路径分隔符'''
print(os.pathsep)
'''输出当前系统类型'''
print(os.name)
'''执行当前系统的操作命令,不保存结果'''
os.system("ls")
'''执行当前系统的操作命令,结果保存在内存中,使用read方法获取'''
print(os.popen("ls").read())
'''输出系统环境变量'''
print(os.environ)
'''输出文件绝对路径'''
print(os.path.abspath("3-30.txt"))
'''分隔文件目录路径和文件名'''
print(os.path.split("/root/3-30.txt"))
'''输出文件路径中的目录部分'''
print(os.path.dirname("/usr/local/bin/a.txt"))
'''输出文件路径中的文件名部分'''
print(os.path.basename("/usr/local.bin/a.txt"))
'''判断路径是否存在'''
print(os.path.exists("/usr/local/a.txt"))
'''判断输入的是否为绝对路径'''
print(os.path.isabs("3-20.txt"))
'''判断输入的是否为一个存在的文件'''
print(os.path.isfile("3-20.txt"))
'''判断输入的是否为一个存在的目录'''
print(os.path.isdir("/usr/"))
'''将输入的多个路径组合返回,最后一个绝对路径前的内容会被忽略'''
print(os.path.join("a","/usr","local","a.txt"))
'''输出文件或目录最后的存取时间'''
print(os.path.getatime(__file__))
'''输出文件或目录最后的修改时间'''
print(os.path.getmtime(__file__))

 

sys模块

sys.argv

sys.exit()  退出程序,正常推出为exit(0)

sys.version 获取python解释器版本信息

sys.maxint 最大Int值

sys.path 返回python环境变量值

sys.platform 返回操作系统平台名称

sys.stdout.write() 

val = sys.stdin.readline()[:-1]

 

shutil模块

shutil.copyfileobj()  传入两个文件对象,复制源文件内容到目标文件

shutil.copyfile() 输入源文件名,目标文件名进行复制

shutil.copymode()   将源文件权限模式复制给目标文件

shutil.copystat()  将源文件属性复制给目标文件

shutil.copy()    复制文件和权限

shutil.copy2() 复制文件和权限和状态信息

shutil.copytree() 递归的复制文件

shutil.rmtree() 递归删除目录

shutil.move() 递归移动文件

shutil.make_archive("压缩包名或路径","压缩类型","要压缩文件的路径") 

 

shelve模块

通过key-value将内存数据通过文件持久化

import shelve
d =shelve.open("shelve_test")
name =[1,2,3,4]
info = {"name":"lf","age":23}

d["name"] =name  列表持久化
d["info"] =info  字典持久化
d.close()
print(d.get("info"))  取出持久化文件内容

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)  打印xml标签,属性
     for i in child:
          print(i.tag, i.text)  打印标签,文本

# 只遍历year 节点
for node in root.iter('year'):
     print(node.tag, node.text)

#修改

for node in root.iter('year'):
     new_year = int(node.text) +1
     node.text =str(new_year)
     node.set("updated_by","Alex")
tree.write("xmltest.xml")

 

#删除

for country in root.findall('country'):
     rank =int(country.find('rank').text)
     if rank > 50:
        root.remove(country)
tree.write("output.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) #打印生成的格式
 
configparser模块
使用configparser生成配置文件
import configparser
 
config = configparser.ConfigParser()
config["DEFAULT"= {'ServerAliveInterval''45',
            'Compression''yes',
               'CompressionLevel''9'}
 
config['bitbucket.org'= {}
config['bitbucket.org']['User'= 'hg'
config['topsecret.server.com'= {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'= '50022'     # mutates the parser
topsecret['ForwardX11'= 'no'  # same here
config['DEFAULT']['ForwardX11'= 'yes'
with open('example.ini''w') as configfile:
   config.write(configfile)
 
读配置文件
config.read('example.ini')
config.default()   输出配置文件的默认配置项
config.sections()  输出其他配置
config['bitbucket.org']['User']  读取配置选项的参数
 
hashlib模块
import hashlib
 
= hashlib.md5()   MD5方式加密,可以指定其他加密方式
m.update(b"Hello")    要加密的内容,加密中文需要encode之后才能加密
m.update(b"It's me")
print(m.digest())
m.update(b"It's been a long time since last time we ...")
 
print(m.digest()) #2进制格式hash
print(len(m.hexdigest())) #16进制格式hash
 
import hmac
= hmac.new('天王盖地虎'.encode("encoding="utf-8"), '宝塔镇河妖'.encode(encoding="utf-8"))  key-values形式加密,前面指定key值,通讯双方比对key值是否相同来鉴别消息真伪,加密时需要输入bytes类型的值,加密中文需要encode之后才能加密
print(h.hexdigest())
 
re模块
常用正则符号
'.'     默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^'     匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
'$'     匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
'*'     匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac")  结果为['abb''ab''a']
'+'     匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab''abb']
'?'     匹配前一个字符1次或0
'{m}'   匹配前一个字符m次
'{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb''ab''abb']
'|'     匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
'(...)' 分组匹配,re.search("(abc){2}a(123|456)c""abcabca456c").group() 结果 abcabca456c
 
 
'\A'    只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的
'\Z'    匹配字符结尾,同$
'\d'    匹配数字0-9
'\D'    匹配非数字
'\w'    匹配[A-Za-z0-9]
'\W'    匹配非[A-Za-z0-9]
's'     匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'
 
'(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province''3714''city''81''birthday''1993'}
 
常用匹配模式
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当做列表分隔符
re.sub    匹配字符并替换
 
subprocess模块
py3.5及以上版本
subprocess.run("命令","选项","参数")  
subprocess.run("命令",shell=True) 使用shell执行命令  
 
py3.5以前的3.0版本

#执行命令,返回命令执行状态 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"])

#执行命令,如果命令结果为0,就正常返回,否则抛异常
>>> subprocess.check_call(["ls", "-l"])
0

#接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果 
>>> subprocess.getstatusoutput('ls /bin/ls')    建议使用
(0, '/bin/ls')

#接收字符串格式命令,并返回结果
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

#执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
>>> res=subprocess.check_output(['ls','-l'])
>>> res
b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'

 

p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)

可用参数

    • 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()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
subprocess.popen对象可用的方法
poll()   检查命令是否结束,结束后返回结果
wait()  等待命令结束
terminate() 结束命令
stdout.read() 读取标准输出
 
sudo自动输密码

subprocess.popen("echo "123"|sudo -S yum -y install httpd",shell=True)

 

 

 
 
 
posted @ 2017-03-23 18:48  魅力宁波  阅读(209)  评论(1)    收藏  举报