#!/usr/bin/env python import subprocess, re, sys # Run ioreg to get the battery status line p = subprocess.Popen(args=["ioreg", "-w0", "-l"], stdout=subprocess.PIPE) for line in p.stdout.xreadlines(): if line.find("IOBatteryInfo") >= 0: p.stdout.close() break else: print "IOBatteryInfo not found!" sys.exit(1) # Parse the line to a dict & calculate the percentage line = line.strip() m = re.compile('^.*"IOBatteryInfo" = ').match(line) line = line[m.end()+1:-1].replace("=", ":") exec "fields = " + line fields["Capacity%"] = int(100.0 * float(fields["Capacity"]) / float(fields["AbsoluteMaxCapacity"])) # Print to screen for field in ("Current", "Capacity", "Capacity%", "Cycle Count"): print "%s:\t%d" % (field, fields[field])