首页 > 解决方案 > Python Battery AI - 如何仅在电池连接或断开连接时记录

问题描述

我正在制作一个人工智能电池监视器,看起来就像在 iOS13 上一样,我只需要在用户连接或断开充电器插头时记录电池百分比/小时/插入。

我试图做类似的事情:

if str(plugged) == "True":
    log_file.write(current_info + "\r\n")
elif str(plugged) == "False"
      log_file.write(current_info + "\r\n")

但脚本不会停止在“True”上循环

这是我的代码的主要功能

log_file = open("activity_log.txt", "w")

while True:
    battery = psutil.sensors_battery()
            # Check if charger is plugged in or not
    plugged = battery.power_plugged

            # Check for current battery percentage
    percent = str(battery.percent)

    # Check for the current system time
    sys_time = datetime.datetime.now()

    current_info = percent + " " + str(sys_time) + " " + str(plugged)

    if str(plugged) == "True":
        log_file.write(current_info + "\r\n")

log_file.close()

github上的项目,如果你想测试或实现它:https ://github.com/peterspbr/battery-ai

标签: pythonbattery

解决方案


如果我对您的理解正确,您想在变量plugged为 True 时退出循环吗?需要考虑的是,Python 是一种字符串类型语言,也就是说,它不是同一个“True”和 True。

log_file = open("activity_log.txt", "w")
plugged = False
while not plugged:
    battery = psutil.sensors_battery()
            # Check if charger is plugged in or not
    plugged = battery.power_plugged

            # Check for current battery percentage
    percent = str(battery.percent)

    # Check for the current system time
    sys_time = datetime.datetime.now()

    current_info = percent + " " + str(sys_time) + " " + str(plugged)

    if str(plugged) == "True":
        log_file.write(current_info + "\r\n")

log_file.close() 

PD:我假设变量batery.power_plug是布尔类型。


推荐阅读