【问题标题】:How to get Average speed Ping in Python?如何在 Python 中获得平均速度 Ping?
【发布时间】:2021-10-11 22:34:26
【问题描述】:

嘿,我制作了一个小工具,可以在 python 中 ping 任何网站/ip。

所以我的机器人可以找到但我不想添加一个功能来获取平均值。

我的代码如下:

import os, time, requests

url = 'WEBHOOK URL'


while True:
    hostname = "google.com" 
    response = os.system("ping -c 1 " + hostname)
    if response == 0:
      print (hostname, 'is online!')
      data = {
    "content" : "Message content",
    "username" : "Author name"
}
      data["embeds"] = [
    {
        "description" : "Google is  onligne",
        "title" : "TITLE EMBEDS"
    }
]
      requests.post(url, json = data)
      time.sleep(900)
    else:
      data = {
    "content" : "Message content",
    "username" : "Author name"
}
      data["embeds"] = [
    {
        "description" : "Google is offligne",
        "title" : "TITTLE EMBEDS"
    }
]
      requests.post(url, json = data)
      print (hostname, 'is down!')
      time.sleep(900)

这段代码工作得很好,但我想通过获得平均速度来完成我的代码:

像这样:

平均速度是 ping 的结果。

当我这样做时:

print (response)

我明白了:

0

我不想得到类似的东西:

Average = 49ms

但我不知道该怎么做......

感谢您的帮助

PYTHONPING 解决的问题

【问题讨论】:

标签: python ping


【解决方案1】:

如果要捕获ping命令的o/p,os.system不是办法,请改用subprocess.Popen

from subprocess import (
    Popen,
    PIPE,
)

def run_cmd(cmd):
    try:
        proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE,)
        (out, err,) = proc.communicate()
        exitcode = proc.returncode
        return (
            out.decode("utf-8"),
            err.decode("utf-8"),
            exitcode,
        )
    except Exception as e:
        raise e

out, err_msg, exit_code = run_cmd("ping -c1 {hostname}")

现在您可以从out 申请regex 以提取您需要的信息。我不确定你是如何获得速度的,所以没有它的代码。

【讨论】:

  • 我只是将此命令的平均速度提取到 cmd 中:ping -c 4 www.stackoverflow.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 但是当我尝试添加到变量中时,它返回我 0
  • 只需将上述代码的最后一行替换为:out, err_msg,exit_code = run_cmd("ping -c 4 www.stackoverflow.com | tail -1| awk '{print $4}' | cut -d '/' -f 2") 即可完成.. 即调用run_cmd 并使用您要执行的命令作为其参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多