xcc140
xcc140

Reputation: 13

Logging ping results python?

I can use the ping command and save the output using the following line:

command = os.system('ping 127.0.0.1 > new.txt')

However each time the script is run the text file is overwritten so I only have the last ping saved. I have looked into logging but cannot find a way to save the outputs of the ping requests into a text file without over writing.

I have tried:

logging.debug(command = os.system('ping 127.0.0.1'))

But this throws up an error with: debug() takes at least 1 argument (0 given)

Any help would be appreciated, thanks!

Upvotes: 1

Views: 7774

Answers (2)

noSkill
noSkill

Reputation: 68

You could get result of subprocess.check_output and write it to a file:

import subprocess
result = subprocess.check_output(['ping', '127.0.0.1'])
with open("new.txt", "a") as myfile:
    myfile.write(result)

Upvotes: 2

ash
ash

Reputation: 652

If you insist on using os.system, then simply use >> redirection:

command = os.system('ping 127.0.0.1 >> new.txt')

This would append new data to new.txt instead of overwriting it.

Another solution is to use subprocess module and manage file handler manually. This has the advantage of skipping the shell (it's faster and in some cases safer):

import subprocess
out = open('new.txt', 'a')
subprocess.call(['ping', '127.0.0.1'], stdout = out)
out.close()

Notice that you can do something else with stdout. For example, save it to string.

Upvotes: 2

Related Questions