diff options
author | Giampaolo Rodola' <g.rodola@gmail.com> | 2011-07-01 11:55:36 (GMT) |
---|---|---|
committer | Giampaolo Rodola' <g.rodola@gmail.com> | 2011-07-01 11:55:36 (GMT) |
commit | 210e7ca032d51b8368359c02ad505dbd5f633cc9 (patch) | |
tree | 6558f76ed9be7add62a771d5b09b52e94f058fa3 /Lib | |
parent | 59929d9877e2968c38e672f14cd92aa63bfe9c4b (diff) | |
download | cpython-210e7ca032d51b8368359c02ad505dbd5f633cc9.zip cpython-210e7ca032d51b8368359c02ad505dbd5f633cc9.tar.gz cpython-210e7ca032d51b8368359c02ad505dbd5f633cc9.tar.bz2 |
Issue #12442: add shutil.disk_usage()
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/shutil.py | 19 | ||||
-rw-r--r-- | Lib/test/test_shutil.py | 10 |
2 files changed, 29 insertions, 0 deletions
diff --git a/Lib/shutil.py b/Lib/shutil.py index d2e2dc5..0af9fa5 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -12,6 +12,7 @@ import fnmatch import collections import errno import tarfile +from collections import namedtuple try: import bz2 @@ -754,3 +755,21 @@ def unpack_archive(filename, extract_dir=None, format=None): func = _UNPACK_FORMATS[format][1] kwargs = dict(_UNPACK_FORMATS[format][2]) func(filename, extract_dir, **kwargs) + +if hasattr(os, "statvfs") or os.name == 'nt': + _ntuple_diskusage = namedtuple('usage', 'total used free') + + def disk_usage(path): + """Return disk usage statistics about the given path as a namedtuple + including total, used and free space expressed in bytes. + """ + if hasattr(os, "statvfs"): + st = os.statvfs(path) + free = (st.f_bavail * st.f_frsize) + total = (st.f_blocks * st.f_frsize) + used = (st.f_blocks - st.f_bfree) * st.f_frsize + else: + import nt + total, free = nt._getdiskusage(path) + used = total - free + return _ntuple_diskusage(total, used, free) diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index ad31f47..20e9412 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -728,6 +728,16 @@ class TestShutil(unittest.TestCase): unregister_unpack_format('Boo2') self.assertEqual(get_unpack_formats(), formats) + @unittest.skipUnless(hasattr(shutil, 'disk_usage'), + "disk_usage not available on this platform") + def test_disk_usage(self): + usage = shutil.disk_usage(os.getcwd()) + self.assertTrue(usage.total > 0) + self.assertTrue(usage.used > 0) + self.assertTrue(usage.free >= 0) + self.assertTrue(usage.total >= usage.used) + self.assertTrue(usage.total > usage.free) + class TestMove(unittest.TestCase): |