优化一下这段代码 # 获取历史数据//播报状态 def get_play_resp_DataHistory(self,ProductId,DeviceName,mintime,maxtime): try: req = models.DescribeDeviceDataHistoryRequest() params = { "ProductId": ProductId, "DeviceName": DeviceName, "MinTime": mintime, "MaxTime": maxtime, "FieldName": "play_resp" } req.from_json_string(json.dumps(params)) resp = self.client.DescribeDeviceDataHistory(req) test_str ='' for device in resp.Results: s= json.loads(str(device)) time1 = timestamp_to_datetime(int(s['Time'])) valve1 = s['Value'] str1 = str( "{} ,播报状态, Time={}, Value={}\r\n".format(DeviceName,time1,valve1)) test_str += str1 path1 = os.getcwd() # 获取当前工作目录路径 try: f = open(path1+"\\test.txt","r",encoding="utf-8") json_data = json.load(f) aa = pd.DataFrame(json_data) aa aa.to_excel("./ceshi(1).xlsx",sheet_name="测试",encoding="utf-8") except Exception as e: print("---打开异常---", e) except TencentCloudSDKException as err: print(err)
时间: 2024-02-10 09:22:19 浏览: 163
square root raised cosine impulse response.zip_RRC _impulse resp
# 获取历史数据//播报状态
import json
import os
import pandas as pd
from tencentcloud.iotexplorer.v20190423 import models
def get_play_resp_DataHistory(self,ProductId,DeviceName,mintime,maxtime):
try:
req = models.DescribeDeviceDataHistoryRequest()
params = {
"ProductId": ProductId,
"DeviceName": DeviceName,
"MinTime": mintime,
"MaxTime": maxtime,
"FieldName": "play_resp"
}
req.from_json_string(json.dumps(params))
resp = self.client.DescribeDeviceDataHistory(req)
test_str = ''
for device in resp.Results:
s = json.loads(str(device))
time1 = timestamp_to_datetime(int(s['Time']))
valve1 = s['Value']
str1 = str("{} ,播报状态, Time={}, Value={}\r\n".format(DeviceName,time1,valve1))
test_str += str1
path1 = os.getcwd() # 获取当前工作目录路径
try:
with open(path1 + "\\test.txt", "r", encoding="utf-8") as f:
json_data = json.load(f)
aa = pd.DataFrame(json_data)
aa.to_excel("./ceshi(1).xlsx", sheet_name="测试", encoding="utf-8")
except Exception as e:
print("---打开异常---", e)
except TencentCloudSDKException as err:
print(err)
优化建议:
1. 将json.dumps(params)提取到变量中,避免多次进行json编码和解码;
2. 使用with语句打开文件,不需要显式地调用f.close()方法,能够自动关闭文件;
3. 将try-except语句中的缩进调整为一致,避免代码混乱;
4. 对于异常的处理,应该尽可能地具体,而不是简单地打印异常信息。
阅读全文