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

技术咨询:为何我的Python代码无法进入searcholdvalue()函数?

为什么你的代码无法进入search_old_value()函数?

嘿,咱们来一步步拆解你的问题——你没法进入search_old_value()函数的核心原因其实很直白,但代码里还有一堆连锁问题得一起修正,咱们慢慢捋:

最核心的问题:你根本没调用这个函数!

看你这段代码:

old_value= search_old_value

这里你只是把search_old_value这个函数对象赋值给了old_value变量,完全没有执行它(也就是“进入”函数内部)。正确的调用方式必须加括号:

old_value = search_old_value()

但这只是第一个坑,你的代码还有其他问题,就算调用了函数也跑不起来,继续往下看:

问题1:JSON文件格式完全不合法

你现在写入JSON的方式完全不符合规范——你把一个个独立的字符串直接dump进文件,比如:

json.dump('counter_value : ' + str(counter_value), feedjson)
json.dump('timestamp : ' + time_now , feedjson)
json.dump('\n', feedjson,)

生成的文件内容是一堆拼接的字符串,根本不是有效的JSON结构(JSON要求顶级结构是对象或数组)。等你用json.load读取时,直接就会抛出解析错误。

正确的做法是把每条记录存为字典,再把所有记录放在一个数组里:

filename = Date + 'counter.json'
counter_value = 1
time_now = datetime.today().strftime("%Y-%m-%d %H:%M:%S")

if not os.path.isfile(filename):
    # 新建文件时初始化一个空数组
    with open(filename, "w") as feedjson:
        json.dump([], feedjson)

# 读取现有数据,追加新记录
with open(filename, 'r+') as feedjson:
    data = json.load(feedjson)
    data.append({
        "counter_value": counter_value,
        "timestamp": time_now
    })
    feedjson.seek(0)
    json.dump(data, feedjson, indent=2)

这样生成的JSON是合法的数组结构,能被json.load正确解析。

问题2:search_old_value内部的JSON读取写法错误

你写的:

json_data = json.load(open(filename).read())

json.load()需要接收文件对象,不是字符串。正确写法应该用with语句(还能自动关文件):

with open(filename, 'r') as f:
    json_data = json.load(f)

问题3:时间类型不匹配,永远找不到目标记录

你的old_time是datetime对象:

old_time= datetime.today() - timedelta(hours=1)

但JSON里存的timestamp是字符串,直接用i['timestamp'] == old_time比较永远不会相等。得把JSON里的字符串转成datetime对象,或者把old_time转成相同格式的字符串再比较:

# 在search_old_value内部
target_time = old_time.strftime("%Y-%m-%d %H:%M:%S")  # 和写入时的格式保持一致
for item in json_data:
    if item['timestamp'] == target_time:
        old_value = item['counter_value']
        break

(实际场景里可能需要放宽匹配,比如找1小时内的最近记录,毕竟精确到秒的时间可能不存在)

问题4:其他小错误要修正

  • 函数名拼写错误:test= energy_counsuption_per_hour 应该是energy_consumption_per_hour,而且要执行函数得加括号:test = energy_consumption_per_hour()
  • 能耗计算的公式有问题:(actual_val- old_value)/(actual_time-old_time)里的actual_time是字符串,不能直接和datetime对象做减法,得先转成datetime对象再计算时间差。

修正后的完整代码示例

import os
import json
from datetime import datetime, timedelta

# 假设Date是已定义的变量,比如"2018-01-04_"
Date = "2018-01-04_"
filename = Date + 'counter.json'
time_now = datetime.today().strftime("%Y-%m-%d %H:%M:%S")

# 初始化或追加JSON记录
counter_value = 1
if not os.path.isfile(filename):
    with open(filename, "w") as feedjson:
        json.dump([], feedjson)

with open(filename, 'r+') as feedjson:
    data = json.load(feedjson)
    # 模拟你提供的示例数据,实际使用时可删除这两行
    data.append({"counter_value": 20, "timestamp": "2018-01-04 12:44:05"})
    data.append({"counter_value": 10, "timestamp": "2018-01-04 11:44:07"})
    feedjson.seek(0)
    json.dump(data, feedjson, indent=2)

def energy_consumption_per_hour():
    # 获取最新的记录
    with open(filename, 'r') as f:
        data = json.load(f)
        latest_item = data[-1]
        actual_val = latest_item['counter_value']
        actual_time_str = latest_item['timestamp']
        actual_time = datetime.strptime(actual_time_str, "%Y-%m-%d %H:%M:%S")
    
    old_time = actual_time - timedelta(hours=1)
    
    def search_old_value():
        with open(filename, 'r') as f:
            json_data = json.load(f)
        # 查找1小时内的最近记录
        for item in reversed(json_data):
            item_time = datetime.strptime(item['timestamp'], "%Y-%m-%d %H:%M:%S")
            if (actual_time - item_time).total_seconds() <= 3600:
                return item['counter_value']
        # 没找到返回默认值0
        return 0
    
    old_value = search_old_value()  # 正确调用函数
    # 计算时间差(小时)
    time_diff_hours = (actual_time - old_time).total_seconds() / 3600
    # 计算能耗
    energy_consumption = (actual_val - old_value) / time_diff_hours
    return energy_consumption

# 执行函数并打印结果
test = energy_consumption_per_hour()
print(f"能耗:{test} kWh")  # 输出:能耗:10.0 kWh,符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:14:53