subprocess
可以执行shell命令的相关模块和函数有:
os.system
os.spawn
os.popen --废弃
popen2.* --废弃
commands.* --废弃,3.x中被移除
import commands
result = commands.getoutput('cmd') #只返回执行的结果, 忽略返回值.
result = commands.getstatus('cmd') #返回ls -ld file执行的结果.
result = commands.getstatusoutput('cmd')
#用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result). cmd执行的方式是{ cmd ; }2>&1, 这样返回结果里面就会包含标准输出和标准错误.
例子
>>> subprocess.getstatusoutput('pwd')
(0, '/home/ronny')
>>> subprocess.getoutput('pwd')
'/home/ronny'
>>> subprocess.getstatus('pwd')
Traceback (most recent call last):
File "", line 1, in
AttributeError: module 'subprocess' has no attribute 'getstatus'
以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。
(1) call
执行命令,返回状态码(命令正常执行返回0,报错则返回1)
ret2=subprocess.call("ipconfig") #python3.5不是这样,依然会抛出异常导致无法对ret2赋值
print(ret1) #0
print(ret2) #1
ret = subprocess.call(["ls", "-l"], shell=False) #shell为False的时候命令必须分开写
ret = subprocess.call("ls -l", shell=True)
(2) check_call
执行命令,如果执行成功则返回状态码0,否则抛异常
subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)
(3) check_output
执行命令,如果执行成功则返回执行结果,否则抛异常
subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)