Python 调用系统命令


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

--------------------------------------分割线 --------------------------------------

CentOS上源码安装Python3.4 

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版]

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]

Python脚本获取Linux系统信息

在Ubuntu下用Python搭建桌面算法交易研究环境

Python 语言的发展简史

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永久更新链接地址:

相关内容

    暂无相关文章