From: Christian Herdtweck Date: Fri, 5 Feb 2016 10:16:40 +0000 (+0100) Subject: make sizes more readable with function file_helpers.size_str X-Git-Tag: v1.2~38 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=f692c704170acaebd688cb480263f06b5eb31247;p=pyi2ncommon make sizes more readable with function file_helpers.size_str --- diff --git a/src/file_helpers.py b/src/file_helpers.py index 79eb2b3..b9e932b 100644 --- a/src/file_helpers.py +++ b/src/file_helpers.py @@ -108,8 +108,9 @@ class FilesystemFillState: self.mount_point = None def __str__(self): - return '[Filesystem {0} mounted at {1}: {2}% used]' \ - .format(self.name, self.mount_point, int(round(self.capacity))) + return '[Filesystem {0} mounted at {1}: {2}/{3} used]' \ + .format(self.name, self.mount_point, + size_str(self.used), size_str(self.size)) def get_filesystem_fill_states(method=FS_FILL_METHOD_STATVFS): @@ -401,3 +402,26 @@ def find_mount_point(path): while not os.path.ismount(path): path = os.path.dirname(path) return path + + +def size_str(byte_number): + """ round byte_number to something easily human-readable like '1.5G' """ + + units = 'B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' + factor = 1024 + thresh_add_comma = 10. # below this, return 1.2G, above this return 12G + + curr_fac = 1 + curr_num = float(byte_number) + for unit in units: + if curr_num > factor: + curr_num /= factor + continue + elif curr_num < thresh_add_comma and unit != 'B': # e.g. 1.2G + return '{0:.1f}{1}'.format(curr_num, unit) + else: # e.g. 12G or 1B + return '{0:d}{1}'.format(int(round(curr_num)), unit) + + # have an impossible amount of data. (>1024**4 GB) + # undo last "/factor" and show thousand-separator + return '{0:,d}{1}'.format(int(round(curr_num*factor)), units[-1]) diff --git a/test/test_file_helpers.py b/test/test_file_helpers.py index 31c5769..c58a619 100644 --- a/test/test_file_helpers.py +++ b/test/test_file_helpers.py @@ -62,11 +62,11 @@ class FileHelperTester(unittest.TestCase): state.capacity = 90 state.mount_point = '/not/mounted' - expect = '[Filesystem {0} mounted at {1}: {2}% used]' \ - .format(state.name, state.mount_point, state.capacity) + expect = '[Filesystem dummy mounted at /not/mounted: 9.0G/10G used]' self.assertEqual(str(state), expect) + def test_disc_stats_df(self): """ tests get_filesystem_fill_states using df """