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"""
8Show battery information.
9
10$ python scripts/battery.py
11charge:     74%
12left:       2:11:31
13status:     discharging
14plugged in: no
15"""
16
17from __future__ import print_function
18import sys
19
20import psutil
21
22
23def secs2hours(secs):
24    mm, ss = divmod(secs, 60)
25    hh, mm = divmod(mm, 60)
26    return "%d:%02d:%02d" % (hh, mm, ss)
27
28
29def main():
30    if not hasattr(psutil, "sensors_battery"):
31        return sys.exit("platform not supported")
32    batt = psutil.sensors_battery()
33    if batt is None:
34        return sys.exit("no battery is installed")
35
36    print("charge:     %s%%" % round(batt.percent, 2))
37    if batt.power_plugged:
38        print("status:     %s" % (
39            "charging" if batt.percent < 100 else "fully charged"))
40        print("plugged in: yes")
41    else:
42        print("left:       %s" % secs2hours(batt.secsleft))
43        print("status:     %s" % "discharging")
44        print("plugged in: no")
45
46
47if __name__ == '__main__':
48    main()
49