Kittystone
Kittystone

Reputation: 671

How to print a statement one time in a loop

I have the following code :

  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"

So the thing is, this code works fine. All I want now is just to have the following type of output if a IP is found with the mentioned condition:

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

But the above code prints

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

Upvotes: 0

Views: 68

Answers (2)

RaminNietzsche
RaminNietzsche

Reputation: 2791

Store your data in a list:

 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

Upvotes: 1

justderb
justderb

Reputation: 2854

You can simply hold a stateful variable called first. Once you print the line, toggle first to False so it doesn't execute again.

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"

This isn't the prettiest way of doing it, but it will do the behavior you want. One nice thing, though, is that it adds very little memory/complexity to the program. Another way would be to hold every result in a list and print it at the end - but that would require holding a reference to every result until the very end. If your program is generating a lot of results, that can take up a lot of memory. This only holds a boolean...

Upvotes: 2

Related Questions