这里介绍一下python执行shell命令的四种办法:

1、os模块中的os.system()这个函数来执行shell命令

>>> os.system('ls')anaconda-ks.cfg  install.log  install.log.syslog  send_sms_service.py  sms.py

注,这个办法得不到shell命令的输入。

2、popen()#这个办法能失去命令执行后的后果是一个字符串,要自行处理能力失去想要的信息。

>>> import os>>> str = os.popen("ls").read()>>> a = str.split("\n")>>> for b in a:        print b

这样失去的后果与第一个办法是一样的。

3、commands模块#能够很不便的获得命令的输入(包含规范和谬误输入)和执行状态位

import commandsa,b = commands.getstatusoutput('ls')a是退出状态b是输入的后果。>>> import commands>>> a,b = commands.getstatusoutput('ls')>>> print a0>>> print banaconda-ks.cfginstall.loginstall.log.syslog

commands.getstatusoutput(cmd)返回(status,output)

commands.getoutput(cmd)只返回输入后果

commands.getstatus(file)返回ls -ld file 的执行后果字符串,调用了getoutput,不倡议应用这个办法。

4、subprocess模块

应用subprocess模块能够创立新的过程,能够与新建过程的输出/输入/谬误管道连通,并能够取得新建过程执行的返回状态。应用subprocess模块的目标是代替os.system()、os.popen()、commands.等旧的函数或模块。

import subprocess

1、subprocess.call(command, shell=True)

会间接打印出后果。

2、subprocess.Popen(command, shell=True) 也能够是subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) 这样就能够输入后果了。

如果command不是一个可执行文件,shell=True是不可省略的。

shell=True意思是shell下执行command

这四种办法都能够执行shell命令。