Merge pull request #742 from cdbrkfxrpt/main

Add TiB to disk units, add SI unit option for disk space
This commit is contained in:
tobi-wan-kenobi 2020-12-02 21:14:18 +01:00 committed by GitHub
commit 1d8b261057
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 8 deletions

View file

@ -8,6 +8,7 @@ Parameters:
* disk.path: Path to calculate disk usage from (defaults to /)
* disk.open: Which application / file manager to launch (default xdg-open)
* disk.format: Format string, tags {path}, {used}, {left}, {size} and {percent} (defaults to '{path} {used}/{size} ({percent:05.02f}%)')
* disk.system: Unit system to use - SI (KB, MB, ...) or IEC (KiB, MiB, ...) (defaults to 'IEC')
"""
import os
@ -25,6 +26,7 @@ class Module(core.module.Module):
self._path = self.parameter("path", "/")
self._format = self.parameter("format", "{used}/{size} ({percent:05.02f}%)")
self._system = self.parameter("system", "IEC")
self._used = 0
self._left = 0
@ -38,9 +40,9 @@ class Module(core.module.Module):
)
def diskspace(self, widget):
used_str = util.format.byte(self._used)
size_str = util.format.byte(self._size)
left_str = util.format.byte(self._left)
used_str = util.format.byte(self._used, sys=self._system)
size_str = util.format.byte(self._size, sys=self._system)
left_str = util.format.byte(self._left, sys=self._system)
percent_str = self._percent
return self._format.format(

View file

@ -71,22 +71,33 @@ def astemperature(val, unit="metric"):
return "{}°{}".format(int(val), __UNITS.get(unit.lower(), __UNITS["default"]))
def byte(val, fmt="{:.2f}"):
def byte(val, fmt="{:.2f}", sys="IEC"):
"""Returns a byte representation of the input value
:param val: value to format, must be convertible into a float
:param fmt: optional output format string, defaults to {:.2f}
:param sys: optional unit system specifier - SI (kilo, Mega, Giga, ...) or
IEC (kibi, Mebi, Gibi, ...) - defaults to IEC
:return: byte representation (e.g. <X> KiB, GiB, etc.) of the input value
:rtype: string
"""
if sys == "IEC":
div = 1024.0
units = ["", "Ki", "Mi", "Gi", "Ti"]
final = "TiB"
elif sys == "SI":
div = 1000.0
units = ["", "K", "M", "G", "T"]
final = "TB"
val = float(val)
for unit in ["", "Ki", "Mi", "Gi"]:
if val < 1024.0:
for unit in units:
if val < div:
return "{}{}B".format(fmt, unit).format(val)
val /= 1024.0
return "{}GiB".format(fmt).format(val * 1024.0)
val /= div
return "{}{}".format(fmt).format(val * div, final)
__seconds_pattern = re.compile(r"(([\d\.?]+)h)?(([\d\.]+)m)?([\d\.]+)?s?")