scripts/bin/dirsize.py

67 lines
1.3 KiB
Python

#!/usr/bin/env python3
import argparse, sys
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument('path', help='Path to recursively search')
parser.add_argument('--progress', '-p', action='store_true', help='Enables displaying the current size in progress')
parser.add_argument('--count', '-c', default=100, type=int, help='The number of files to go through before updating the status (--progress implied)')
args = parser.parse_args()
path = Path(args.path)
if args.path.startswith('~'):
path = path.expanduser()
size = 0
files = 0
filenum = 0
chunk = 0
def print_size():
size_mib = round(size/1024/1024, 2)
sys.stdout.write(f'Current size: {size_mib}MiB\r')
sys.stdout.flush()
def main():
global size
global files
global filenum
global chunk
if not path.exists():
print('Path doen\'t exist:', str(path))
return
if not path.is_dir():
print('Path is not a dir:', str(path))
return
for f in path.glob('**/*'):
if f.is_file():
size += f.stat().st_size
filenum += 1
files += 1
if (args.progress or args.count != 100) and filenum >= args.count:
chunk += 1
filenum = 0
print_size()
return True
try:
ret = main()
except KeyboardInterrupt:
pass
if args.progress or args.count != 100:
print('\n')
if ret:
print(f'Files: {files}')
print(f'Size: {round(size/1024/1024, 2)} MiB')