1: import commands
2:
3: ret, output = commands.getstatusoutput('ls')
4: print ret
5: print output
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的commands模块获取系统命令的执行结果及状态码,提供了获取命令执行输出和判断命令执行是否成功的示例代码,并展示了一个获取网卡IP地址的具体应用案例。

7980

被折叠的 条评论
为什么被折叠?



