Skip to main content
 首页 » 编程设计

用于测量电池时间的python脚本

2025年05月04日12落叶

我正在寻找一个脚本来记录电池时间(即笔记本电脑使用电池运行的总时间)。我想我会尝试用 python 写一个。我是 python 的初学者,并使用来自该站点的大量示例想出了这个:D

#!/usr/bin/env python 
 
import subprocess, os 
from datetime import datetime 
 
time = (datetime.now()).strftime('%H:%M:%S') 
date = (datetime.today()).strftime('%d/%m/%y') 
 
def start(x): 
    if x[2] == 'Discharging' and int(x[3][:-1]) in range(98, 101): 
 
        batt_log = open('/home/saad/Code/batt_log', 'w') 
        batt_log.write(time + '%s' %(os.linesep)) 
        batt_log.close() 
 
def end(x): 
    if x[2] == 'Discharging' and int(x[3][:-1]) in range(1, 11): 
 
        batt_log = open('/home/saad/Code/batt_log', 'a') 
        batt_log.write(time) 
        batt_log.close() 
 
def main(): 
 
    output = subprocess.check_output('acpi -b', shell=True) 
    l = (output.replace(',', '')).split(' ') 
 
    if not (l[2] in ['Charging', 'Full'] or int(l[3][:-1]) in range(11, 98)): 
        start(l) 
        end(l) 
        ts = []      
        batt_log = open('/home/saad/Code/batt_log', 'r') 
        all_lines = batt_log.readlines() 
        for line in all_lines: 
            ts.append(line.replace(os.linesep, '')) 
 
        if len(ts) > 1: 
            FMT = '%H:%M:%S' 
            tdelta = datetime.strptime(ts[1], FMT) - datetime.strptime(ts[0], FMT) 
            batt_store = open('/home/saad/Code/batt_store', 'a') 
            batt_store.write(date + '\nTotal Time: ' + str(tdelta) + '\n') 
            batt_store.close() 
 
    batt_store = open('/home/saad/Code/batt_store', 'r')     
    all_lines = batt_store.readlines() 
    print "Last Battery Time:", all_lines[-1][-8:] 
 
if __name__ == '__main__': 
    main() 

脚本确实有效,但我希望它更好。它使用系统 acpi 命令获取电池统计信息,将它们写入一个文件 (batt_log) 以存储开始和结束时间,然后从该文件中读取,计算时间差并将其写入另一个文件 (batt_store)。作为一个进程,我每 5 分钟运行一次。

我想做的可能是使用更少的文件 I/O 操作,并找到一种在程序中持久存储值的方法。欢迎任何想法。

请您参考如下方法:

通过命令获取数据要容易得多。本质上,acpi 命令所做的是在/dev/中的特定文件节点上打开一个文件描述符。您可以查看 dbus 接口(interface)以获取信息。

关于文件的打开和关闭,您可以再次使用像 dbus 或 gconf 这样的服务,但编写文件更容易。