-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
83 lines (60 loc) · 2.35 KB
/
Copy pathmain.py
File metadata and controls
83 lines (60 loc) · 2.35 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
"""Command-line entry point for FolderVisualizer v0.2.0."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from models import ScanResult
from scanner import scan_folder
OUTPUT_PATH = Path(__file__).resolve().parent / "outputs" / "scan-result.json"
def _format_size(size: int) -> str:
units = ("B", "KB", "MB", "GB", "TB")
value = float(size)
for unit in units:
if value < 1024 or unit == units[-1]:
return f"{int(value)} {unit}" if unit == "B" else f"{value:.2f} {unit}"
value /= 1024
return f"{size} B"
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="扫描文件夹并输出汇总信息")
parser.add_argument("path", nargs="?", help="需要扫描的文件夹路径")
return parser.parse_args()
def _save_result(result: ScanResult) -> Path:
"""Save a scan result as UTF-8 JSON and return the output path."""
OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
with OUTPUT_PATH.open("w", encoding="utf-8") as output_file:
json.dump(result.to_dict(), output_file, ensure_ascii=False, indent=2)
output_file.write("\n")
return OUTPUT_PATH
def main() -> int:
args = _parse_args()
path = args.path or input("请输入要扫描的文件夹路径: ").strip()
if not path:
print("错误: 文件夹路径不能为空。")
return 1
try:
result = scan_folder(path)
except (FileNotFoundError, NotADirectoryError) as error:
print(f"错误: {error}")
return 1
except KeyboardInterrupt:
print("\n扫描已取消。")
return 130
print("\n扫描完成")
print(f"路径: {result.root.path}")
print(f"总大小: {_format_size(result.total_size)} ({result.total_size} 字节)")
print(f"文件数量: {result.file_count}")
print(f"目录数量: {result.directory_count}(包含根目录)")
print(f"扫描错误: {len(result.errors)}")
if result.errors:
print("\n错误详情:")
for message in result.errors:
print(f"- {message}")
try:
output_path = _save_result(result)
except OSError as error:
print(f"\n错误: 无法保存 JSON 文件: {error}")
return 1
print(f"JSON 文件: {output_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())