-2

I am looking to write two python scripts; one to ping an IP, and store the ping results to a file, and one to extract and average the ping times from the created .txt file. (Please note that all I really need to log are the ping times) (My platform is the Pi if it helps)

Below is the line of code which I plan to use to store the ping results in a text file (Obviously in my program I have put this in an infinity loop with a delay so it doesn't ping too often)

command = os.system('ping 127.0.0.1 >> pingresults.txt')

I am stuck on how access this file, and then to parse this file into just the useful data? (Please bear in mind that I am a serious amateur)

I am wondering if when I initially log the data into the file, if I can filter it for just the ping time. That would make averaging them later much easier.

If you have any suggestions of commands of interest, or tricks, or implementations, that would be great!

Pang
  • 9,564
  • 146
  • 81
  • 122
  • See [this answer](http://stackoverflow.com/a/316974/1084416) to [Ping a site in Python?](http://stackoverflow.com/questions/316866/ping-a-site-in-python). – Peter Wood Oct 07 '15 at 19:03
  • See the `open` function as well as the `str` methods and the `re` module. – MisterMiyagi Oct 07 '15 at 19:05
  • You can do this in a bash one-liner - [see this question.](http://stackoverflow.com/questions/9634915/extract-average-time-from-ping-c) – Kyle Pittman Oct 07 '15 at 19:09

1 Answers1

0

I'll take this in basic steps, entirely in Python, ignoring Python "tricks":

Open the file:

f = open("pingresults.txt", "r")
time_list = []
for line in f:
    # Ping time is in the penultimate field, 5 chars in.
    field_list = line.split(' ')
    ping_time = field_list[-2][5:]
    time_list.append(field_list[-1])   # add last field to end of time_list

print sum(time_list) / float(len(time_list))
Prune
  • 76,765
  • 14
  • 60
  • 81
  • Note also that you can easily do the field extraction with a simple command (awk?) to grab the 7th field, strip off the leading "time=", and accumulate both count and running sum. Divide at the end. as @monkey says, this is a one-liner. – Prune Oct 07 '15 at 20:32
  • I would like to repost the code you have just given, with the comments of how I understand it functioning, and note the lines of code that I don't understand. I would very much appreciate it if you could confirm my understand and provide a brief explanation of the lines which I am unsure of. – user5410008 Oct 07 '15 at 20:37
  • StackOverflow is not the place to get an introductory tutorial to Python syntax. Please search on line for an introduction that fits your learning style. – Prune Oct 07 '15 at 21:21