Connecting Tech Pros Worldwide Help | Site Map

parse command output in variable with loop

Newbie
 
Join Date: Jan 2009
Posts: 12
#1: Mar 13 '09
would like to read and parse certain fields from multiple lines ( say lines 5 and 9 and the first and sixth fields respectively)
from the variable of the file the command output created
tried this code below but having problems parsing out_ping
Expand|Select|Wrap|Line Numbers
  1. ip_array = ('192.168.1.1', '192.168.1.1', '124.128.x.x')
  2. for i in ip_array:
  3.     out_ping = os.popen('ping' + ' ' + i, 'r+').read()
  4.     #sys.stdout.flush()
  5.     print out_ping
  6.  
  7. out_text = ('out_ping',5,9, 'r')    
  8. for line in out_text:
  9.    z = line.split()
  10. if line 5 z[0] == "Reply" and line 9 z[6] < 80ms:
  11.         #sys.stdout.writelines(z[2] + reachable + "\n")
  12.         print z[2] + reachable + "\n"  
  13. else
  14. print "congested"
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#2: Mar 13 '09

re: parse command output in variable with loop


Your first for loop appears to work OK. Then you create a tuple and iterate on it in another for loop. The first item in the tuple is the string object 'out_ping'. Look at this:
Expand|Select|Wrap|Line Numbers
  1. >>> 'out_ping'.split()
  2. ['out_ping']
  3. >>> 
The following if statement is indented incorrectly. It only checks the last iteration of the preceding for loop.

Look at the following and see if you can adapt it for your purpose:
Expand|Select|Wrap|Line Numbers
  1. import os
  2.  
  3. ip_array = ('192.168.1.1',)
  4. ping_results = []
  5. for ip in ip_array:
  6.     f = os.popen('ping %s' % (ip), 'r+')
  7.     out_ping = [item.strip() for item in f.readlines() if item.strip()]
  8.     f.close()
  9.     ping_results.append(out_ping)
  10.  
  11. for result in ping_results:
  12.     chk1 = result[4]
  13.     chk2 = int(''.join([s for s in result[8].split()[-1] if s.isdigit()]))
  14.     if chk1.startswith("Reply") and chk2 < 80:
  15.         print chk1
  16.         print result[8]
  17.  
Reply