prezto/themes/twain/charge.py

42 lines
1.3 KiB
Python
Raw Normal View History

2012-02-20 13:11:08 +00:00
#!/usr/bin/env python
# coding=UTF-8
""" Prints a battery meter for use in a zsh theme """
2012-02-21 11:31:52 +00:00
import sys
2012-02-20 13:11:08 +00:00
""" Config """
output_length = 10
hide_when_charge_is_above = 90
2012-02-20 13:11:08 +00:00
blank_when_battery_full = True
filled_char, empty_char = u'', u''
""" Read battery charge """
2012-02-28 16:17:39 +00:00
def read_battery_percent (sp, regex):
""" Reads the battery charge as an integer between 0 and 100, using a given process and regex. """
2012-02-20 13:11:08 +00:00
import subprocess, re
2012-02-28 16:17:39 +00:00
process = subprocess.Popen(sp, stdout=subprocess.PIPE)
2012-02-20 13:11:08 +00:00
output = process.communicate()[0].strip()
return int(re.search(regex, output, re.MULTILINE).group(1))
2012-02-20 13:11:08 +00:00
2012-02-28 16:17:39 +00:00
if sys.platform.startswith('darwin'):
""" OSX - 'pmset -g batt' """
charge = read_battery_percent(["pmset", "-g", "batt"], "^.+\t([\d]+)\%")
elif sys.platform.startswith('freebsd'):
""" Freebsd - 'acpiconf -i 0' """
charge = read_battery_percent(["acpiconf", "-i", "0"], "")
2012-02-28 16:17:39 +00:00
else:
""" Linux - 'acpi -b' """
2012-02-28 16:17:39 +00:00
charge = read_battery_percent(["acpi", "-b"], "^Battery 0: .+, ([\d]+)\%")
2012-02-20 13:11:08 +00:00
2012-02-28 16:17:39 +00:00
""" Output """
2012-02-20 13:11:08 +00:00
2012-02-21 11:31:52 +00:00
if charge < hide_when_charge_is_above:
filled = int(charge / output_length)
2012-02-20 13:11:08 +00:00
empty = output_length - filled
meter = (filled * filled_char + empty * empty_char).encode('utf-8')
color = 'green'if filled > 6 else 'yellow' if filled > 4 else 'red'
sys.stdout.write("%F{{{}}}{}%f".format(color, meter))