2

我正在寻找一个脚本来记录电池时间(即笔记本电脑使用电池运行的总时间)。我想我会用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 操作并找到一种在程序中持久存储值的方法。欢迎任何想法。

4

1 回答 1

0

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

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

于 2012-10-25T18:25:06.800 回答