Last active
February 15, 2016 21:47
-
-
Save adityaramesh/8d96cffb72621c20f5ef to your computer and use it in GitHub Desktop.
Converts a human-readable memory string (e.g. "256 GiB") into an integral byte count.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def parse_memory_string(mem_str): | |
""" | |
Returns the number of bytes represented by a string ``mem_str`` matching the following | |
regex: :: | |
r'^(0|[1-9][0-9]*) (byte|bytes|KiB|MiB|GiB|TiB)' | |
If ``mem_str`` does not match this regex, then ``None`` is returned. | |
""" | |
memory_regex = r'^(0|[1-9][0-9]*) (byte|bytes|KiB|MiB|GiB|TiB)' | |
mem_pat = re.compile(memory_regex) | |
match = mem_pat.match(mem_str) | |
if match is None: | |
return | |
assert len(match.groups()) == 2 | |
base = int(match.groups()[0]) | |
return base * { | |
'byte': 1, | |
'bytes': 1, | |
'KiB': 2 ** 10, | |
'MiB': 2 ** 20, | |
'GiB': 2 ** 30, | |
'TiB': 2 ** 40 | |
}[match.groups()[1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment