【问题标题】:How to catch ping error with Python?如何用 Python 捕获 ping 错误?
【发布时间】:2017-03-20 21:50:43
【问题描述】:

这是我的简单示例:

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 错误消息。我怎样才能得到它?

【问题讨论】:

  • 使用 os.system 代替 Popen。然后查看响应码
  • 那么,用subprocess.Popen是不是不可能了?

标签: python ping


【解决方案1】:

只需通过stderr=subprocess.STDOUT 捕获结果中的标准错误。
另外,请使用shlex.split 而不是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

【讨论】:

  • 以管道| tail -n 3 为例?
猜你喜欢
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2022-11-10
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多