modify scripts
This commit is contained in:
@ -1,5 +1,6 @@
|
||||
import requests
|
||||
import time
|
||||
import json
|
||||
import sys
|
||||
|
||||
# 企业微信相关信息
|
||||
@ -43,6 +44,53 @@ def send_message(access_token, message, touser=None, toparty=None, totag=None):
|
||||
else:
|
||||
print(f"消息发送失败: {result.get('errmsg')}")
|
||||
|
||||
def pretty_print_json(data, n=10, indent=4, sort_keys=False):
|
||||
"""
|
||||
以美化格式打印数组的前n个元素,其他元素用"..."表示
|
||||
|
||||
参数:
|
||||
- data: 要打印的数据(应为数组)
|
||||
- n: 要显示的元素数量
|
||||
- indent: 缩进空格数
|
||||
- sort_keys: 是否按键排序
|
||||
"""
|
||||
try:
|
||||
# 处理非数组数据
|
||||
if not isinstance(data, list):
|
||||
formatted = json.dumps(data, indent=indent, ensure_ascii=False, sort_keys=sort_keys)
|
||||
return formatted
|
||||
|
||||
# 复制原始数据,避免修改原数组
|
||||
data_copy = data.copy()
|
||||
|
||||
# 切片取前n个元素
|
||||
first_n_elements = data_copy[:n]
|
||||
|
||||
# 如果数组长度超过n,添加"..."标记
|
||||
if len(data) > n:
|
||||
result = first_n_elements + ["... ({} more elements)".format(len(data) - n)]
|
||||
else:
|
||||
result = first_n_elements
|
||||
|
||||
# 格式化输出
|
||||
formatted = json.dumps(result, indent=indent, ensure_ascii=False, sort_keys=sort_keys)
|
||||
return formatted
|
||||
|
||||
except TypeError as e:
|
||||
print(f"错误:无法格式化数据。详情:{e}")
|
||||
return str(data)
|
||||
except Exception as e:
|
||||
print(f"格式化时发生意外错误:{e}")
|
||||
return str(data)
|
||||
|
||||
def is_json(s):
|
||||
"""判断字符串是否可以解析为JSON"""
|
||||
try:
|
||||
json.loads(s)
|
||||
return True
|
||||
except json.JSONDecodeError:
|
||||
return False
|
||||
|
||||
# 主函数
|
||||
def main(report_content=None):
|
||||
# 模拟数据报表内容
|
||||
@ -51,7 +99,16 @@ def main(report_content=None):
|
||||
else:
|
||||
# 处理转义字符
|
||||
report_content = report_content.encode().decode('unicode_escape')
|
||||
|
||||
|
||||
# 判断是否为JSON并格式化
|
||||
if is_json(report_content):
|
||||
try:
|
||||
parsed_data = json.loads(report_content)
|
||||
report_content = pretty_print_json(parsed_data)
|
||||
except Exception as e:
|
||||
print(f"JSON解析或格式化失败: {e}")
|
||||
# 解析失败时保持原始内容
|
||||
|
||||
# 获取 access_token
|
||||
access_token = get_access_token()
|
||||
if access_token:
|
||||
|
||||
Reference in New Issue
Block a user