[我正在使人造智能电池监视器看起来像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
如果我正确理解了您想在变量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
是布尔类型。
我可能已经弄清楚了您要做什么:您想在电池插头状态改变时记录信息。您遇到了麻烦,因为您没有做任何事情来跟踪电池是否已插入。请尝试以下操作:
was_plugged = battery.power_plugged
while True:
...
if battery.power_plugged != was_plugged:
log_file.write(current_info + "\r\n")
was_plugged = battery.power_plugged
请阅读有关基本Python类型的更多教程。很难遵循间接检查值的方式:您将布尔值转换为文本,然后针对结果字符串进行了检查:
if str(plugged) == "True":
您需要的是直接布尔测试:
if plugged: