python/psutil/examples/disk_usage.py

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rwxr-xr-x

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

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

mercurial