您的位置:首页 > 编程语言 > Python开发

python笔记 - day7

2016-08-28 15:35 423 查看

python笔记 - day7

参考:

http://www.cnblogs.com/wupeiqi/articles/5501365.html

面向对象,初级篇:

http://www.cnblogs.com/wupeiqi/p/4493506.html

大纲:

configparser模块
XML模块
shutil模块以及压缩包处理
subprocess模块
面向对象学习

configparser:

模块解析:configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

from xml.etree import ElementTree as ET
from xml.dom import minidom

def prettify(elem):
"""将节点转换成字符串,并添加缩进。
"""
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.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()


缩进保存方法:

zipfile,压缩,解压缩文件:

ZIP

import zipfile

#把文件“ooo.xml,newxx.xml”打包成laxi.zip文件
z = zipfile.ZipFile('laxi.zip','w')
z.write('ooo.xml')
z.write('newxx.xml')
z.close()

#把t1.py文件,追加打包到laxi.zip文件中
z = zipfile.ZipFile('laxi.zip','a')
z.write('t1.py')
z.close()

#解压laxi.zip这个包文件
z = zipfile.ZipFile('laxi.zip','r')
z.extract()
z.close()

#单独把“ooo.xml”文件解压出来
z = zipfile.ZipFile('laxi.zip','r')
z.extract('ooo.xml')

#打印出来“laxi.zip”压缩包中,打包了哪些文件
z = zipfile.ZipFile('laxi.zip','r')
for item in z.namelist():
print(item,type(item))


tarfile

import tarfile

#把“t1.py重命名成t1bak.py”
#把“t2.py重命名成t2bak.py”
#然后把这两个文件打包成your.tar文件
tar = tarfile.open('your.tar','w')
tar.add('t1.py',arcname='t1bak.py')
tar.add('t2.py',arcname='t2bak.py')
tar.close()

#把t1.py文件重命名后追加打包到your.tar文件中
tar = tarfile.open('your.tar','a')
tar.add('t1.py',arcname='t3bak.py')
tar.close()

#解压your.tar这个文件
tar = tarfile.open('your.tar','r')
tar.extractall()
tar.close()

#只解压t1bak.py这个文件
tar = tarfile.open('your.tar','r')
tar.extract('t1bak.py')
tar.close()

#打印出your.tar包中的所有文件
tar = tarfile.open('your.tar','r')
for item in tar.getmembers():
print(item)


subprocess执行系统命令:

shell=False传列表,shell等于True传字符串

call

执行命令,返回状态码

ret = subprocess.call(["ls", "-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)


check_call

执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

import subprocess
subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)

ret = subprocess.call(["ipconfig"],shell=False)
print(ret)

ret = subprocess.call("ipconfig",shell=True)
print(ret)


check_output

执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)


subprocess.Popen(...) 用于执行复杂的系统命令

参数:

args:shell命令,可以是字符串或者序列类型(如:list,元组)

bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲

stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄

preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用

close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。

shell:同上

cwd:用于设置子进程的当前目录

env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。

universal_newlines:不同系统的换行符不同,True -> 同意使用 \n

startupinfo与createionflags只在windows下有效
将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)


终端输入的命令分为两种:

输入即可得到输出,如:ifconfig

输入进行某环境,依赖再输入,如:python

import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)


import subprocess

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: