0

I wrote this simple script in Python:

import os
os.system("ping www.google.com")

It's working in interactive mode from cmd of windows, but seems it doesn't work if I write on IDLE (it appear a cmd black screen). This is the first problem.

The second thing that I like to do is this: I'd like to save the results of the pings in a file How can I do it?

I'm novice of Python (two days) ;) Thanks a lot.

ekostadinov
  • 6,880
  • 3
  • 29
  • 47
paolo rossi
  • 123
  • 1
  • 2
  • 7
  • 1
    You can't do it with `os.system`. That's why [the docs for `os.system`](https://docs.python.org/3/library/os.html#os.system) specifically say, "The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the [*Replacing Older Functions with the subprocess Module*](https://docs.python.org/3/library/subprocess.html#subprocess-replacements) section in the `subprocess` documentation for some helpful recipes." – abarnert Sep 08 '14 at 11:08

1 Answers1

0

you save the output using subprocess.check_output

    import subprocess
    with open('output.txt','w') as out:
        out.write(subprocess.check_output("ping www.google.com"))

output.txt

Pinging www.google.com [74.125.236.178] with 32 bytes of data:

Reply from 74.125.236.178: bytes=32 time=31ms TTL=56

Reply from 74.125.236.178: bytes=32 time=41ms TTL=56

Reply from 74.125.236.178: bytes=32 time=41ms TTL=56

Reply from 74.125.236.178: bytes=32 time=32ms TTL=56



Ping statistics for 74.125.236.178:

    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

    Minimum = 31ms, Maximum = 41ms, Average = 36ms
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46