如何将 os.system 的输出保存到 .csv 文件?
How to save the output of os.system to .csv file?
在写这个post之前,我试着自己做但是放弃了。
我读了this one and this但是我没看懂
这是向我们显示延迟数据的代码:
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
我只想像这个图那样保存这些数据
使用 os.popen()
而不是 os.system()
函数 return 输出到变量。
os.popen()
在后台执行任务并 return 输出,而 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
之后)。根据需要,该号码可以替换为任何其他号码。但这不会对结果造成太大的改变。
在写这个post之前,我试着自己做但是放弃了。
我读了this one and this但是我没看懂
这是向我们显示延迟数据的代码:
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
我只想像这个图那样保存这些数据
使用 os.popen()
而不是 os.system()
函数 return 输出到变量。
os.popen()
在后台执行任务并 return 输出,而 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
之后)。根据需要,该号码可以替换为任何其他号码。但这不会对结果造成太大的改变。