Blog /Battery Level in Your Prompt with Python

May 17, 2009 07:31 +0000  |  Linux Python 1

In the midst of one of those "because I can" moods today, I wrote a fun Python script to get my battery status and colour-code it so it could be loaded into my prompt. I'm posting it here 'cause I think it's nifty:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

battery = "/proc/acpi/battery/BAT0"

def getMax(path):
    return getValueFromFile(path + "/info", "last full capacity")


def getRemaining(path):
    return getValueFromFile(path + "/state", "remaining capacity")


def getValueFromFile(name, value):
    f = open(name, "r")
    for line in f:
        remaining = re.match(r"^%s:\s+(\d+)" % (value), line)
        if remaining:
            return remaining.group(1)


def isCharging(path):
    f = open(path + "/state", "r")
    for line in f:
        key = re.match(r"^charging state:\s+charging", line)
        if key:
            return True


def render(path):

    level = int((float(getRemaining(path)) / float(getMax(path))) * 100)

    colour = ""
    if isCharging(path):
        colour = "\033[1;36m" # Cyan
    elif level < 25:
        colour = "\033[1;31m" # Red
    elif level < 50:
        colour = "\033[1;33m" # Yellow
    else:
        colour = "\033[1;32m" # Green

    print colour + str(level) + "%\033[0m",

render(battery)

Comments

Robin
17 May 2009, 4:42 p.m.  | 

Nerd.

Post a Comment of Your Own

Markdown will work here, if you're into that sort of thing.