Python,if语句中OS命令的求值输出

2024-10-03 04:30:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将下面的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

Tags: 命令版本valueosstatusshellgrephostname
2条回答

尝试子流程模块:

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

建议使用subprocess模块。
文档的以下部分具有指导意义:
replacing shell pipeline
我在此报告以供参考:

output=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]

The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.

Alternatively, for trusted input, the shell’s own pipeline support may still be used directly:

output=dmesg | grep hda

变成:

output=check_output("dmesg | grep hda", shell=True)

下面是要翻译的菜谱欧斯波本到子流程模块:
replacing os.popen()

所以你可以这样做

import subprocess

output=check_output("hastatus -sum |grep `hostname` |grep Grp| awk '{print $6}'", shell=True) 

或者

连接Popens,如上面的文档所示(可能我会这么做)。你知道吗

然后,为了测试您可以使用的输出,假设您使用的是第一种方法:

import sys
import subprocess

....
if 'ONLINE' in output:
    sys.exit(1)

相关问题 更多 >