python学习——python中执行shell命令

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

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

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

注,这个方法得不到shell命令的输出。ide


二、popen()#这个方法能获得命令执行后的结果是一个字符串,要自行处理才能获得想要的信息。函数

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

这样获得的结果与第一个方法是同样的。spa

三、commands模块#能够很方便的取得命令的输出(包括标准和错误输出)和执行状态位进程

import commands
a,b = commands.getstatusoutput('ls')
a是退出状态
b是输出的结果。
>>> import commands
>>> a,b = commands.getstatusoutput('ls')
>>> print a
0
>>> print b
anaconda-ks.cfg
install.log
install.log.syslog

commands.getstatusoutput(cmd)返回(status,output)字符串

commands.getoutput(cmd)只返回输出结果get

commands.getstatus(file)返回ls -ld file 的执行结果字符串,调用了getoutput,不建议使用这个方法。cmd


四、subprocess模块
it


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

import subprocess

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

#会直接打印出结果。

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

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

shell=True意思是shell下执行command


这四种方法均可以执行shell命令。

相关文章
相关标签/搜索