问题描述
我想将以下外壳评估转换为python2.6(无法升级)。 我不知道如何评估命令的输出。
这是外壳程序版本:
status=`$hastatus -sum |grep $hostname |grep Grp| awk '{print $6}'`
if [ $status != "ONLINE" ]; then
exit 1
fi
我尝试了os.popen
,它返回['ONLINE \\ n']。
value = os.popen("hastatus -sum |grep `hostname` |grep Grp| awk '{print $6}'".readlines()
print value
1楼
尝试子流程模块:
import subprocess
value = subprocess.call("hastatus -sum |grep `hostname` |grep Grp| awk '{print $6}'")
print(value)
可在此处找到文档: :
2楼
推荐的方法是使用模块。
文档的以下部分具有指导意义:
我在这里报告以供参考:
输出=
dmesg | grep hda
dmesg | grep hda
变为:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
启动
p2
之后的p1.stdout.close()
调用很重要,如果p2
在p1
之前退出,则p1
才能接收SIGPIPE
。另外,对于受信任的输入,仍然可以直接使用外壳自身的管道支持:
输出=
dmesg | grep hda
dmesg | grep hda
变为:
output=check_output("dmesg | grep hda", shell=True)
这是将os.popen转换为子流程模块的方法:
因此,在您的情况下,您可以执行以下操作
import subprocess
output=check_output("hastatus -sum |grep `hostname` |grep Grp| awk '{print $6}'", shell=True)
要么
如上面的文档中所示将Popen连接起来(可能是我会做的)。
然后,假设您正在使用第一种方法,则可以测试您可以使用的输出:
import sys
import subprocess
....
if 'ONLINE' in output:
sys.exit(1)