This commit is contained in:
lou
2026-08-09 21:51:44 +08:00
commit 3da2cecc69
2 changed files with 96 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
{
"python.defaultInterpreterPath": "/home/lou/文档/7z-encrypt/.venv/bin/python",
"python.terminal.activateEnvironment": true,
"python.analysis.extraPaths": [
"/home/lou/文档/7z-encrypt/.venv/lib/python3.11/site-packages"
]
}
+89
View File
@@ -0,0 +1,89 @@
import os
import hashlib
class FileReader:
"""
实现01-文件读取.md描述的 file_reader 模块。
功能描述:
- 支持流式读取大文件,不阻塞内存。
- 校验文件存在性及可读性。
- 实时计算总大小和SHA-256哈希值。
"""
def __init__(self, file_path: str, chunk_size: int = 1 * 1024 * 1024):
"""
A[接收文件路径 + 卷大小]
Args:
file_path (str): 目标文件的路径。
chunk_size (int): 单次读取的数据块大小(字节),默认1MB。
"""
self.file_path = file_path
self.chunk_size = chunk_size
# B["文件存在 / 可读 ?"] -> 校验节点
if not os.path.exists(file_path):
raise FileNotFoundError(f"文件不存在: {file_path}")
if not os.access(file_path, os.R_OK):
raise PermissionError(f"无读权限: {file_path}")
def __iter__(self):
# C["打开二进制流"]
self._total_size = 0
self._sha256_hash = hashlib.sha256()
with open(self.file_path, 'rb') as f:
while True:
chunk = f.read(self.chunk_size)
# E["EOF ?"] -> 检查文件是否结束
if not chunk:
break
# 更新元数据状态 (对应F节点输出的元信息)
self._total_size += len(chunk)
self._sha256_hash.update(chunk)
yield chunk
@property
def total_size(self) -> int:
"""返回文件总大小"""
return self._total_size
@property
def sha256_hash(self) -> str:
"""返回SHA-256哈希值"""
return self._sha256_hash.hexdigest()
# --- 使用示例 (Usage Example) ---
if __name__ == "__main__":
try:
# 初始化读取器
reader = FileReader("kali-2026.zip", chunk_size=1024*1024)
print(f"开始读取...")
total_chunks = 0
# D/E/F节点逻辑:遍历数据流并模拟下游处理
for data_chunk in reader:
# 此处模拟传递给 crypto 加密引擎
# process_crypto_engine(data_chunk)
total_chunks += 1
# 可选:实时查看进度 (实际工程中通常由外部状态管理模块处理)
print(f"已读取第 {total_chunks} 块数据,当前大小: {reader.total_size} bytes")
print("-" * 30)
print(f"文件读取完毕。")
print(f"总大小: {reader.total_size} bytes")
print(f"SHA-256: {reader.sha256_hash}")
except Exception as e:
# B节点报错处理
print(f"读取失败: {e}")