By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,630 Members | 1,252 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,630 IT Pros & Developers. It's quick & easy.

parse command output in variable with loop

P: 29
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"
Mar 13 '09 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
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.  
Mar 13 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.