Darkshadows
Darkshadows

Reputation: 51

Output result of a ping with subprocess.call to a text file

I'm attempting to ping an IP address in Windows with Python. I want to output the result of the ping into a text file, but I don't know how to do that with the subprocess.call function. I know how to write variables to a file, but I don't know how to assign anything from the subprocess.call to a variable.

For example, if I pinged, I would want the text file to look like this

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

How would I do this?

Upvotes: 0

Views: 1897

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

If you call ping in a reasonable shell (for instance cmd.exe), you can use I/O redirection:

ping 127.0.0.1 > file

> means the output of the program is written to the given file.

If you call it as a python subprocess (not easy to derive from your question), you can use Popen:

with open('output.txt', 'w') as output:
    process = subprocess.Popen('ping 127.0.0.1', stdout=output)
    process.communicate()

Upvotes: 1

Related Questions