Home > Software design >  How to save the output of os.system to .csv file?
How to save the output of os.system to .csv file?

Time:12-10

before writing this post, I tried to do it by myself but give up.

I read enter image description here

CodePudding user response:

Use :

import os
x = os.popen('ping 198.168.1.1').read()

print (x)

to assign to a variable.

Here is the full code :

This only works for Linux system :

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.

  • Related