diff options
author | Giampaolo Rodola <g.rodola@gmail.com> | 2017-01-27 03:46:35 +0100 |
---|---|---|
committer | Giampaolo Rodola <g.rodola@gmail.com> | 2017-01-27 03:46:35 +0100 |
commit | 32cec3e427621b77fa2f267ffe416f89cd120536 (patch) | |
tree | de1cd5fd3a23bc23a51d78ef116e66d414a35b4b /scripts/battery.py | |
parent | e462e7b3b3966a90e0430584fa43ffdc71078f90 (diff) | |
download | psutil-32cec3e427621b77fa2f267ffe416f89cd120536.tar.gz |
#955: add battery.py example script
Diffstat (limited to 'scripts/battery.py')
-rwxr-xr-x | scripts/battery.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/scripts/battery.py b/scripts/battery.py new file mode 100755 index 00000000..67d706e3 --- /dev/null +++ b/scripts/battery.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +Show battery information. + +$ python battery.py +charge: 49% +left: 2:11:31 +status: discharging +plugged in: no +""" + +from __future__ import print_function +import sys + +import psutil + + +def secs2hours(secs): + mm, ss = divmod(secs, 60) + hh, mm = divmod(mm, 60) + return "%d:%02d:%02d" % (hh, mm, ss) + + +def main(): + if not hasattr(psutil, "sensors_battery"): + return sys.exit("platform not supported") + batt = psutil.sensors_battery() + if batt is None: + return sys.exit("no battery is installed") + + print("charge: %s%%" % batt.percent) + if batt.power_plugged: + print("status: %s" % ( + "charging" if batt.percent < 100 else "fully charged")) + print("plugged in: yes") + else: + print("left: %s" % secs2hours(batt.secsleft)) + print("status: %s" % "discharging") + print("plugged in: no") + + +if __name__ == '__main__': + main() |