1

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!

1
  • have you tried command = os.system('ping 127.0.0.1 >> new.txt')? Commented Sep 17, 2013 at 9:38

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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.

5 Comments

Thanks, what would you recommend over using os.system?
It's fine if os.system solution works for you. But I still edited the answer with subprocess solution.
The subprocess example above overwrites the text file even though I have used 'a' with: out = open('new.txt', 'a')
Are you sure? I tested it on my system (Mac). File is appended. That said, I think @noSkill solution is better than mine. At least until the output is small enough not to eat the memory. Still, upvote all of us :)
Yeah, it definitely over writes! Thanks for the help though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.