开发者社区> 科技小能手> 正文

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

简介:
+关注继续查看

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

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

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

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


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

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

这样得到的结果与第一个方法是一样的。

3、commands模块#可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位

1
2
3
4
5
6
7
8
9
10
11
12
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)只返回输出结果

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命令。



本文转自 ZhouLS 51CTO博客,原文链接:http://blog.51cto.com/zhou123/1312791

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
shell脚本中执行python脚本,处理字符串,同时复制到剪贴板
shell脚本中执行python脚本,处理字符串,同时复制到剪贴板
77 0
Python编程:sh模块执行shell命令
Python编程:sh模块执行shell命令
43 0
python subprocess模块处理shell命令详解
python subprocess模块处理shell命令详解
83 0
python实现【希尔排序】(Shell Sort)
python实现【希尔排序】(Shell Sort)
14 0
shell中调用python函数,发送邮件
shell中调用python函数,发送邮件
64 0
Python编程:sh模块执行shell命令
Python编程:sh模块执行shell命令
47 0
Monit 和 shell python脚本 的使用
Monit 和 shell python脚本 的使用
70 0
程序员必备手册 | Git、Vim、GDB、Shell、Python
程序员必备手册 | Git、Vim、GDB、Shell、Python
52 0
Python:Scrapy Shell
Python:Scrapy Shell
53 0
书籍:Data Cleaning数据清洗-基于shell和python - 2018.pdf
简介 作为最畅销的口袋入门系列的一部分,本书旨在为程序员提供足够的数据清理知识,以便能够在自己的项目中工作。 它被设计为使用灵活,强大(和免费)的Unix / Linux shell命令和python来执行常见数据清理任务的实用介绍。
1825 0
文章
问答
文章排行榜
最热
最新
相关电子书
更多
给运维工程师的Python实战课
立即下载
Shell 脚本速查手册
立即下载
Python 脚本速查手册
立即下载