commands模块【转】
https://www.cnblogs.com/wjoyxt/p/5087951.html
要获得shell命令的输出只需要`cmd`命令就可以了,
需要得到命令执行的状态则需要判断$?的值, 在Python中有一个模块commands也很容易做到以上的效果.
看一下三个函数:
1). commands.getstatusoutput(cmd)
用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result),其中 status为int类型,result为string类型。cmd执行的方式是{ cmd ; } 2>&1, 这样返回结果里面就会包含标准输出和标准错误.
2). commands.getoutput(cmd)
只返回执行的结果, 忽略返回值.
3). commands.getstatus(file) #现已被弃用
返回ls -ld file执行的结果.
看一下这些函数使用的例子:
>>> 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') #该函数已被python丢弃,不建议使用,它返回 ls -ld file 的结果(String)(返回结果太奇怪了,难怪被丢弃)
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
#!/usr/bin/python
#coding:utf-8
import os,sys,commands def openfile():
grains = {}
_open_file=65533
try:
getulimit=commands.getstatusoutput('source /etc/profile;ulimit -n')
except Exception,e:
pass
if getulimit[0]==0:
_open_file=int(getulimit[1])
grains['max_open_file'] = _open_file
return grains
最新文章
- python数字图像处理(18):高级形态学处理
- 【BZOJ 2809】【APIO 2012】dispatching
- Java控制语句——break和continue
- mac终端下运行shell脚本
- POJ 1317
- 2014年辛星完全解读Javascript第四节 流程控制语句
- Java调用SQLCMD遇到的问题
- Unity3d 协程的注意问题(新手须注意,老手须加勉)
- 【Android 开源】:最火的Android开源项目 第01期
- nginx conf by linux kernel
- Redis集群搭建方案(Linux)
- [knowledge][模式匹配] 字符匹配/模式匹配 正则表达式 自动机
- yum update 自动忽略内核更新
- Peter的烟(水题测试2017082401&洛谷1150)
- YQCB冲刺第二周第四天
- [kafka] 001_kafka起步
- 20155325 2016-2017-2 《Java程序设计》第7周学习总结
- flask介绍
- golang基础--method方法
- Splitter Control for Dialog
热门文章
- 洛谷P2324 [SCOI2005] 骑士精神
- UDP 区别于 TCP 的特点
- 模板 - 数学 - 同余 - 扩展Euclid算法
- C++标准库分析总结(八)——<;仿函数、适配器、istream_iterator、ostream_iterator、bind>;
- vue+element 表格formatter数据格式化并且插入html标签
- Java学习笔记-文件读写和Json数组
- 【转】JDK5.0中JVM堆模型、GC垃圾收集详细解析
- name_scope与variable_scope 详解
- Are query string keys case sensitive?
- TP-Link TL-WR941N Ver 5.1安装OPENWRT过程