~ubuntu-branches/ubuntu/trusty/python-psutil/trusty-proposed

« back to all changes in this revision

Viewing changes to examples/disk_usage.py

  • Committer: Package Import Robot
  • Author(s): Leo Iannacone
  • Date: 2012-01-07 13:18:54 UTC
  • mfrom: (2.1.9 sid)
  • Revision ID: package-import@ubuntu.com-20120107131854-6l22ulo9hwrroa8m
Tags: 0.4.1-1ubuntu1
* Merge with Debian unstable (LP: #913100).  Remaining Ubuntu changes:
  - Switch to dh_python2. (LP: #788514)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/env python
2
2
#
3
 
# $Id: disk_usage.py 1143 2011-10-05 19:11:59Z g.rodola $
 
3
# $Id: disk_usage.py 1236 2011-12-13 19:00:35Z g.rodola $
4
4
#
5
5
# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
6
6
# Use of this source code is governed by a BSD-style license that can be
13
13
import sys
14
14
import psutil
15
15
 
16
 
def convert_bytes(n):
17
 
    if n == 0:
18
 
        return "0B"
19
 
    symbols = ('k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
 
16
def print_(s):
 
17
    # python 2/3 compatibility layer
 
18
    sys.stdout.write(s + '\n')
 
19
    sys.stdout.flush()
 
20
 
 
21
def bytes2human(n):
 
22
    # >>> bytes2human(10000)
 
23
    # '9.8K'
 
24
    # >>> bytes2human(100001221)
 
25
    # '95.4M'
 
26
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
20
27
    prefix = {}
21
28
    for i, s in enumerate(symbols):
22
29
        prefix[s] = 1 << (i+1)*10
24
31
        if n >= prefix[s]:
25
32
            value = float(n) / prefix[s]
26
33
            return '%.1f%s' % (value, s)
 
34
    return "%sB" % n
27
35
 
28
36
 
29
37
def main():
30
38
    templ = "%-17s %8s %8s %8s %5s%% %9s  %s"
31
 
    print templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount")
 
39
    print_(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
32
40
    for part in psutil.disk_partitions(all=False):
33
41
        usage = psutil.disk_usage(part.mountpoint)
34
 
        print templ % (part.device,
35
 
                       convert_bytes(usage.total),
36
 
                       convert_bytes(usage.used),
37
 
                       convert_bytes(usage.free),
38
 
                       int(usage.percent),
39
 
                       part.fstype,
40
 
                       part.mountpoint)
 
42
        print_(templ % (part.device,
 
43
                        bytes2human(usage.total),
 
44
                        bytes2human(usage.used),
 
45
                        bytes2human(usage.free),
 
46
                        int(usage.percent),
 
47
                        part.fstype,
 
48
                        part.mountpoint))
41
49
 
42
50
if __name__ == '__main__':
43
51
    sys.exit(main())