psutil
1#!/usr/bin/env python3
2
3# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Show battery information.
8
9$ python3 scripts/battery.py
10charge: 74%
11left: 2:11:31
12status: discharging
13plugged in: no
14"""
15
16from __future__ import print_function17
18import sys19
20import psutil21
22
23def secs2hours(secs):24mm, ss = divmod(secs, 60)25hh, mm = divmod(mm, 60)26return "%d:%02d:%02d" % (hh, mm, ss)27
28
29def main():30if not hasattr(psutil, "sensors_battery"):31return sys.exit("platform not supported")32batt = psutil.sensors_battery()33if batt is None:34return sys.exit("no battery is installed")35
36print("charge: %s%%" % round(batt.percent, 2))37if batt.power_plugged:38print(39"status: %s"40% ("charging" if batt.percent < 100 else "fully charged")41)42print("plugged in: yes")43else:44print("left: %s" % secs2hours(batt.secsleft))45print("status: %s" % "discharging")46print("plugged in: no")47
48
49if __name__ == '__main__':50main()51