python学习——python中执行shell命令
2013-10-21 17:44
555 查看
这里介绍一下python执行shell命令的四种方法:
1、os模块中的os.system()这个函数来执行shell命令
2、popen()#这个方法能得到命令执行后的结果是一个字符串,要自行处理才能得到想要的信息。
3、commands模块#可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位
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命令。
1、os模块中的os.system()这个函数来执行shell命令
>>> os.system('ls') anaconda-ks.cfg install.log install.log.syslog send_sms_service.py sms.py 0注,这个方法得不到shell命令的输出。
2、popen()#这个方法能得到命令执行后的结果是一个字符串,要自行处理才能得到想要的信息。
>>> import os >>> str = os.popen("ls").read() >>> a = str.split("\n") >>> for b in a: print b这样得到的结果与第一个方法是一样的。
3、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.syslogcommands.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命令。
相关文章推荐
- python学习——python中执行shell命令
- python学习——python中执行shell命令
- IPython下执行shell命令-魔力函数(alias store rehash)- 千月的python linux 系统管理指南学习笔记(6)
- Python 执行Shell 外部命令
- Python学习总结 06 paramiko 远程执行命令
- Linux学习笔记:bash特性之多命令执行,shell脚本
- python 学习笔记 8 -- Python下调用Linux的Shell命令
- python中执行shell命令的几种方式
- 命令执行顺序-------shell学习(5)
- python执行shell命令的几种方法
- python 执行shell命令的类
- python 执行shell命令无法获取返回值的解决方法
- python执行shell命令的几种方法
- python执行shell命令
- shell script 学习笔记-----命令执行
- python-模块间的导入与os.system('xxx')的shell命令执行
- python-执行shell命令的模块使用
- C++/Php/Python 语言执行shell命令
- 转变思维--使用Python生成Shell命令,批量执行程序
- 在python中执行shell命令,并以字符串形式返回命令执行结果