battery.py 968 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python
  2. # coding=UTF-8
  3. import math, subprocess
  4. p = subprocess.Popen(["ioreg", "-rc", "AppleSmartBattery"], stdout=subprocess.PIPE)
  5. output = p.communicate()[0]
  6. o_max = [l for l in output.splitlines() if 'MaxCapacity' in l][0]
  7. o_cur = [l for l in output.splitlines() if 'CurrentCapacity' in l][0]
  8. b_max = float(o_max.rpartition('=')[-1].strip())
  9. b_cur = float(o_cur.rpartition('=')[-1].strip())
  10. charge = b_cur / b_max
  11. charge_threshold = int(math.ceil(10 * charge))
  12. # Output
  13. total_slots, slots = 10, []
  14. filled = int(math.ceil(charge_threshold * (total_slots / 10.0))) * u'▸'
  15. empty = (total_slots - len(filled)) * u'▹'
  16. out = (filled + empty).encode('utf-8')
  17. import sys
  18. color_green = '%{%}'
  19. color_yellow = '%{%}'
  20. color_red = '%{%}'
  21. color_reset = '%{%}'
  22. color_out = (
  23. color_green if len(filled) > 6
  24. else color_yellow if len(filled) > 4
  25. else color_red
  26. )
  27. out = color_out + out + color_reset
  28. sys.stdout.write(out)