How to catch ping error with Python?

南楼画角 提交于 2019-12-12 04:34:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!