title: python script for measuring battery time
body: <p>I was looking for a script to log battery time (i.e. total time laptop runs on battery). I thought I'd give writing one a shot in python. I'm an beginner at python and came up with this using a lot of examples from this site :D</p>
  
  <pre><code>#!/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) &gt; 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()
  </code></pre>
  
  <p>The script actually works but I'd like it to be better. It uses system acpi command to get battery stats, writes them to one file (batt_log) to store start and end times, then reads from that file, calculates the time difference and writes it to another file (batt_store). I run it every 5 minutes as a process.</p>
  
  <p>What I'd like to do is to maybe use less file I/O operations and find a way to store values persistently in the program. Any ideas welcome. </p>