Reputation: 967
before writing this post, I tried to do it by myself but give up.
I read this one and this but I could not get it
This is the code to show us latency data:
import os
x = os.system("ping 192.168.1.1")
The output is:
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=2.47 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=2.97 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=3.02 ms
64 bytes from 192.168.1.1: icmp_seq=4 ttl=64 time=2.74 ms
64 bytes from 192.168.1.1: icmp_seq=5 ttl=64 time=2.74 ms
64 bytes from 192.168.1.1: icmp_seq=6 ttl=64 time=2.08 ms
--- 192.168.1.1 ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 5007ms
rtt min/avg/max/mdev = 2.087/2.674/3.020/0.319 ms
I would like to only save these data like this figure
Upvotes: 1
Views: 1213
Reputation: 395
Use os.popen()
rather than the os.system()
function to return the output to a variable.
os.popen()
executes the task in background and return the output, while os.system()
execute the task in a terminal.
Here is the full code to extract the ip statistics to a .csv file (Linux only) :
import os
ip = "192.168.1.1"
x = os.popen("ping -c 4 "+ip).read()
print (x)
x = x.splitlines()
x = x[len(x)-1]
x = x.replace("rtt min/avg/max/mdev = ","")
x = x.replace(" ms" , "")
x = x.replace("/" , ",")
x = ip +","+ x
file = open("newfile.csv","w")
file.write("PING,min,avg,max,mdev\n")
file.write(x)
file.close()
print(x)
print(".csv created successfully")
Note : The x = os.popen("ping -c 4 "+ip).read()
command represents that the number of times the ping will occur and end is 4(written after ping -c
). The number can replaced by any other number, as needed. But this doesn't cause much changes to the result.
Upvotes: 2