MacBookのバッテリーの残量をGrowlに通知する

30分プログラム、その577。MacBookのバッテリーの残量をGrowlに通知してみる。

昔にやったMacBookのバッテリー残量表示 - みずぴー日記PythonでGrowlに通知を出してみる - みずぴー日記を組合せれば簡単にできる。
5分おきに残量をチェックして40%以下だったら、Growlで通知するようにした。

使い方

$ python battery.py

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# battery.py -
#
# Copyright(C) 2009 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2009/05/07 20:06:27
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

from subprocess import Popen,PIPE
import re
from Growl import *
from time import sleep

def search(regexp,output):
    return int(re.compile(regexp).search(output).group(1))

def used():
    output = Popen(["system_profiler", "SPPowerDataType"],
                   stdout=PIPE).communicate()[0]
    remain = search(r'Charge remaining \(mAh\):\s+(\d*)',output)
    full   = search(r'Full charge capacity \(mAh\):\s+(\d*)',output)
    return remain*100 / full

if __name__ == '__main__':
    growl = GrowlNotifier("Battery Notifier",["normal"])
    growl.register()

    while True:
        bat = used()
        print bat
        if bat < 40:
            growl.notify('normal',
                         'Battery is Low',
                         "Battery Remain: %s %%" % bat)
        sleep(300)