我想将以下shell评估转换为python2.6(无法升级)。我无法弄清楚如何评估命令的输出。
这是shell版本:
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
答案 0 :(得分:0)
尝试子进程模块:
import subprocess
value = subprocess.call("hastatus -sum |grep `hostname` |grep Grp| awk '{print $6}'")
print(value)
文档可在此处找到: https://docs.python.org/2.6/library/subprocess.html?highlight=subprocess#module-subprocess
答案 1 :(得分:0)
推荐的方法是使用subprocess模块
文档的以下部分具有指导意义:
replacing shell pipeline
我在此报告以供参考:
输出=
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]
启动
p1.stdout.close()
后的p2
电话非常重要,以便p1
在SIGPIPE
之前p2
退出p1
时收到dmesg | grep hda
。或者,对于可信输入,shell自己的管道支持可能仍然可以直接使用:
输出=
output=check_output("dmesg | grep hda", shell=True)
变为:
import subprocess output=check_output("hastatus -sum |grep `hostname` |grep Grp| awk '{print $6}'", shell=True)
这里是将os.popen转换为子进程模块的方法:
replacing os.popen()
因此,在您的情况下,您可以执行类似
的操作import sys
import subprocess
....
if 'ONLINE' in output:
sys.exit(1)
或
如上文所述(可能是我会做的),将Popens连接在一起。然后测试你可以使用的输出,假设你正在使用第一种方法:
MjAxNi0wMS0wNVQwOTowMDowMA==