如何在循环中一次打印语句

时间:2017-04-18 05:25:04

标签: python

我有以下代码:

  for nodeid,nodeip in zip(node['id'], node['ip']):
          nodeurl = url.format(nodeid, nodeip)
          x = requests.get(nodeurl,headers=headers , auth=('admin', '0p3nNM$2015'))
          parsed = json.loads(x.content)
          ##print json.dumps(parsed, indent=4, sort_keys=True)
          for i in parsed["service"]:
              #print i["serviceType"]["name"]

              if i["serviceType"]["name"]=="SSH":
                 print "OpenNMS BOT Found the following IP: " ## How to print it just ONCE
                 print nodeip
                 slack.chat.post_message(slack_channel,">>>"+nodeip,username='OPENNMS_FRA_BOT')
              else:
                 print "No IP found with SSH running"

所以问题是,这段代码运行正常。 全部我现在想要的是,如果找到具有上述条件的IP,则具有以下类型的输出:

OpenNMS BOT Found the following IP:
10.0.0.1
10.0.0.2
10.0.0.3
.
.
.
so on

但上面的代码打印

OpenNMS BOT Found the following IP:
10.0.0.1
OpenNMS BOT Found the following IP:
10.0.0.2
OpenNMS BOT Found the following IP:
10.0.0.3
.
.
.
so on

2 个答案:

答案 0 :(得分:2)

您可以简单地保存一个名为first的有状态变量。打印该行后,将first切换为False,以便它不会再次执行。

first = True
for nodeid,nodeip in zip(node['id'], node['ip']):
      nodeurl = url.format(nodeid, nodeip)
      x = requests.get(nodeurl,headers=headers , auth=('admin', '0p3nNM$2015'))
      parsed = json.loads(x.content)
      ##print json.dumps(parsed, indent=4, sort_keys=True)
      for i in parsed["service"]:
          #print i["serviceType"]["name"]

          if i["serviceType"]["name"]=="SSH":
             if first:
                 print "OpenNMS BOT Found the following IP: "
                 first = False
             print nodeip
             slack.chat.post_message(slack_channel,">>>"+nodeip,username='OPENNMS_FRA_BOT')
          else:
             print "No IP found with SSH running"

这不是最漂亮的方式,但它会做你想要的行为。但是,一件好事是它为程序增加了很少的内存/复杂性。另一种方法是将每个结果保存在列表中并在最后打印 - 但这需要保留对每个结果的引用直到最后。如果你的程序产生了很多结果,那么会占用大量内存。这只包含一个布尔值......

答案 1 :(得分:1)

将您的数据存储在列表中:

 node_list = []
 ...
         for i in parsed["service"]:
              if i["serviceType"]["name"]=="SSH":
                 node_list.append(nodeip)
 ...
 print "OpenNMS BOT Found the following IP: "
 for item in node_list:
     print item