设为首页 加入收藏

TOP

Python 调用系统命令
2015-02-13 18:23:40 来源: 作者: 【 】 浏览:25
Tags: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


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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python 日志记录模块logging的使用 下一篇Linux C编程学习:进程,进程,进..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: