python - 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
解决方案
如果我对您的理解正确,您想在变量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
是布尔类型。
推荐阅读
- python - Python 3 OOP——“super().__init__()”到底去哪儿了?
- apache-kafka - 如何使用 writeStream 将 Spark 流传递给 kafka 主题
- android - 使用 WorkManager 和 Notification Service 在服务器上上传媒体
- java - 在 Spring 中向客户端发送字段元数据
- c - C - 将非常大文件中的行插入数组
- python - 如何减少 sqlalchemy 用于连接数据库和选择数据的时间
- rest - 使用 keycloak rest admin apis 获取给定部分 url 路径或基于正则表达式模式的资源
- java - com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造`javax.xml.bind.JAXBElement`的实例
- python - Luis python SDK 话语添加
- jmeter - 为什么在 Jmeter 中请求时添加“&”?