【问题标题】:How to save the output of os.system to .csv file?如何将 os.system 的输出保存到 .csv 文件?
【发布时间】:2022-01-13 23:22:28
【问题描述】:

在写这篇文章之前,我尝试过自己做,但放弃了。

我读了this 一个和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

我只想像这个图一样保存这些数据

【问题讨论】:

  • 嗯,你是怎么得到第二行的?看起来是为了ping同一个服务器
  • 我只跑了两次,你可以跳过。
  • 如果您想将命令的输出重定向到文件,我建议您使用subprocess 模块。您仍然需要重新格式化为 CSV 格式。
  • 感谢您的建议。我已经开始使用了。

标签: python csv save


【解决方案1】:

使用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之后)。该号码可以根据需要替换为任何其他号码。但这不会对结果造成太大的改变。

【讨论】:

  • 对不起,这对我不起作用。
  • 你得到什么输出?
  • 第一次打印(x)没什么。
  • 第一个代码是专门针对windows的,但我想你是在Linux,所以我现在已经为Linux编写了代码。见上文。
猜你喜欢
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 2022-11-28
  • 2011-10-31
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2021-07-14
相关资源
最近更新 更多