Just A Small Guideline

Feel free to browse the site. Don't be afraid to leave comments, they're supportive.
Please follow me on Twitter @ehldmnt and retweet my posts.

Sunday, July 28, 2013

[Python 3] Console Battery Monitor In Python [Using BAT0]

I never took up Lua, despite having a Lua-based Window Manager (AwesomeWM), I've been able to feel my way around with the help of some friends as well as a bit of googling. "Implementing a battery monitor into the wibox seemed wasteful," I thought. "Why not create a terminal battery monitor for the good of learning?"

And so I did.

Here's what the output looks like:


Here's the code [Image]:


Here's the code again[plain text]:

#!/usr/bin/python
# The full charge.

cf = open('/sys/class/power_supply/BAT0/charge_full')
cf = int(cf.readline().strip('\n'))

#The current battery charge

cn = open('/sys/class/power_supply/BAT0/charge_now')
cn = int(cn.readline().strip('\n'))

st = open('/sys/class/power_supply/BAT0/status')
st = st.readline().strip('\n')

# Creating the Percentage
   
percent = (cn / cf) * 100
   
#  Creating the Rounded Percentage
   
percents = str(percent)[0:2]
rpercent = int(percents)


def batMon(cf, cn, st):


    # Testing Whether or not it is Charging
    if rpercent == 20 and st != "Charging":
        print("\n!!!! Battery is low! Please charge it now!!!!")

    print("\n[Charging]: %s" % st)

    # Printing out the total Voltage to the console
    print("[Total Charge]: %d" % cf)
   
    # Printing out the current voltage to the console
    print("[Current Charge]: %d" % cn)
   
    # Printing out the Rounded and the actual percentage
    print("[Round Percent / Percent]: %s / %.2f" % (rpercent, percent))




if __name__ == "__main__":
    batMon(cf, cn, st)

This was a pet project of mine for a while. I just recently decided to get into it. It's released under GNU GPLv3.

No comments: