python 调用 shell 命令方法

简介:

python调用shell命令方法


1、os.system(cmd)

缺点:不能获取返回值


2、os.popen(cmd)

要得到命令的输出内容,只需再调用下read()或readlines()等  
例:a=os.popen(cmd).read()


3、commands 模块,其实也是对popen的封装。

此模块主要有如下方法:
commands.getstatusoutput(cmd) 返回(status, output).
commands.getoutput(cmd) 只返回输出结果
commands.getstatus(file) 返回ls -ld file的执行结果字符串,调用了getoutput

例:
 >>> import commands
 >>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
 >>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
 >>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
 >>> commands.getoutput('ls /bin/ls')
'/bin/ls'
 >>> commands.getstatus('/bin/ls')
'-rwxr-xr-x  1 root        13352 Oct 14  1994 /bin/ls'

 

本文转自罗兵博客园博客,原文链接:http://www.cnblogs.com/hhh5460/p/5245523.html ,如需转载请自行联系原作者
相关文章
|
14天前
|
Python
python魔法方法如何应用
【4月更文挑战第12天】这个Python示例展示了类继承和方法重写。`Student`类继承自`Person`,并覆盖了`say_hello`方法。通过`super().__init__(name)`调用父类的`__init__`初始化`name`属性,`Student`添加了`age`属性,并在重写的`say_hello`中使用。创建`Student`实例`student`并调用其`say_hello`,输出定制的问候信息。
20 1
|
18天前
|
Web App开发 Java Linux
Linux之Shell基本命令篇
Linux之Shell基本命令篇
Linux之Shell基本命令篇
|
5天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
30 3
|
1天前
|
运维 Shell Python
Shell和Python学习教程总结
Shell和Python学习教程总结
|
2天前
|
监控 Shell
生产环境Shell脚本Ping监控主机是否存活(多种方法)
生产环境Shell脚本Ping监控主机是否存活(多种方法)
|
2天前
|
运维 Shell
Shell脚本判断IP是否合法性(多种方法)
Shell脚本判断IP是否合法性(多种方法)
|
3天前
|
人工智能 Python
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
21 0
|
6天前
|
存储 Shell 数据安全/隐私保护
ZooKeeper【基础知识 04】控制权限ACL(原生的 Shell 命令)
【4月更文挑战第11天】ZooKeeper【基础知识 04】控制权限ACL(原生的 Shell 命令)
25 7
|
7天前
|
存储 关系型数据库 MySQL
Python搭建代理IP池实现存储IP的方法
Python搭建代理IP池实现存储IP的方法
|
7天前
|
Python
Python动态IP代理防止被封的方法
Python动态IP代理防止被封的方法