python/psutil/examples/disk_usage.py

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rwxr-xr-x

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 #!/usr/bin/env python
michael@0 2
michael@0 3 # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
michael@0 4 # Use of this source code is governed by a BSD-style license that can be
michael@0 5 # found in the LICENSE file.
michael@0 6
michael@0 7 """
michael@0 8 List all mounted disk partitions a-la "df -h" command.
michael@0 9 """
michael@0 10
michael@0 11 import sys
michael@0 12 import os
michael@0 13 import psutil
michael@0 14 from psutil._compat import print_
michael@0 15
michael@0 16 def bytes2human(n):
michael@0 17 # http://code.activestate.com/recipes/578019
michael@0 18 # >>> bytes2human(10000)
michael@0 19 # '9.8K'
michael@0 20 # >>> bytes2human(100001221)
michael@0 21 # '95.4M'
michael@0 22 symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
michael@0 23 prefix = {}
michael@0 24 for i, s in enumerate(symbols):
michael@0 25 prefix[s] = 1 << (i+1)*10
michael@0 26 for s in reversed(symbols):
michael@0 27 if n >= prefix[s]:
michael@0 28 value = float(n) / prefix[s]
michael@0 29 return '%.1f%s' % (value, s)
michael@0 30 return "%sB" % n
michael@0 31
michael@0 32
michael@0 33 def main():
michael@0 34 templ = "%-17s %8s %8s %8s %5s%% %9s %s"
michael@0 35 print_(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
michael@0 36 for part in psutil.disk_partitions(all=False):
michael@0 37 if os.name == 'nt' and 'cdrom' in part.opts:
michael@0 38 # may raise ENOENT if there's no cd-rom in the drive
michael@0 39 continue
michael@0 40 usage = psutil.disk_usage(part.mountpoint)
michael@0 41 print_(templ % (part.device,
michael@0 42 bytes2human(usage.total),
michael@0 43 bytes2human(usage.used),
michael@0 44 bytes2human(usage.free),
michael@0 45 int(usage.percent),
michael@0 46 part.fstype,
michael@0 47 part.mountpoint))
michael@0 48
michael@0 49 if __name__ == '__main__':
michael@0 50 sys.exit(main())

mercurial