subprocess

python2.x 中使用os 模块来在执行系统命令。

其中两个方法值得关注

os.sys('df -h')

os.Popen('df -h')

其中os.sys() 最终返回的是执行命令的成功与否的状态

而os.Popen() 就相当于开启了一个临时文件,把执行结果放到这个临时文件中。于是你想得到执行结果就需要os.Popen('df -h').read()

 

python3.x 中执行系统命令就不要再用os模块了,因为有subprocess模块,必定人要往前看,别用一些过时的技术。

subprocess模块怎么使用,详细的你去搜,我这就是一个常用的,方法如下:

>>>command_exec_result = subprocess.Popen('df -lh',shell=True,stdout=subprocess.PIPE).stdout.read()

>>> print(command_exec_result.decode())
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1 465Gi 273Gi 191Gi 59% 1325893 4293641386 0% /

来解释下:

1. subprocess.Popen('df -lh',shell=True)这样就执行了。但不能通过这个.read()来获取结果。为什么呢?
因为上面的命令,就相当于你在python中调用subprocess模块下的Popen方法,这个方法得到'df -lh'和 shell=True两个参数,接下来它就开启了一个linux子进程, 我们知道进程 和子进程是不能访问共享数据的。所以你不能直接通过.read()获取结果。
那么怎么获得呢?我们在shell环境中经常使用管道符号“|”获取一个命令的结果传给下一个命令。这里:subprocess.Popen('df -lh',shell=True,stdout=subprocess.PIPE) 中的stdout=subprocess.PIPE 就是管道。这里是stdout,还有stderr但是不常用。
2.
print(command_exec_result.decode())这里为什么command_exec_result.decode(),因为在python3中用subprocess执行的结果是bytes,用decode()方法获取string.
这里扩展一个小知识:
python2.x中 bytes 和 string没有啥区别。
python3.x中bytes和string就区分了。并且python3.x默认用的字符编码是utf-8,所以默认支持中文。
字符串.encode()是将string转换成bytes
b'ss'.decoude()是将bytes转换成了utf-8编码形式的字符串。



posted @ 2017-01-13 16:37  zhming  阅读(977)  评论(0编辑  收藏  举报