Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import argparse, sys
- parser = argparse.ArgumentParser(description="Format numbers as human readable byte units. Accepts basic mathematical expressions. Characters allowed are \"0123456789\\t\\n -+/*%\".")
- parser.add_argument("bytes", help="number to format")
- parser.add_argument("--no-suffix", help="don't add a 'B' suffix to the end of the output", action="store_true")
- args = parser.parse_args()
- allowed_chars = '0123456789\t\n -+/*%'
- def format(num):
- suffix = 'B'
- units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']
- if args.no_suffix:
- suffix = ''
- units = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']
- for unit in units:
- if abs(num) < 1024.0:
- return "%3.1f%s%s" % (num, unit, suffix)
- num /= 1024.0
- return "%.1f%s%s" % (num, 'Yi', suffix)
- for char in args.bytes:
- if char not in allowed_chars:
- sys.stderr.write("{}: error: argument bytes: invalid int value or math expression: '{}'\n".format("formatbytes", args.bytes))
- sys.exit(1)
- try:
- evaluated = eval(args.bytes)
- except SyntaxError:
- sys.stderr.write("{}: error: argument bytes: error while evaluating expression: '{}'\n".format("formatbytes", args.bytes))
- sys.exit(1)
- print(format(evaluated))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement