1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/python/psutil/examples/disk_usage.py Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,50 @@ 1.4 +#!/usr/bin/env python 1.5 + 1.6 +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. 1.7 +# Use of this source code is governed by a BSD-style license that can be 1.8 +# found in the LICENSE file. 1.9 + 1.10 +""" 1.11 +List all mounted disk partitions a-la "df -h" command. 1.12 +""" 1.13 + 1.14 +import sys 1.15 +import os 1.16 +import psutil 1.17 +from psutil._compat import print_ 1.18 + 1.19 +def bytes2human(n): 1.20 + # http://code.activestate.com/recipes/578019 1.21 + # >>> bytes2human(10000) 1.22 + # '9.8K' 1.23 + # >>> bytes2human(100001221) 1.24 + # '95.4M' 1.25 + symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') 1.26 + prefix = {} 1.27 + for i, s in enumerate(symbols): 1.28 + prefix[s] = 1 << (i+1)*10 1.29 + for s in reversed(symbols): 1.30 + if n >= prefix[s]: 1.31 + value = float(n) / prefix[s] 1.32 + return '%.1f%s' % (value, s) 1.33 + return "%sB" % n 1.34 + 1.35 + 1.36 +def main(): 1.37 + templ = "%-17s %8s %8s %8s %5s%% %9s %s" 1.38 + print_(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount")) 1.39 + for part in psutil.disk_partitions(all=False): 1.40 + if os.name == 'nt' and 'cdrom' in part.opts: 1.41 + # may raise ENOENT if there's no cd-rom in the drive 1.42 + continue 1.43 + usage = psutil.disk_usage(part.mountpoint) 1.44 + print_(templ % (part.device, 1.45 + bytes2human(usage.total), 1.46 + bytes2human(usage.used), 1.47 + bytes2human(usage.free), 1.48 + int(usage.percent), 1.49 + part.fstype, 1.50 + part.mountpoint)) 1.51 + 1.52 +if __name__ == '__main__': 1.53 + sys.exit(main())