All pastes #968772 Raw Edit

Something

public text v1 · immutable
·published 2008-04-03 08:48 UTC
rendered paste body
#!/usr/bin/env python
import os
import re
from itertools import chain

acpi_battery_path = "/proc/acpi/battery/"
STATE_FILE = 'state'
INFO_FILE = 'info'

extract_mha_re = re.compile(r'^[^:]*:\s*(\d+).*')
def extract_mha(prefix, line):
	if line.startswith(prefix):
		m = extract_mha_re.match(line)
		if m:
			return int(m.group(1))
	return None

for battery in os.listdir(acpi_battery_path):
	if not battery.startswith("BAT"): continue
	battery_path = os.path.join(acpi_battery_path, battery)
	if not os.path.isdir(battery_path): continue
	current = max_cap = 0
	state = "Unknown"
	for line in chain(*map(
			lambda s: file(os.path.join(battery_path, s)),
			(STATE_FILE, INFO_FILE))):
		line = line.strip().lower()
		mha = extract_mha('remaining capacity:', line)
		if mha: current = mha
		mha = extract_mha('design capacity:', line)
		if mha: max_cap = mha
		if line.startswith("charging state:"):
			state = line.split(':', 1)[1].strip()
	print '%s: %i%% (%s)' % (
		battery, (current * 100) / max_cap, state)