python 常用代码学习笔记之commands模块
2013-08-08 08:32
986 查看
通常我们调用os.system(cmd) 只能获得命令是否能执行成功。即结果为0或者非0标识是否执行成功。
而有时我们希望即获取到是否成功,同时也获取命令的执行结果。
这时就可以使用commands了,通过它可以同时获取命令的执行结果输出和结果。
实例如下:
这样ret就反馈是否执行成功,比如为0(成功) 或者非0(不成功)
output 用来获取ls命令的执行结果。
注:查看python api文档:
commands.getstatusoutput(cmd)
Execute the string cmd in a shell with os.popen() and
return a 2-tuple (status, output). cmd is actually run as { cmd ; } 2>&1,
so that the returned output will contain output or error messages. A trailing newline is stripped from the output. The exit status for the command can be interpreted according to the rules for the C function wait().
注意该命令会将错误输出流重定向到标准输出流中,因此output也会保存错误输出。
如下是一个获取机器eth0 网卡ip的使用示例。
cmd='''ifconfig eth0|grep "inet "|awk '{print $2}'|awk -F":" '{print $2}' '''
ret,ip = commands.getstatusoutput(cmd)
#print ip, ret
if ret != 0 :
print "get ip failed";
sys.exit(2)
而有时我们希望即获取到是否成功,同时也获取命令的执行结果。
这时就可以使用commands了,通过它可以同时获取命令的执行结果输出和结果。
实例如下:
1: import commands
2:
3: ret, output = commands.getstatusoutput('ls')
4: print ret
5: print output
这样ret就反馈是否执行成功,比如为0(成功) 或者非0(不成功)
output 用来获取ls命令的执行结果。
注:查看python api文档:
commands.getstatusoutput(cmd)
Execute the string cmd in a shell with os.popen() and
return a 2-tuple (status, output). cmd is actually run as { cmd ; } 2>&1,
so that the returned output will contain output or error messages. A trailing newline is stripped from the output. The exit status for the command can be interpreted according to the rules for the C function wait().
注意该命令会将错误输出流重定向到标准输出流中,因此output也会保存错误输出。
如下是一个获取机器eth0 网卡ip的使用示例。
cmd='''ifconfig eth0|grep "inet "|awk '{print $2}'|awk -F":" '{print $2}' '''
ret,ip = commands.getstatusoutput(cmd)
#print ip, ret
if ret != 0 :
print "get ip failed";
sys.exit(2)
相关文章推荐
- [代码笔记] python 常用标准库学习
- python学习笔记之常用模块用法分析
- python 学习笔记 14 -- 常用的时间模块之datetime
- python的学习笔记之——time模块常用内置函数
- 学习笔记(11月10日)--python常用内置模块的使用(logging, os, command)
- [转载]Python学习笔记三(常用模块)
- Python学习笔记(三十三)常用内置模块(2)collections_namedtuple_deque_defaultdict_OrderedDict_Counter
- [Python] Python学习笔记之常用模块总结[持续更新...]
- python 学习笔记 os模块常用项
- python学习笔记(5)--迭代器,生成器,装饰器,常用模块,序列化
- Python 学习笔记(四):常用内建模块和第三方模块
- Python 学习笔记(常用模块)
- python学习笔记 常用第三方模块
- python 常用代码学习笔记之commands模块
- Python 学习笔记(6)--常用模块(2)
- python学习笔记(六):常用模块
- python 学习笔记 13 -- 常用的时间模块之time
- 【Python】学习笔记——-14、常用第三方模块
- 28. Python脚本学习笔记二十八代码检测和分析
- python学习笔记——Thread常用方法