Reputation: 1818
I am using subprosess to ping a server, but I want to receive the full response. In the past I have used os
to ping but this only returned 1
or 0
.
The code that I am using is:
import subprocess
p = subprocess.Popen(['ping', '8.8.8.8'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out
I would like if if the response that I would see if I had ran it from the terminal was visible. Please note that I am using -c
and not -n
because I am using linux as the OS.
I am confused as to why this does't work because when I ran similar code, it printed out the expected response:
import subprocess
p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out
The code above printed out the list of files and folders in the directory which the python script was saved in, so the code that I am using seems to be correct.
My question is, how can I have the response from pinging a server assigned to a variable that I can then print out like I can when I run ls
.
Upvotes: 2
Views: 3002
Reputation: 414335
.communicate()
waits for the child process to finish. ping
with the given arguments does not exit unless you explicitly stop it e.g., send it Ctrl+C.
Here're varous methods to stop reading process output in Python without hang.
If want to see the output while the process is still running; see Python: read streaming input from subprocess.communicate()
Upvotes: 1
Reputation:
The default ping
is a continuous process; it doesn't stop until you interrupt it, e.g. with ctrl-C. Of course, with subprocess
, ctrl-C is not possible.
subprocess.communicate
will buffer all the output in memory until the program ends (that is, never); you could use it in fact to create an out-of-memory error ;-).
If you just like a few pings, or even 1 ping, use the -c
option to ping
:
p = subprocess.Popen(['ping', '-c1', '8.8.8.8'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
If you'd like continuous polling, you could wrap this in a while
loop inside Python.
Upvotes: 3