python运行shell命令四种方法
2014-07-05 09:43
295 查看
这里介绍一下python执行shell命令的四种方法:
1、os模块中的os.system()这个函数来执行shell命令
注,这个方法得不到shell命令的输出。
2、popen()#这个方法能得到命令执行后的结果是一个字符串,要自行处理才能得到想要的信息。
这样得到的结果与第一个方法是一样的。
3、commands模块#可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位
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命令。
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命令。
相关文章推荐
- python执行shell命令的四种方法
- python运行shell命令并得到返回结果(比C++方便多了)
- python调用shell命令的方法有许多
- Python——调用shell命令的三种方法
- Nodejs中调用系统命令、Shell脚本和Python脚本的方法和实例
- 运行jar应用程序引用其他jar包的四种方法(java命令)
- Python运行Shell命令
- python 调用shell命令的方法
- python2.7 执行cmd命令及shell命令封装方法
- python中执行shell命令的几个方法小结
- python脚本内运行linux命令的方法
- python学习五:执行linux命令的两种方法、提高运行效率、进制转换、切片详解、ip和mac获取
- csc不是内部或外部命令,也不是可运行的程序,VisualStudio2005环境下四种解决方法。
- python 调用shell命令三种方法 分类: python基础学习 python Module 2014-01-13 14:13 239人阅读 评论(0) 收藏
- Nodejs中调用系统命令、Shell脚本和Python脚本的方法和实例
- python 调用shell命令三种方法
- python 调用shell命令三种方法
- python脚本内运行linux命令的方法
- python调用shell命令之三大方法
- Nodejs中调用系统命令、Shell脚本和Python脚本的方法和实例