subprocess模块作用
通过此模块,可直接运行系统命令
代码
#Author Kang
import subprocess
#subprocess.getoutput命令:
#把命令运行结果传给res变量,但不能判断命令是否执行成功
res = subprocess.getoutput("ls -lh /etc")
print(res)
#结果:
lrwxr-xr-x@ 1 root wheel 11B Sep 14 2016 /etc -> private/etc
#subprocess.getstatusoutput命令:
#把命令运行结果传给res1变量,此结果为一个元组,带有命令执行是否成功
#0为成功,非0为不成功
res1 = subprocess.getstatusoutput("ls -lh /etc")
print(res1[0])
print(res1[1])
print(res1)
#结果:
0
lrwxr-xr-x@ 1 root wheel 11B Sep 14 2016 /etc -> private/etc
(0, 'lrwxr-xr-x@ 1 root wheel 11B Sep 14 2016 /etc -> private/etc')
res2 = subprocess.getstatusoutput("lsbb -lh /etc")
print(type(res2))
print(res2[0])
#结果:
<class 'tuple'>
127
/bin/sh: lsbb: command not found