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

Python无需print语句输出JSON内容的方法(PRTG自定义传感器适配)

PRTG自定义传感器Python脚本无print输出JSON的解决办法

核心方案

直接通过sys.stdout写入JSON字符串,避开print语句可能带来的格式干扰。PRTG会读取脚本的标准输出,只要把符合要求的JSON直接输出到标准输出即可。

具体实现步骤

  • 导入sys和json模块,前者用于操作标准输出,后者处理JSON序列化
  • 从Rubrik API获取数据并提取所需字段,组装成PRTG要求的JSON结构
  • 使用sys.stdout.write()输出序列化后的JSON字符串
  • 调用sys.stdout.flush()强制刷新输出缓冲区,确保PRTG能立即获取完整内容

代码示例

import json
import sys
import requests

# 调用Rubrik API获取数据
rubrik_api_url = "https://your-rubrik-api-endpoint"
response = requests.get(rubrik_api_url, auth=("username", "password"))
rubrik_data = response.json()

# 提取需要的字段,组装PRTG格式的JSON
prtg_output = {
    "prtg": {
        "result": [
            {
                "channel": "快照数量",
                "value": rubrik_data.get("snapshot_count", 0),
                "unit": "Count"
            },
            {
                "channel": "可用存储",
                "value": rubrik_data.get("available_storage", 0),
                "unit": "Bytes"
            }
        ]
    }
}

# 输出JSON到标准输出
sys.stdout.write(json.dumps(prtg_output))
sys.stdout.flush()

注意事项

  • 必须严格遵循PRTG的JSON格式要求:外层必须包含prtg键,其下的result数组是每个监控指标的具体数据,每个指标需要channel(通道名)、value(数值)等字段
  • 避免在脚本中产生任何额外输出(比如日志、报错信息),否则会破坏JSON结构导致PRTG识别失败
  • 如果需要处理异常,建议将错误信息封装到PRTG的error字段中,示例如下:
# 异常处理示例
try:
    # API调用和数据处理逻辑
except Exception as e:
    error_output = {
        "prtg": {
            "error": 1,
            "text": f"获取Rubrik数据失败: {str(e)}"
        }
    }
    sys.stdout.write(json.dumps(error_output))
    sys.stdout.flush()

示例输出JSON

{
    "prtg": {
        "result": [
            {
                "channel": "快照数量",
                "value": 42,
                "unit": "Count"
            },
            {
                "channel": "可用存储",
                "value": 53687091200,
                "unit": "Bytes"
            }
        ]
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:54:14