Python 调用系统命令

来源:互联网 发布:mtv制作软件下载 编辑:程序博客网 时间:2024/06/14 00:34

原文:http://www.linuxidc.com/Linux/2015-02/113067.htm

os.system
os.spawn
os.popen
popen2
commands
这些东西统统将被subprocess取代,subprocess真的很好用,有没有!
1、subprocess.call()
subprocess.call()参数是一个列表,如果想把shell命令以字符串的形式传进来,需要添加shell=True这个参数。
>>> from subprocess import call 
>>> call("df -h",shell=True) 
Filesystem      Size  Used Avail Use% Mounted on 
/dev/disk1      112G  75G  38G  67% /

0
如果不指定shell=True,需要传递一个列表作为参数
>>> call(['df','-h']) 
Filesystem      Size  Used Avail Use% Mounted on 
/dev/disk1      112G  75G  38G  67% /

0

返回值是shell的returncode

2、subprocess.Popen()

call方法是Popen的一个封装,call 的返回值是shell的退出码,Popen返回的是一个Popen对象。使用起来比较方便,但是是阻塞的,会一直等到call方法执行完,才能继续执行。Popen是非阻塞的,相当于放到后台执行,如果需要拿到shell命令的标准输出,错误输出的时候,用Popen比较方便。
>>> from subprocess import Popen,PIPE 
>>> pobj = Popen('ls -l',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) 
>>> result = pobj.communicate()

此时result以一个列表的方式返回,result[0]为标准输出,result[1]是错误输出
>>> exitcode = pobj.poll() 
>>> print exitcode

2

调用Popen对象的poll方法,返回shell退出码

下面是封装的一个方法,参数是要传递的命令,如果不添加shell=True,需要以列表的方式传递命令,否则,传一个字符串。函数返回一个列表,分别是标准输出,错误输出和returncode
1 from subprocess import Popen,PIPE

 def execcommand(commandstr): 
    process = Popen(commandstr,stdout=PIPE,stderr=PIPE,shell=True) 
    res = process.communicate() 
    toout = res[0] 
    toerr = res[1] 
    exitcode = process.poll() 
    result = [toout,toerr,exitcode] 
    return result

0 0