在写这篇文章之前,我试着自己写,但放弃了。
这是向我们展示延迟数据的代码:
import os
x = os.system("ping 192.168.1.1")产出如下:
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我只想把这些数据保存成这样

发布于 2021-12-09 06:22:52
使用os.popen()而不是os.system()函数将输出返回给变量。
os.popen()在后台执行任务并返回输出,而os.system()则在终端中执行任务。
下面是将ip统计信息提取到.csv文件(仅限Linux)的完整代码:
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")注意事项:x = os.popen("ping -c 4 "+ip).read()命令表示ping发生和结束的次数为4次(写在ping -c之后)。该数字可以根据需要被任何其他数字替换。但这不会对结果造成太大的变化。
https://stackoverflow.com/questions/70284655
复制相似问题