问题
Here is my simple example:
import subprocess
cmd = 'ping something.local -c 1'
tail = 'tail -n 3'
ping = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE)
tail = subprocess.Popen(tail.split(' '), stdin=ping.stdout, stdout=subprocess.PIPE)
ping.stdout.close()
out, err = tail.communicate()
print 'Print values:'
print out
print err
And here is the output example of script:
[~/python]$ python ping_stats.py
ping: cannot resolve tpeo.local: Unknown host
Print values:
None
So, my variables out
and err
are "empty", but I need a ping: cannot resolve tpeo.local: Unknown host
error message. How I can get it?
回答1:
Just capture standard error in the result via stderr=subprocess.STDOUT
.
Also, use shlex.split rather than string.split(' ')
:
import subprocess
import shlex
cmd = 'ping something.local -c 1'
ping = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out = ping.communicate()[0]
Or:
import subprocess
import shlex
cmd = 'ping unknown -c 1'
ping = subprocess.Popen(shlex.split(cmd), stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
out, err = ping.communicate()
print out
print err
来源:https://stackoverflow.com/questions/40467105/how-to-catch-ping-error-with-python