簡體   English   中英

用於測量電池時間的python腳本

[英]python script for measuring battery time

我正在尋找一個腳本來記錄電池時間(即筆記本電腦依靠電池運行的總時間)。 我以為我會用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接口以獲取信息。

關於打開和關閉文件,您可以再次使用dbus或gconf之類的服務,但是寫入文件更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM