You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python ping监控脚本变量返回值不正确的问题

问题根源

os.system()函数仅会返回命令的执行退出状态码:命令执行成功返回0,执行失败返回非0值,不会返回命令行打印的标准输出内容,因此你拿到的ping变量永远是0,和实际的延迟数值无关。

修复方案

改用subprocess模块捕获命令的标准输出即可,修正后的完整代码如下:

import os, time, requests, subprocess

url = 'WEBHOOK URL'

while True:
    hostname = "google.com" # 替换为你的目标主机
    # 检测主机连通性
    response = os.system(f"ping -c 1 {hostname}")    
    if response == 0:
        print(hostname, 'est en ligne!')
        # 捕获ping命令的输出结果,解码为字符串并去除多余空白字符
        ping_output = subprocess.check_output(f"ping -c 4 {hostname} | tail -1 | awk -F '/' '{{print $5}}'", shell=True)
        ping_val = ping_output.decode('utf-8').strip()
        data = {
            "content" : f"Service online with ping of {ping_val}ms",
            "username" : "Ping Bot" 
        }
        requests.post(url, json = data)
    # 可根据需求调整检测间隔,单位为秒
    time.sleep(60)

改动说明

  • 新增导入subprocess模块,用于捕获命令行输出
  • 用subprocess.check_output()替代原来的os.system()获取ping延迟数值,返回的字节流需要通过decode('utf-8')转为字符串,再用strip()去除末尾的换行、空格等多余字符
  • 新增休眠逻辑,避免循环执行频率过高占用过多资源,可根据需求调整间隔时长

提示:如果运行环境为Windows,需要将ping命令的-c参数改为-n,同时tail、awk命令需要对应替换为Windows下的适配逻辑。

内容的提问来源于stack exchange,提问作者Akyna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 20:36:04