Repository navigation
Expand file tree
/
Copy pathdf.py
More file actions
executable file
·250 lines (202 loc) · 7.09 KB
/
Copy pathdf.py
File metadata and controls
executable file
·250 lines (202 loc) · 7.09 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/env python3
"""
df.py - 磁盘空间使用情况(Python 版 df)
用法:
./df.py # 显示主要文件系统
./df.py -a # 包含伪文件系统(tmpfs/proc 等)
./df.py -T # 额外显示文件系统类型
./df.py -i # 显示 inode 使用情况
./df.py /path # 只看该路径所在文件系统
./df.py --no-color
依赖: 仅标准库
"""
import os
import re
import sys
import argparse
class C:
R = "\033[0m"
B = "\033[1m"
DIM = "\033[2m"
CYAN = "\033[36m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RED = "\033[31m"
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 human_int(n):
n = int(n)
if n >= 10**9:
return f"{n / 1e9:.1f}G"
if n >= 10**6:
return f"{n / 1e6:.1f}M"
if n >= 10**4:
return f"{n / 1e3:.0f}K"
return str(n)
# 默认不显示的伪文件系统
PSEUDO_FS = {
"proc", "sysfs", "devtmpfs", "devpts", "cgroup", "cgroup2",
"pstore", "bpf", "debugfs", "tracefs", "securityfs", "fusectl",
"configfs", "mqueue", "hugetlbfs", "autofs", "binfmt_misc",
"selinuxfs", "rpc_pipefs", "nsfs", "squashfs", "overlay",
}
NUMERIC_HEADERS = {"Size", "Used", "Avail", "Use%", "Inodes", "IUsed", "IFree", "IUse%"}
# /proc/mounts 里的 \040 等八进制转义
_ESC_RE = re.compile(r"\\([0-7]{3})")
def _unescape(s):
return _ESC_RE.sub(lambda m: chr(int(m.group(1), 8)), s)
def read_mounts():
"""返回 [(device, mountpoint, fstype), ...]"""
mounts = []
try:
with open("/proc/self/mounts", "r", errors="replace") as f:
for line in f:
parts = line.split()
if len(parts) < 3:
continue
mounts.append((_unescape(parts[0]),
_unescape(parts[1]),
parts[2]))
except OSError:
pass
return mounts
def find_mount(path):
"""找 path 所在的挂载点(最长前缀匹配)"""
rp = os.path.realpath(path)
best = None
for dev, mp, fstype in read_mounts():
if rp == mp or rp.startswith(mp.rstrip("/") + "/"):
if best is None or len(mp) > len(best[1]):
best = (dev, mp, fstype)
return best
def collect(args):
"""返回 [(device, fstype, total, used, avail, pct, mountpoint), ...]"""
if args.path:
m = find_mount(args.path)
if not m:
return []
mounts = [m]
else:
mounts = read_mounts()
if not args.all:
mounts = [(d, m, f) for d, m, f in mounts if f not in PSEUDO_FS]
rows = []
seen_dev = set()
for dev, mp, fstype in mounts:
if not args.all:
# 同一块设备(bind mount 等)只显示一次
try:
st_dev = os.stat(mp).st_dev
except OSError:
continue
if st_dev in seen_dev:
continue
seen_dev.add(st_dev)
try:
st = os.statvfs(mp)
except OSError:
continue
frs = st.f_frsize or st.f_bsize
if args.inodes:
total = st.f_files
avail = getattr(st, "f_favail", st.f_ffree)
used = total - st.f_ffree
pct = (used / (used + avail) * 100) if (used + avail) > 0 else 0.0
else:
total = frs * st.f_blocks
free = frs * st.f_bfree
avail = frs * st.f_bavail
used = total - free
pct = (used / (used + avail) * 100) if (used + avail) > 0 else 0.0
rows.append((dev, fstype, total, used, avail, pct, mp))
return rows
def fmt_pct(pct):
if pct >= 90:
return color(f"{pct:.0f}%", C.RED)
if pct >= 75:
return color(f"{pct:.0f}%", C.YELLOW)
return color(f"{pct:.0f}%", C.GREEN)
def print_table(rows, args):
if not rows:
print("无数据")
return
headers = ["Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on"]
if args.inodes:
headers[1:5] = ["Inodes", "IUsed", "IFree", "IUse%"]
if args.show_type:
headers.insert(1, "Type")
table = []
for dev, fstype, total, used, avail, pct, mp in rows:
if args.inodes:
vals = [dev, human_int(total), human_int(used),
human_int(avail), fmt_pct(pct), mp]
else:
vals = [dev, human(total), human(used),
human(avail), fmt_pct(pct), mp]
if args.show_type:
vals.insert(1, fstype)
table.append(vals)
# 计算列宽(先算纯文本宽度,颜色标记加宽度后不影响对齐)
widths = []
for i, h in enumerate(headers):
w = len(h)
for r in table:
# 去掉 ANSI 颜色码再算宽度
raw = re.sub(r"\033\[[0-9;]*m", "", str(r[i]))
w = max(w, len(raw))
widths.append(w)
def fmt_row(vals, is_header=False):
cells = []
for i, v in enumerate(vals):
raw = re.sub(r"\033\[[0-9;]*m", "", str(v))
pad = widths[i] - len(raw)
if headers[i] in NUMERIC_HEADERS:
cells.append(" " * pad + str(v))
else:
cells.append(str(v) + " " * pad)
return " ".join(cells)
head = fmt_row(headers)
print(color(head, C.B + C.CYAN))
for r in table:
print(fmt_row(r))
def main():
parser = argparse.ArgumentParser(
description="磁盘空间使用情况(Python 版 df)",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="示例:\n"
" ./df.py 显示主要文件系统\n"
" ./df.py -T 加显示类型\n"
" ./df.py -i 看 inode\n"
" ./df.py ~ 家目录所在文件系统\n",
)
parser.add_argument("path", nargs="?", default=None,
help="只显示该路径所在的文件系统")
parser.add_argument("-a", "--all", action="store_true",
help="包含伪文件系统(tmpfs/proc 等)")
parser.add_argument("-T", "--show-type", action="store_true",
help="显示文件系统类型")
parser.add_argument("-i", "--inodes", action="store_true",
help="显示 inode 使用情况而非块使用情况")
parser.add_argument("--no-color", action="store_true",
help="禁用颜色")
args = parser.parse_args()
global USE_COLOR
if args.no_color:
USE_COLOR = False
if args.path and not os.path.exists(args.path):
print(f"路径不存在: {args.path}", file=sys.stderr)
sys.exit(1)
rows = collect(args)
# 挂载点排序:/ 优先,其余按字母
rows.sort(key=lambda r: (r[-1] != "/", r[-1]))
print_table(rows, args)
if __name__ == "__main__":
main()