-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisk_cleaner.py
More file actions
717 lines (636 loc) · 22.4 KB
/
Copy pathdisk_cleaner.py
File metadata and controls
717 lines (636 loc) · 22.4 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Windows 磁盘清理工具(侧重 C 盘)。
默认仅扫描并报告可释放空间;使用 --apply 才会删除。
部分目录需要管理员权限。
"""
from __future__ import annotations
import argparse
import ctypes
import os
import subprocess
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Iterable
# ---------------------------------------------------------------------------
# 基础工具
# ---------------------------------------------------------------------------
def is_admin() -> bool:
try:
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
def human_bytes(n: int) -> str:
if n < 0:
n = 0
units = ("B", "KB", "MB", "GB", "TB")
v = float(n)
for u in units:
if v < 1024.0 or u == units[-1]:
if u == "B":
return f"{int(v)} {u}"
return f"{v:.2f} {u}"
v /= 1024.0
return f"{n} B"
def iter_files(root: Path) -> Iterable[Path]:
try:
for dirpath, _dirnames, filenames in os.walk(root, topdown=True, onerror=None):
base = Path(dirpath)
for name in filenames:
yield base / name
except (OSError, PermissionError):
return
def dir_size(root: Path) -> tuple[int, int]:
"""返回 (可统计的字节数, 无法访问的文件数)。"""
total = 0
errors = 0
for p in iter_files(root):
try:
if p.is_file():
total += p.stat().st_size
except (OSError, PermissionError):
errors += 1
return total, errors
def safe_rmtree_contents(root: Path, on_progress: Callable[[], None] | None = None) -> tuple[int, int]:
"""删除 root 下所有子项,保留 root 目录本身。"""
removed_bytes = 0
failures = 0
if not root.exists() or not root.is_dir():
return 0, 0
for child in list(root.iterdir()):
try:
if child.is_file() or child.is_symlink():
try:
removed_bytes += child.stat().st_size
except OSError:
pass
child.unlink(missing_ok=True)
elif child.is_dir():
b, f = safe_rmtree_contents(child, on_progress)
removed_bytes += b
failures += f
try:
child.rmdir()
except OSError:
failures += 1
except (OSError, PermissionError):
failures += 1
if on_progress:
on_progress()
return removed_bytes, failures
def empty_recycle_bin() -> tuple[bool, str]:
try:
r = subprocess.run(
[
"powershell.exe",
"-NoProfile",
"-NonInteractive",
"-Command",
"Clear-RecycleBin -Force -ErrorAction Stop",
],
capture_output=True,
text=True,
timeout=600,
)
if r.returncode == 0:
return True, ""
msg = (r.stderr or r.stdout or "").strip() or f"exit {r.returncode}"
return False, msg
except Exception as e:
return False, str(e)
def disable_hibernation() -> tuple[bool, str]:
"""关闭休眠并删除 hiberfil.sys(需管理员)。"""
try:
r = subprocess.run(
["powercfg.exe", "/h", "off"],
capture_output=True,
text=True,
timeout=60,
)
if r.returncode == 0:
return True, ""
msg = (r.stderr or r.stdout or "").strip() or f"exit {r.returncode}"
return False, msg
except Exception as e:
return False, str(e)
def file_size_safe(path: Path) -> int:
try:
return path.stat().st_size
except OSError:
return 0
# ---------------------------------------------------------------------------
# 清理目标
# ---------------------------------------------------------------------------
@dataclass
class CleanTarget:
key: str
title: str
path: Path # 主显示路径
extra_paths: list[Path] = field(default_factory=list)
needs_admin_hint: bool = False
note: str = ""
info_only: bool = False # 仅展示,不参与勾选与清理
label_only_path: bool = False # 若 True,path 仅作显示,不参与清理/统计
_size_cache: tuple[int, int] | None = field(default=None, repr=False)
# ---- 路径处理 ----
def resolve(self) -> Path:
try:
return self.path.expanduser().resolve()
except Exception:
return self.path
def all_paths(self) -> list[Path]:
"""返回参与统计与清理的所有路径(不含 label_only_path 时的 self.path)。"""
if self.label_only_path:
sources: list[Path] = list(self.extra_paths)
else:
sources = [self.path, *self.extra_paths]
seen: set[str] = set()
out: list[Path] = []
for p in sources:
try:
rp = p.expanduser().resolve()
except Exception:
rp = p
k = str(rp).lower()
if k in seen:
continue
seen.add(k)
out.append(rp)
return out
def display_paths(self) -> list[Path]:
"""用于 UI 显示的路径:始终包含主路径在前。"""
seen: set[str] = set()
out: list[Path] = []
for p in [self.path, *self.extra_paths]:
try:
rp = p.expanduser().resolve()
except Exception:
rp = p
k = str(rp).lower()
if k in seen:
continue
seen.add(k)
out.append(rp)
return out
# ---- 体积 ----
def size(self) -> tuple[int, int]:
if self._size_cache is not None:
return self._size_cache
if self.key == "thumbcache":
total, errors = 0, 0
for p in self.all_paths():
if p.exists():
for f in p.glob("thumbcache_*.db"):
try:
total += f.stat().st_size
except OSError:
errors += 1
self._size_cache = (total, errors)
return self._size_cache
total = 0
errors = 0
for p in self.all_paths():
if not p.exists():
continue
try:
if p.is_file():
total += p.stat().st_size
else:
b, e = dir_size(p)
total += b
errors += e
except (OSError, PermissionError):
errors += 1
self._size_cache = (total, errors)
return self._size_cache
# ---- 清理 ----
def clean(self, dry_run: bool) -> tuple[int, int]:
if self.info_only:
return 0, 0
if self.key == "thumbcache":
total_b, total_f = 0, 0
for p in self.all_paths():
b, f = clean_thumbcache_only(p, dry_run=dry_run)
total_b += b
total_f += f
return total_b, total_f
if self.key == "recycle_bin":
if dry_run:
return self.size()
ok, _ = empty_recycle_bin()
return (0, 0) if ok else (0, 1)
if self.key == "hibernation":
if dry_run:
return self.size()
ok, _ = disable_hibernation()
return (0, 0) if ok else (0, 1)
total_b, total_f = 0, 0
for p in self.all_paths():
if not p.exists():
continue
if dry_run:
if p.is_file():
total_b += file_size_safe(p)
else:
b, _ = dir_size(p)
total_b += b
continue
if p.is_file():
try:
b = p.stat().st_size
p.unlink()
total_b += b
except OSError:
total_f += 1
else:
b, f = safe_rmtree_contents(p)
total_b += b
total_f += f
return total_b, total_f
# ---------------------------------------------------------------------------
# 浏览器缓存路径搜索
# ---------------------------------------------------------------------------
CHROMIUM_CACHE_SUBDIRS = (
"Cache",
"Code Cache",
"GPUCache",
"ShaderCache",
Path("Service Worker") / "CacheStorage",
Path("Service Worker") / "ScriptCache",
)
def _filter_existing(paths: Iterable[Path]) -> list[Path]:
return [p for p in paths if p.exists()]
def find_chromium_cache_dirs(user_data_root: Path) -> list[Path]:
if not user_data_root.exists():
return []
results: list[Path] = []
for profile in user_data_root.iterdir():
try:
if not profile.is_dir():
continue
except OSError:
continue
name = profile.name
if not (
name == "Default"
or name.startswith("Profile ")
or name in ("Guest Profile", "System Profile")
):
continue
for sub in CHROMIUM_CACHE_SUBDIRS:
results.append(profile / sub)
return _filter_existing(results)
def find_firefox_cache_dirs(local: Path) -> list[Path]:
base = local / "Mozilla" / "Firefox" / "Profiles"
if not base.exists():
return []
results: list[Path] = []
for profile in base.iterdir():
try:
if not profile.is_dir():
continue
except OSError:
continue
for sub in ("cache2", "startupCache", "OfflineCache", "thumbnails"):
results.append(profile / sub)
# Firefox 部分缓存也可能在 Roaming 下,但常用的全在 Local 里。
return _filter_existing(results)
def _on_drive(p: Path, drive: str) -> bool:
try:
return str(p).upper().startswith(drive.upper())
except Exception:
return False
# ---------------------------------------------------------------------------
# 构造目标列表
# ---------------------------------------------------------------------------
def build_targets(drive: str) -> list[CleanTarget]:
drive = drive.rstrip("\\/").upper()
if len(drive) != 2 or drive[1] != ":":
raise ValueError("驱动器格式应为 C: 或 D:")
windir = Path(os.environ.get("WINDIR", f"{drive}\\Windows"))
local = Path(os.environ.get("LOCALAPPDATA", ""))
targets: list[CleanTarget] = []
system_drive = (os.environ.get("SystemDrive", "C:") or "C:").upper()
is_system_drive = drive == system_drive
# ---- 临时目录 ----
for env in ("TEMP", "TMP"):
raw = os.environ.get(env)
if raw:
p = Path(raw)
if _on_drive(p, drive):
targets.append(
CleanTarget(
key=f"user_{env.lower()}",
title=f"用户临时目录 ({env})",
path=p,
note="当前登录用户的临时文件,通常可安全清理。",
)
)
if is_system_drive:
targets.append(
CleanTarget(
key="windows_temp",
title="Windows\\Temp",
path=windir / "Temp",
needs_admin_hint=True,
note="系统级临时目录;部分文件可能被服务占用。",
)
)
targets.append(
CleanTarget(
key="prefetch",
title="Prefetch(可选)",
path=windir / "Prefetch",
needs_admin_hint=True,
note="预读取数据;删除后可能短暂影响启动预测,一般可清理。",
)
)
targets.append(
CleanTarget(
key="softdist_download",
title="Windows Update 缓存 (SoftwareDistribution\\Download)",
path=windir / "SoftwareDistribution" / "Download",
needs_admin_hint=True,
note="Windows 更新已下载的安装包;建议先停止 wuauserv 服务。",
)
)
program_data = Path(os.environ.get("ProgramData", f"{drive}\\ProgramData"))
targets.append(
CleanTarget(
key="wer",
title="Windows 错误报告 (WER)",
path=program_data / "Microsoft" / "Windows" / "WER",
extra_paths=[
local / "Microsoft" / "Windows" / "WER" if local else program_data,
],
needs_admin_hint=True,
note="错误报告与崩溃转储,可清理。",
)
)
# ---- 用户级缓存 ----
if local.exists() and _on_drive(local, drive):
targets.append(
CleanTarget(
key="inet_cache",
title="IE/旧版 Edge 缓存 (INetCache)",
path=local / "Microsoft" / "Windows" / "INetCache",
note="旧式 Web 缓存。",
)
)
targets.append(
CleanTarget(
key="thumbcache",
title="缩略图缓存",
path=local / "Microsoft" / "Windows" / "Explorer",
note="仅清理 thumbcache_*.db(缩略图会自动重建)。",
)
)
targets.append(
CleanTarget(
key="crash_dumps",
title="本机崩溃转储 (CrashDumps)",
path=local / "CrashDumps",
note="应用崩溃 dump 文件。",
)
)
# Chrome
chrome_root = local / "Google" / "Chrome" / "User Data"
chrome_dirs = find_chromium_cache_dirs(chrome_root)
if chrome_dirs:
targets.append(
CleanTarget(
key="chrome_cache",
title=f"Chrome 缓存({len(chrome_dirs)} 项)",
path=chrome_root,
extra_paths=chrome_dirs,
label_only_path=True,
note="仅清理各 Profile 下的 Cache/Code Cache/GPUCache 等;建议先关闭 Chrome。",
)
)
# Edge
edge_root = local / "Microsoft" / "Edge" / "User Data"
edge_dirs = find_chromium_cache_dirs(edge_root)
if edge_dirs:
targets.append(
CleanTarget(
key="edge_cache",
title=f"Edge 缓存({len(edge_dirs)} 项)",
path=edge_root,
extra_paths=edge_dirs,
label_only_path=True,
note="仅清理各 Profile 下的 Cache/Code Cache/GPUCache 等;建议先关闭 Edge。",
)
)
# Firefox
firefox_dirs = find_firefox_cache_dirs(local)
if firefox_dirs:
targets.append(
CleanTarget(
key="firefox_cache",
title=f"Firefox 缓存({len(firefox_dirs)} 项)",
path=local / "Mozilla" / "Firefox" / "Profiles",
extra_paths=firefox_dirs,
label_only_path=True,
note="仅清理各 Profile 下的 cache2 等;建议先关闭 Firefox。",
)
)
# ---- Delivery Optimization ----
if is_system_drive:
targets.append(
CleanTarget(
key="delivery_opt",
title="传递优化缓存 (Delivery Optimization)",
path=windir
/ "ServiceProfiles"
/ "NetworkService"
/ "AppData"
/ "Local"
/ "Microsoft"
/ "Windows"
/ "DeliveryOptimization"
/ "Cache",
needs_admin_hint=True,
note="Windows 更新 P2P 缓存;常需管理员权限。",
)
)
# ---- 回收站 ----
targets.append(
CleanTarget(
key="recycle_bin",
title="回收站",
path=Path(f"{drive}\\$Recycle.Bin"),
needs_admin_hint=True,
note="清空所有分区回收站条目(调用 Clear-RecycleBin)。",
)
)
# ---- 系统大文件:休眠 / 分页 ----
if is_system_drive:
targets.append(
CleanTarget(
key="hibernation",
title="休眠文件 hiberfil.sys(关闭休眠以删除)",
path=Path(f"{drive}\\hiberfil.sys"),
needs_admin_hint=True,
note="执行 powercfg /h off;之后将无法使用休眠/快速启动。",
)
)
targets.append(
CleanTarget(
key="pagefile_info",
title="分页文件 pagefile.sys(仅信息)",
path=Path(f"{drive}\\pagefile.sys"),
info_only=True,
note="由系统管理;如需缩小请在“系统属性 → 性能 → 高级 → 虚拟内存”中调整。",
)
)
targets.append(
CleanTarget(
key="swapfile_info",
title="交换文件 swapfile.sys(仅信息)",
path=Path(f"{drive}\\swapfile.sys"),
info_only=True,
note="UWP 应用使用;通常不建议手动清理。",
)
)
# 去重
seen: set[str] = set()
unique: list[CleanTarget] = []
for t in targets:
try:
k = (t.key, str(t.resolve()).lower())
except Exception:
k = (t.key, str(t.path).lower())
if k in seen:
continue
seen.add(k)
unique.append(t)
return unique
def clean_thumbcache_only(root: Path, dry_run: bool) -> tuple[int, int]:
removed = 0
fails = 0
if not root.exists():
return 0, 0
for p in root.glob("thumbcache_*.db"):
try:
if dry_run:
removed += p.stat().st_size
else:
b = p.stat().st_size
p.unlink()
removed += b
except OSError:
fails += 1
return removed, fails
def run_dism_reset_base(dry_run: bool) -> None:
cmd = [
"DISM.exe",
"/Online",
"/Cleanup-Image",
"/StartComponentCleanup",
"/ResetBase",
]
print("\n[DISM] 命令:", " ".join(cmd))
print("说明:会压缩/清理组件存储,耗时较长,需要管理员;/ResetBase 不可轻易撤销。")
if dry_run:
print("[DISM] 模拟运行:未执行。")
return
if not is_admin():
print("[DISM] 需要管理员权限,已跳过。")
return
subprocess.run(cmd, check=False)
def configure_stdio_utf8() -> None:
"""让中文在 Windows 控制台正常显示。"""
for stream in (sys.stdout, sys.stderr):
reconf = getattr(stream, "reconfigure", None)
if callable(reconf):
try:
reconf(encoding="utf-8", errors="replace")
except Exception:
pass
# ---------------------------------------------------------------------------
# CLI 入口
# ---------------------------------------------------------------------------
def main() -> int:
configure_stdio_utf8()
parser = argparse.ArgumentParser(
description="Windows 磁盘清理(默认只扫描,--apply 才删除)",
)
parser.add_argument(
"--drive",
default=os.environ.get("SystemDrive", "C:"),
help="目标盘符,默认系统盘",
)
parser.add_argument(
"--apply",
action="store_true",
help="实际执行删除;不加此参数仅估算空间",
)
parser.add_argument(
"--targets",
default="all",
help="逗号分隔的目标 key,或 all。key 见扫描输出第一列。",
)
parser.add_argument(
"--dism",
action="store_true",
help="(危险/慢)在 --apply 且管理员下尝试 DISM 组件存储清理",
)
args = parser.parse_args()
try:
all_targets = build_targets(args.drive)
except ValueError as e:
print(e, file=sys.stderr)
return 2
selected = all_targets
if args.targets.strip().lower() != "all":
keys = {k.strip().lower() for k in args.targets.split(",") if k.strip()}
selected = [t for t in all_targets if t.key.lower() in keys]
missing = keys - {t.key.lower() for t in selected}
if missing:
print("未知 target:", ", ".join(sorted(missing)), file=sys.stderr)
dry_run = not args.apply
print("模式:", "【模拟】仅统计" if dry_run else "【执行】将尝试删除")
print("目标盘:", args.drive.upper())
print("管理员:", "是" if is_admin() else "否(部分目录可能无法清理)")
print()
total_bytes = 0
for t in selected:
sz, errn = t.size()
flag = " [建议管理员]" if t.needs_admin_hint and not is_admin() else ""
kind = "(信息)" if t.info_only else ""
print(f"{t.key:18} {human_bytes(sz):>12} 无法读≈{errn} {t.title}{flag} {kind}")
for p in t.display_paths():
print(f" 路径: {p}")
if t.note:
print(f" 说明: {t.note}")
if not t.info_only:
total_bytes += sz
print()
print("估算可清理(扫描到的文件体积,实际释放可能略少):", human_bytes(total_bytes))
if dry_run:
print("\n若要真正清理,请使用: python disk_cleaner.py --apply --drive", args.drive)
if args.dism:
run_dism_reset_base(dry_run=True)
return 0
print("\n开始清理…")
freed = 0
fail_total = 0
for t in selected:
if t.info_only:
continue
b, f = t.clean(dry_run=False)
freed += b
fail_total += f
print(f" {t.key}: 处理约 {human_bytes(b)},失败项 {f}")
print()
print("完成。粗略释放/处理:", human_bytes(freed), "失败项:", fail_total)
if args.dism:
run_dism_reset_base(dry_run=False)
return 0
if __name__ == "__main__":
if os.name != "nt":
print("本脚本仅适用于 Windows。", file=sys.stderr)
sys.exit(1)
raise SystemExit(main())