Repository navigation
Expand file tree
/
Copy pathdu.py
More file actions
executable file
·169 lines (136 loc) · 5.17 KB
/
Copy pathdu.py
File metadata and controls
executable file
·169 lines (136 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/usr/bin/env python3
"""
du.py - 磁盘占用统计(Python 版 du)
用法:
./du.py # 统计当前目录下每个子项
./du.py /path # 指定目录
./du.py -s /path # 只输出总计
./du.py -a # 列出所有文件,不只目录
./du.py --max-depth 2 # 限制展示深度
./du.py --top 10 # 只显示最大的 10 项
./du.py --apparent # 按文件实际大小而非磁盘块统计 ...
依赖: 仅标准库
"""
import os
import sys
import argparse
from pathlib import Path
class C:
R = "\033[0m"
B = "\033[1m"
DIM = "\033[2m"
CYAN = "\033[36m"
YELLOW = "\033[33m"
RED = "\033[31m"
GREEN = "\033[32m"
USE_COLOR = sys.stdout.isatty()
def color(t, c):
return f"{c}{t}{C.R}" if USE_COLOR else str(t)
def human(n):
n = float(n)
for u in ("B", "K", "M", "G", "T", "P"):
if n < 1024:
return f"{n:.0f}{u}" if u == "B" else f"{n:.1f}{u}"
n /= 1024
return f"{n:.1f}E"
def entry_size(path: Path, apparent: bool):
"""返回 (size, is_dir)。apparent=True 用 st_size,否则用 512B 块数。"""
try:
st = path.lstat()
except OSError:
return 0, False
is_dir = path.is_dir() and not path.is_symlink()
if apparent:
size = st.st_size if not is_dir else 0
else:
size = st.st_blocks * 512
if is_dir:
try:
for root, dirs, files in os.walk(path, followlinks=False):
for name in files + dirs:
fp = os.path.join(root, name)
try:
fst = os.lstat(fp)
size += fst.st_size if apparent else fst.st_blocks * 512
except OSError:
continue
except OSError:
pass
return size, is_dir
def scan(root: Path, args):
"""返回 [(path, size, is_dir), ...] 顶层条目大小列表。"""
results = []
try:
entries = list(root.iterdir())
except OSError as e:
print(f"无法读取 {root}: {e}", file=sys.stderr)
return results
if not args.all:
entries = [e for e in entries if e.is_dir()]
if not args.all and args.hidden_off:
entries = [e for e in entries if not e.name.startswith(".")]
for e in entries:
size, is_dir = entry_size(e, args.apparent)
results.append((e, size, is_dir))
return results
def print_tree(root: Path, args, prefix="", depth=0):
"""递归按深度打印。"""
entries = scan(root, args)
entries.sort(key=lambda x: x[1], reverse=True) # 大的在前
if args.top:
entries = entries[:args.top]
for i, (path, size, is_dir) in enumerate(entries):
is_last = i == len(entries) - 1
conn = "└── " if is_last else "├── "
ext = " " if is_last else "│ "
size_s = human(size)
if size >= 1024**3:
size_c = color(size_s, C.RED)
elif size >= 1024**2:
size_c = color(size_s, C.YELLOW)
elif size >= 1024:
size_c = color(size_s, C.GREEN)
else:
size_c = color(size_s, C.DIM)
name = path.name + ("/" if is_dir else "")
name_c = color(name, C.CYAN + C.B) if is_dir else name
print(f"{prefix}{conn}{size_c:>10} {name_c}")
if is_dir and not path.is_symlink():
if args.max_depth is None or depth + 1 < args.max_depth:
print_tree(path, args, prefix + ext, depth + 1)
def total_size(root: Path, args):
entries = scan(root, args)
return sum(s for _, s, _ in entries)
def main():
parser = argparse.ArgumentParser(
description="磁盘占用统计(Python 版 du)",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("path", nargs="?", default=".", help="目标目录(默认当前)")
parser.add_argument("-s", "--summarize", action="store_true", help="只输出总计")
parser.add_argument("-a", "--all", action="store_true", help="包含文件和隐藏项")
parser.add_argument("-d", "--max-depth", type=int, default=None, help="最大展示深度")
parser.add_argument("-t", "--top", type=int, default=None, help="每层只显示最大的 N 项")
parser.add_argument("--apparent", action="store_true", help="按实际大小统计,不按磁盘块")
parser.add_argument("--hidden-off", action="store_true", help="默认统计时忽略隐藏项(非 -a 时)")
parser.add_argument("--no-color", action="store_true", help="禁用颜色")
args = parser.parse_args()
global USE_COLOR
if args.no_color:
USE_COLOR = False
root = Path(args.path).resolve()
if not root.exists():
print(f"路径不存在: {root}", file=sys.stderr)
sys.exit(1)
if not root.is_dir():
print(f"不是目录: {root}", file=sys.stderr)
sys.exit(1)
if args.summarize:
print(f"{human(total_size(root, args))}\t{root}")
return
print(f"{color(str(root), C.CYAN + C.B)}\n")
print_tree(root, args)
print()
print(f"总计: {color(human(total_size(root, args)), C.B)}")
if __name__ == "__main__":
main()