【问题标题】:Pinging in Python with Feedback [duplicate]使用反馈在 Python 中进行 Ping [重复]
【发布时间】:2015-09-16 21:03:28
【问题描述】:

所以我是 Python 中的菜鸟,这很痛苦,但我正试图想出一种方法来 PING 一个站点,然后吐出一个“if/else”子句。

到目前为止,我有这个:

import subprocess 
command = "ping -c 3 www.google.com"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE,     
stderr=None, shell=True)

#Launch the shell command:
output = process.communicate()

print output[0]

下面是我出错的地方,这是第二部分:

if output == 0.00
print "server is good"

else
print "server is hosed"

显然第 2 部分没有成功。

我的问题是,我如何“读取”来自 ping 的结果(毫秒) icmp_seq=0 ttl=44 时间=13.384 毫秒

并说“如果 ping 时间快于 12.000 毫秒,则执行此操作” 别的 “做那个”

现在我只是在打印,但很快我想改变它,所以其他的东西。

【问题讨论】:

  • 为什么不把get请求当作心跳呢?

标签: python subprocess ping


【解决方案1】:

subprocess.Popen 通常不是您想要的。所有简单任务都有方便的功能。就你而言,我想你想要subprocess.check_output:

output = subprocess.check_output(command, shell=True)

有很多方法可以解析得到的输出字符串。我喜欢正则表达式:

matches = re.findall(" time=([\d.]+) ms", output)

re.findall 返回 liststr,但您希望将其转换为单个数字,以便进行数值比较。使用float()构造函数将strs转换为floats,然后计算平均值:

matches = [float(match) for match in matches]
ms = sum(matches)/len(matches)

示例程序:

import subprocess
import re

# Run the "ping" command
command = "ping -c 3 www.google.com"  # the shell command
output = subprocess.check_output(command, shell=True)

# And interpret the output
matches = re.findall(" time=([\d.]+) ms", output)
matches = [float(match) for match in matches]
ms = sum(matches)/len(matches)

if ms < 12:
     print "Yay"
else:
     print "Boo"

请注意,ping 的输出不是标准化的。在我的机器上,运行 Ubuntu 14.04,上面的正则表达式有效。在您的机器上,运行一些其他操作系统,它可能需要有所不同。

【讨论】:

  • 谢谢 - 所以 Popen 就像实际打开终端一样,对吗?我注意到当我这样做时,它会显示 3 条 ping 线以供查看。使用 check_output,它只显示“Yay”或“Boo”。脚本有没有办法打印出 ping 行?
  • 是的,所有subprocess 系列函数都运行您可能在终端上调用的命令。 check_output("ping") 返回的文本与在命令提示符下键入 ping 的结果相同。
  • 如果您希望我的示例程序显示 ping 的整个输出,请在末尾添加 print output
  • 谢谢!我真的很讨厌问这些简单的问题,但我参加了一个简短的 python 课程,两个月没有做任何事情(所以我忘记了大部分),通常对我的问题的回复是包含这么多技术的文章的 url行话,我读后比以前更困惑。所以非常感谢你......我敢肯定还有更多问题。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-13
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多