Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import argparse, sys
  3. parser = argparse.ArgumentParser(description="Format numbers as human readable byte units. Accepts basic mathematical expressions. Characters allowed are \"0123456789\\t\\n -+/*%\".")
  4. parser.add_argument("bytes", help="number to format")
  5. parser.add_argument("--no-suffix", help="don't add a 'B' suffix to the end of the output", action="store_true")
  6. args = parser.parse_args()
  7. allowed_chars = '0123456789\t\n -+/*%'
  8.  
  9. def format(num):
  10. suffix = 'B'
  11. units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']
  12. if args.no_suffix:
  13. suffix = ''
  14. units = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']
  15.  
  16. for unit in units:
  17. if abs(num) < 1024.0:
  18. return "%3.1f%s%s" % (num, unit, suffix)
  19. num /= 1024.0
  20. return "%.1f%s%s" % (num, 'Yi', suffix)
  21.  
  22.  
  23. for char in args.bytes:
  24. if char not in allowed_chars:
  25. sys.stderr.write("{}: error: argument bytes: invalid int value or math expression: '{}'\n".format("formatbytes", args.bytes))
  26. sys.exit(1)
  27.  
  28. try:
  29. evaluated = eval(args.bytes)
  30. except SyntaxError:
  31. sys.stderr.write("{}: error: argument bytes: error while evaluating expression: '{}'\n".format("formatbytes", args.bytes))
  32. sys.exit(1)
  33.  
  34. print(format(evaluated))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement