Python 调用shell

Python 调用shell

第一种,os.system("The command you want").

这个调用相当直接,且是同步进行的,程序需要阻塞并等待返回。返回值是依赖于系统的,直接返回系统的调用返回值,所以windows和linux是不一样的。

第二种,os.popen(command[,mode[,bufsize]]),先给大家看个例子

import os
p = os.popen("dir c:", 'r')
p.read()
bla bla... <这里是dir正确的输出>

p.close()
p = os.popen("dir d:", 'r') # 电脑中没有D盘
p.read()
''

p.close()
1

可以看出,popen方法通过p.read()获取终端输出,而且popen需要关闭close().当执行成功时,close()不返回任何值,失败时,close()返回系统返回值. 可见它获取返回值的方式和os.system不同。

第三种,使用commands模块,同样看一组例子。

import commands
commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')

commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')

commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')

commands.getoutput('ls /bin/ls')
'/bin/ls'

commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

根据你需要的不同,commands模块有三个方法可供选择。getstatusoutput, getoutput, getstatus。

但是,如上三个方法都不是Python推荐的方法,而且在Python3中其中两个已经消失。Python文档中目前全力推荐第四个方法,subprocess!

subprocess使用起来同样简单:

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

subprocess.call("ls -l", shell=True)
0

subprocess.call("exit 1", shell=True)
1

直接调用命令,返回值即是系统返回。shell=True表示命令最终在shell中运行。Python文档中出于安全考虑,不建议使用shell=True。建议使用Python库来代替shell命令,或使用pipe的一些功能做一些转义。官方的出发点是好的,不过真心麻烦了很多, so....

如果你更关注命令的终端输出,可以这样

subprocess.check_output(["echo", "Hello World!"])
'Hello World! '

subprocess.check_output("exit 1", shell=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1