gpt4 book ai didi

python 2.7 : Using subprocess and a For Loop to output results

转载 作者:太空宇宙 更新时间:2023-11-04 12:39:00 25 4
gpt4 key购买 nike

我有一个脚本可以检查多个主机的字符串模式(在这种情况下它会寻找“平台”。我想添加到这个程序中,让它在找不到该搜索模式时打印一些东西。有人可以帮忙吗指引我正确的方向?例如,如果它没有找到任何“平台”,那么它不会打印出来,而是打印“我们找不到那个主机!”

#!/usr/bin/python

import commands, os, string
import sys
import fileinput
import subprocess
from subprocess import Popen, PIPE
import shlex


nodename = raw_input("Enter the hostname: ")

hostname=['hostA', 'hostB', 'hostC']

for i in hostname:
print "Checking Host List..."

cmd = "ls -l" + hostname
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()

if out.find("Platform") > -1:
print out
break

最佳答案

类似的东西应该可以完成工作:

#!/usr/bin/python
import commands, os, string
import sys
import fileinput
import subprocess
from subprocess import Popen, PIPE
import shlex


nodename = raw_input("Enter the hostname: ")

hostname=['hostA', 'hostB', 'hostC']

for i in hostname:
print "Checking Host List..."

cmd = "ls -l "+i
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out

if out.find("Platform") > -1:
print out
break

if i == hostname[-1]:
print "We could not find that host!"

hostname[-1] 实际上是 hostname 列表最后一个元素的快捷方式。因此,只有当您到达 hostname 列表的最后一个元素并且它不包含 "Platform" 时,您才会进入最后一个 if block 。

关于 python 2.7 : Using subprocess and a For Loop to output results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40775676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com