目录
linux 获取目录大小
import glob
import subprocess
def get_directory_size_with_du(directory):
try:
# 调用 du -sh 命令并捕获输出
result = subprocess.run(['du', '-sh', directory], capture_output=True, text=True, check=True)
# 输出是类似 "1.2G /path/to/directory"
size = result.stdout.split()[0] # 提取文件大小
return size
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
return None
if __name__ == '__main__':
base_dir = "/lpai/volumes/ad-op-ga/code/giga-train/gt_projects"
# base_dir = "/lpai/volumes/ad-op-ga/code/giga-train/gt_projects/svd_front_banggeng_val_lane"
dirs=glob.glob(base_dir+'/*')
for dir in dirs:
size = get_directory_size_with_du(dir)
if size[-1] in ["G"]:
print(f"dir size: {size}",dir)
elif size[-1] in ["M","G"]:
size_number=float(size[:-1])
if size[-1]=="M":
if size_number>10:
print(f"dir size: {size}",dir)
windows系统:
import math
import subprocess
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return f"{s} {size_name[i]}"
def get_directory_size_with_powershell(directory):
try:
# 使用 PowerShell 命令获取目录大小
result = subprocess.run(['powershell', '-Command', f"(Get-ChildItem -Recurse '{directory}' | Measure-Object -Property Length -Sum).Sum"], capture_output=True, text=True, check=True)
size_in_bytes = int(result.stdout.strip())
return size_in_bytes
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
return None
if __name__ == '__main__':
# 示例使用
directory_path =r"F:\biadu_down\jacke121-yolov5-v3.0_class"
size_in_bytes = get_directory_size_with_powershell(directory_path)
size_human_readable = convert_size(size_in_bytes)
print(f"Directory size: {size_human_readable} m")