【问题标题】:How to I get data from tabulated data then print a message如何从表格数据中获取数据然后打印一条消息
【发布时间】:2021-01-12 08:24:51
【问题描述】:

在使用 get_metric_statistics 将来自 cloudwatch 的响应制成表格后,我得到了以下输出。我想添加验证,如果任何 Sum 大于 0,它将打印一条消息,说明存在错误。如果所有 Sum 都等于 0,它会说没有错误。

> +| Timestamp              |   Sum | Unit   | |
> 2021-01-12T09:31:00+00:00 |     0 | Count  | |
> 2021-01-12T09:30:00+00:00 |     0 | Count  | |
> 2021-01-12T09:33:00+00:00 |     0 | Count  | |
> 2021-01-12T09:29:00+00:00 |     0 | Count  | |
> 2021-01-12T09:32:00+00:00 |     0 | Count  | |
> 2021-01-12T09:28:00+00:00 |     0 | Count  |
> +---------------------------+-------+--------+

下面是我的python脚本

import json
import boto3
import os
from datetime import datetime, timedelta
from tabulate import tabulate

client = boto3.client("lambda")


class DateTimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()

        return json.JSONEncoder.default(self, o)


client = boto3.client("cloudwatch")
response = client.get_metric_statistics(
    Namespace="AWS/Lambda",
    MetricName="Errors",
    Dimensions=[{"Name": "FunctionName", "Value": "XXX"}],
    StartTime=datetime.utcnow() - timedelta(seconds=360),
    EndTime=datetime.utcnow(),
    Period=60,
    Statistics=["Sum"],
)

message = json.dumps(response, cls=DateTimeEncoder)
message2 = json.loads(message)
message3 = message2["Datapoints"]
message4 = tabulate(message3, headers="keys", tablefmt="psql")
print(message4)

我知道这看起来很简单,但请帮忙。谢谢!

【问题讨论】:

  • 请点击链接查看截图
  • 请将您的代码和输出作为代码而不是屏幕截图。
  • @Maurice 我编辑了这篇文章。我希望你能帮助我。谢谢!
  • 添加类似:for message in message2: if message["Sum"] > 0: print("Some error") else: pass 这样如果您没有收到反馈,则说明没有错误。如果某些Sum 大于0,它会告诉你Some error
  • @grumpyp 没错,将其添加为答案,您将获得支持 ;-)

标签: python-3.x conditional-statements amazon-cloudwatch tabulate


【解决方案1】:

添加类似:

for message in message2:
   if message["Sum"] > 0:
      print("Some error occured")
   else:
      pass

因此,如果您没有收到反馈,则没有错误。如果某些Sum 大于0,它会告诉你Some error

【讨论】:

  • 感谢@grumpyp,但添加代码时出现此错误。回溯(最后一次调用):文件“.\geterrorV5.py”,第 36 行,在 中 if message["Sum"] > 0: TypeError: string indices must be integers
  • 在 message3 中将其更改为 for message2 时有效: if message2["Sum"] > 0: print("Some error occurred") else: pass
  • 有没有办法只打印一行消息?就像任何总和大于 0 一样,它会打印发生了一些错误?因为使用上面的代码,它会打印多行,根据大于 0 的总和数发生一些错误。
  • 当然可以。您可以在if message["Sum"] > 0: 语句之后添加error = True。然后你可以通过if error is True: print("Some error occured") 检查这个变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 2014-09-23
  • 2016-03-08
  • 2017-05-28
  • 1970-01-01
相关资源
最近更新 更多