SamAko
SamAko

Reputation: 3615

Use Python to Access Battery Status in Ubuntu

I am trying to come out with a small python script to monitor the battery state of my ubuntu laptop and sound alerts if it's not charging as well as do other stuff (such as suspend etc). I really don't know where to start, and would like to know if there is any library for python i can use. Any help would be greatly appreciated. Thanks

Upvotes: 5

Views: 6192

Answers (5)

jitheshKuyyalil
jitheshKuyyalil

Reputation: 51

Here is a small piece of code that I wrote. Fredrik Pihl's reply helped me.

import time
from playsound import playsound

# contains battery remaining power
statusf = "/sys/class/power_supply/BAT0/capacity"
# keep checking the power
with open(statusf) as f:
    while True:
        pow_= f.read()
        print(pow_)
        if float(pow_) < 15.0:
            print("power crisis!!")
            while True:
                # beeps until killed
                playsound('beep.wav')
                time.sleep(2)
        time.sleep(5 * 60)

Upvotes: 0

Rohit Joshi
Rohit Joshi

Reputation: 182

You do not need to use any module for this.

Simply you can navigate to

/sys/class/power_supply/BAT0.

Here you will find a lot of files with information about your battery. You will get current charge in charge_now file and total charge in charge_full file. Then you can calculate battery percentage by using some math.

Note:- You may need root access for this. You can use sudo nautilus command to open directories in root mode.

Upvotes: 0

Stuart Axon
Stuart Axon

Reputation: 1874

The the "power" library on pypi is a good bet, it's cross platform too.

Upvotes: 0

james
james

Reputation: 21

Here I found a solution that might be helpful for you too. http://mantoshkumar1.blogspot.in/2012/11/monitoring-battery-status-on-linux.html

Upvotes: 2

Fredrik Pihl
Fredrik Pihl

Reputation: 45670

I believe you can find the information you are looking for in

/sys/class/power_supply/BAT0

Upvotes: 12

Related Questions