Skip to content

Instantly share code, notes, and snippets.

@zhasm
Created May 21, 2012 09:50
Show Gist options
  • Save zhasm/2761563 to your computer and use it in GitHub Desktop.
Save zhasm/2761563 to your computer and use it in GitHub Desktop.
convert Bytes into human-readable format
#!/usr/bin/env python
'''
usage: sz [-h] [--unit UnitOutput] N [N ...]
Input integer Bites, Output Human-Readable Size.
positional arguments:
N
optional arguments:
-h, --help show this help message and exit
--unit UnitOutput, -u UnitOutput
Available Units: B, K, M, G, T, P, E, Z, Y; Can be in
Upper/Lower Cases. If not provided, an appropriate
unit will be used.
'''
def formatter(size, unit):
unit_names=['b', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y']
u={}
for i in range(len(unit_names)):
u[unit_names[i]]=1024**i
def _name(u):
return 'Byte' if u=='b' else u.upper()+'B'
if unit:
return "%.02f %s" % (size * 1.0 / (u[unit]), _name(unit))
else:
index=0
while size >= 1024 and index<len(unit_names)-1:
size /= 1024.0
index +=1
return "%.02f %s" % (size, _name(unit_names[index]))
def parse():
import argparse
parser = argparse.ArgumentParser(description='Input integer Bites, Output Human-Readable Size.')
parser.add_argument('byte', metavar='N', type=int, nargs='+')
parser.add_argument('--unit', '-u', metavar='UnitOutput', type=str, default="",
help="Available Units: B, K, M, G, T, P, E, Z, Y; Can be in Upper/Lower Cases. If not provided, an appropriate unit will be used.")
args = parser.parse_args()
return args
def process():
args=parse()
n=args.byte
unit=args.unit
for i in n:
print formatter(i, unit)
def main():
process()
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment