Updated string_to_binary()
* Raise an exception if the string can't be parsed as a valid size * Handle strings without spaces (e.g. '1.44mb') * Handle negative values
This commit is contained in:
parent
f985c03490
commit
2cbe99952f
1 changed files with 20 additions and 19 deletions
|
|
@ -28,7 +28,7 @@ COLORS = {
|
||||||
}
|
}
|
||||||
LOG = logging.getLogger(__name__)
|
LOG = logging.getLogger(__name__)
|
||||||
REGEX_SIZE_STRING = re.compile(
|
REGEX_SIZE_STRING = re.compile(
|
||||||
r'(?P<size>\d+\.?\d*)\s+(?P<units>[PTGMKB])(?P<binary>I?)B?'
|
r'(?P<size>\-?\d+\.?\d*)\s*(?P<units>[PTGMKB])(?P<binary>I?)B?'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -197,29 +197,30 @@ def string_to_bytes(size, assume_binary=False):
|
||||||
size = str(size)
|
size = str(size)
|
||||||
tmp = REGEX_SIZE_STRING.search(size.upper())
|
tmp = REGEX_SIZE_STRING.search(size.upper())
|
||||||
|
|
||||||
|
# Raise exception if string can't be parsed as a size
|
||||||
|
if not tmp:
|
||||||
|
raise ValueError('invalid size string: {}'.format(size))
|
||||||
|
|
||||||
# Set scale
|
# Set scale
|
||||||
if tmp.group('binary') or assume_binary:
|
if tmp.group('binary') or assume_binary:
|
||||||
scale = 1024
|
scale = 1024
|
||||||
|
|
||||||
# Convert to bytes
|
# Convert to bytes
|
||||||
if tmp:
|
size = float(tmp.group('size'))
|
||||||
size = float(tmp.group('size'))
|
units = tmp.group('units')
|
||||||
units = tmp.group('units')
|
if units == 'P':
|
||||||
if units == 'P':
|
size *= scale ** 5
|
||||||
size *= scale ** 5
|
if units == 'T':
|
||||||
if units == 'T':
|
size *= scale ** 4
|
||||||
size *= scale ** 4
|
elif units == 'G':
|
||||||
elif units == 'G':
|
size *= scale ** 3
|
||||||
size *= scale ** 3
|
elif units == 'M':
|
||||||
elif units == 'M':
|
size *= scale ** 2
|
||||||
size *= scale ** 2
|
elif units == 'K':
|
||||||
elif units == 'K':
|
size *= scale ** 1
|
||||||
size *= scale ** 1
|
elif units == 'B':
|
||||||
elif units == 'B':
|
size *= scale ** 0
|
||||||
size *= scale ** 0
|
size = int(size)
|
||||||
size = int(size)
|
|
||||||
else:
|
|
||||||
return -1
|
|
||||||
|
|
||||||
# Done
|
# Done
|
||||||
LOG.debug('bytes: %s', size)
|
LOG.debug('bytes: %s', size)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue