Monitoring battery status on Linux using python

Monitoring battery status on Linux using a python program

On laptops powered by Linux, the battery status is exposed by the kernel using the file on /proc pseudo filesystem. The file that you could use to monitor on most laptops is /proc/acpi/battery/BAT0/state. Listed below is a simple python code snippet that scans this file every 1 second, collects the necessary statistics and prints the remaining charge on your laptop battery.

#!/usr/bin/env python3
import sys
from time import sleep

battery_status_file = "/proc/acpi/battery/BAT0/state"
print("Monitoring battery status. Press <Ctrl>+C to exit.")

try:
   with open(battery_status_file) as state:
      while True:
         state.seek(0)
         for line in state:
             data = line.split(":")[1].strip().split(" ")[0]
             if "present rate" in line:
                 if "unknown" in data:
                     rate = 0
                 else:
                     rate = int(data) 
             elif "remaining" in line:
                 remaining = int(data)
                 break

         if not rate:
            print("\rNo statistics available.                         ", end="")
         else:
            time_left = float(remaining) / rate
            hours = int(time_left)
            minutes = int((time_left - hours) * 60) 
            print("\rRemaining time left: {0} hours {1} minutes.".format(hours, minutes), end="") 
         sys.stdout.flush()
         sleep(1)
except KeyboardInterrupt:
   print("\nCtrl+C pressed. Exiting.")

You can customize this code or optimize it to your liking. Feel free to use this code and update any optimizations using the comment below.

Tags: 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.