Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,在if语句中计算OS命令的输出_Python_Shell - Fatal编程技术网

Python,在if语句中计算OS命令的输出

Python,在if语句中计算OS命令的输出,python,shell,Python,Shell,我想将下面的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

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

请尝试子流程模块:

import subprocess
value = subprocess.call("hastatus -sum |grep `hostname` |grep Grp| awk '{print $6}'")
print(value)
文档可在此处找到:
推荐的方法是使用该模块。
本文档的以下部分具有指导意义:

我在此报告以供参考:

输出=
dmesg | grep hda

变成:

p1=Popen([“dmesg”],stdout=PIPE)

p2=Popen([“grep”,“hda”],stdin=p1.stdout,stdout=PIPE)
p1.stdout.close()#如果p2退出,允许p1接收信号管道。

output=p2.communicate()[0]

启动
p2
后的
p1.stdout.close()
调用对于
p1
p1
退出之前接收
SIGPIPE
非常重要

或者,对于可信输入,仍然可以直接使用shell自己的管道支持:

输出=
dmesg | grep hda

变成:

output=check\u输出(“dmesg | grep hda”,shell=True)

下面是将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)
    

那么…是一样的吗?shell版本只返回“ONLINE”,os.popen返回“['ONLINE\n']”。这很好,但是如果“ONLINE”的值是:…谢谢,但是管道似乎被忽略了,我不知道如何用“ONLINE”来测试它。文档显示了命令和参数([“command”,“args”])。我找不到等效的管道。您可以将shell命令包装在shell脚本中。那么,通过这种方式很容易调用。不过,我不确定这是否会挫败你的努力。谢谢你的帮助。现在在shell中做这件事对我来说比较容易。