如何使用Python捕获ping错误? [英] How to catch ping error with Python?

查看:205
本文介绍了如何使用Python捕获ping错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的简单示例:

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

这是脚本的输出示例:

[~/python]$ python ping_stats.py
ping: cannot resolve tpeo.local: Unknown host
Print values:

None

因此,我的变量outerr为空",但是我需要一条ping: cannot resolve tpeo.local: Unknown host错误消息.我如何得到它?

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?

推荐答案

只需通过stderr=subprocess.STDOUT捕获结果中的标准错误.
另外,请使用 shlex.split ,而不要使用string.split(' '):

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]

或者:

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

这篇关于如何使用Python捕获ping错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆