0

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?

1 Answers1

1

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()
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • *subprocess.check_output* will be even simpler – volcano Feb 10 '15 at 17:55
  • Yes, I'm calling it as a Python subprocess. Sorry if that wasn't clear. – Darkshadows Feb 11 '15 at 00:03
  • @volcano: no. `check_output()` is *not* appropriate here. – jfs Feb 11 '15 at 02:09
  • @Darkshadows: you don't need `.communicate()` here. You could use `subprocess.check_call(['ping', '127.0.0.1'], stdout=output)` instead. If you need to interrupt `ping` process; see [ping for indefinite amount of time and get its output in Python](http://stackoverflow.com/q/27994854/4279) – jfs Feb 11 '15 at 02:11
  • @J.F.Sebastian, care to explain why _check_output()_ is not appropriate? – volcano Feb 11 '15 at 05:35
  • OP wants to redirect the output to a file. `check_output()` returns the output as a string. – jfs Feb 11 '15 at 05:37