scpkg 0.1.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,145 @@
1
+ """YAML 配置读写:`read_yaml()` / `write_yaml()`;`default_yaml_file()` 从 paths 复用。
2
+
3
+ 读取原则:只有"文件不存在"和"文件损坏"会停下等人工,其余情况把 `safe_load` 的结果
4
+ 原样返回,不校验顶层类型。
5
+ 写入原则:先写同目录 `.tmp` 并 fsync,再用 `os.replace` 原子换名;Windows 上目标被
6
+ 占用时退回直接覆盖写。
7
+
8
+ 失败约定:类型不支持、解析失败等记 ERROR 后 `exit(1)`;`write_yaml` 的"目标被占用"
9
+ 只降级为 WARNING + 直接覆盖。
10
+ """
11
+
12
+ import logging
13
+ import os
14
+ import pathlib
15
+ import sys
16
+ from typing import Optional, Union
17
+
18
+ import yaml
19
+
20
+ from .paths import default_yaml_file
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ def write_yaml(config: object,
26
+ config_file: Optional[Union[str, pathlib.Path]] = None) -> None:
27
+ """把 config 写成 UTF-8 YAML 文件(保留中文和插入顺序)。
28
+
29
+ 参数:
30
+ config: 必填、位置在前。只接受 dict / list / str / int / float / bool / None,
31
+ tuple / set / date / 自定义对象一律拒绝。用 `safe_dump` 写出,
32
+ 保证 `read_yaml()` 一定读得回来。
33
+ config_file: 目标路径,省略时为 `<脚本目录>/configs/<脚本名>.config.yaml`。
34
+
35
+ 退出:
36
+ config 类型不支持,或 `safe_dump` 失败时,记 ERROR 后 `exit(1)`。
37
+
38
+ 注意:
39
+ - 原子落盘:写同目录 `<文件名>.tmp` → flush + fsync → `os.replace`。写到一半被
40
+ 强杀 / 崩溃 / 断电时,目标文件仍是上一次的完整内容。`.tmp` 由 finally 清理;
41
+ 被强杀时残留的 `.tmp` 会被下次写入覆盖,不影响正确性。
42
+ - `.tmp` 必须与目标同目录:跨盘符的 replace 不保证原子,所以不复用系统临时目录。
43
+ - Windows 上目标文件被别的进程以"不共享删除"方式打开时,`os.replace` 抛
44
+ PermissionError;此时记 WARNING 并退回直接覆盖写 —— 这一趟没有原子保护,
45
+ 但保证配置存得下。连直接写也失败(真没权限 / 磁盘问题)则异常照常抛出。
46
+ - 顶层是裸标量时,去掉 `safe_dump` 补的 `...` 结束标记,让文件更干净。
47
+ """
48
+ if not isinstance(config, (dict, list, str, int, float, bool, type(None))):
49
+ logger.error(
50
+ f"write_yaml 的 config 类型不支持:{type(config).__name__},"
51
+ f"只接受 dict/list/str/int/float/bool/None,请人工介入后重新运行,脚本退出"
52
+ )
53
+ sys.exit(1)
54
+
55
+ try:
56
+ text = yaml.safe_dump(
57
+ config, allow_unicode=True, sort_keys=False, default_flow_style=False
58
+ )
59
+ except Exception as exc:
60
+ logger.error(
61
+ f"write_yaml 转成 YAML 失败:{type(exc).__name__}: {exc},"
62
+ f"请人工介入后重新运行,脚本退出"
63
+ )
64
+ sys.exit(1)
65
+
66
+ # 顶层是裸标量时 safe_dump 会在结尾补 "..."+换行 结束标记,去掉让文件更干净
67
+ if text.endswith("\n...\n"):
68
+ text = text[: -len("\n...\n")] + "\n"
69
+
70
+ if config_file is None:
71
+ config_file = default_yaml_file()
72
+ path = pathlib.Path(config_file)
73
+ path.parent.mkdir(parents=True, exist_ok=True)
74
+
75
+ # 原子落盘:写同目录临时文件 -> flush + fsync -> os.replace 换名。
76
+ tmp = path.with_name(path.name + ".tmp")
77
+ try:
78
+ with tmp.open("w", encoding="utf-8") as f:
79
+ f.write(text)
80
+ f.flush()
81
+ os.fsync(f.fileno())
82
+ try:
83
+ os.replace(tmp, path)
84
+ except PermissionError as exc:
85
+ # 目标文件被别的进程以"不共享删除"方式打开时改名会被拒(实测只有另一个
86
+ # Python 进程 open() 挂着句柄才会挡,记事本、PowerShell 都不挡)。
87
+ # 保存这件事还得继续,退回直接覆盖写:这一趟没有原子保护,但功能不丢。
88
+ logger.warning(
89
+ f"配置文件被占用,原子替换失败(WinError {exc.winerror}),"
90
+ f"退回直接覆盖写入: {path}"
91
+ )
92
+ with path.open("w", encoding="utf-8") as f:
93
+ f.write(text)
94
+ f.flush()
95
+ os.fsync(f.fileno())
96
+ finally:
97
+ # Path.unlink(missing_ok=True) 是 3.8 才有的参数;3.6/3.7 只能用 try/except。
98
+ # 成功时 tmp 已被 replace 走,这里就是 FileNotFoundError 空操作。
99
+ try:
100
+ tmp.unlink()
101
+ except FileNotFoundError:
102
+ pass
103
+ logger.info(f"配置已写入: {path}")
104
+
105
+
106
+ def read_yaml(config_file: Optional[Union[str, pathlib.Path]] = None,
107
+ default_config: dict = {}) -> object:
108
+ """读取 YAML 配置文件,返回 `safe_load` 的结果(不校验顶层类型)。
109
+
110
+ 参数:
111
+ config_file: 目标路径,省略时为 `<脚本目录>/configs/<脚本名>.config.yaml`。
112
+ default_config: 仅在"文件不存在"时用于生成模板。
113
+
114
+ 返回:
115
+ dict / list / 标量 / None 都可能;空文件、纯注释、`null` 都返回 None。
116
+ 需要当 dict 用请自己收窄。
117
+
118
+ 退出:
119
+ 文件不存在:按 default_config 写出模板,记 ERROR 后 `exit(1)`;
120
+ 非 UTF-8 或 YAML 语法错误:记 ERROR 后 `exit(1)`,坏文件原样保留。
121
+ """
122
+ if config_file is None:
123
+ config_file = default_yaml_file()
124
+ path = pathlib.Path(config_file)
125
+
126
+ if not path.is_file():
127
+ # 写模板后立刻退出,所以 default_config 不需要深拷贝。
128
+ write_yaml(default_config, path)
129
+ logger.error(
130
+ f"配置文件不存在: {path},已按默认配置生成模板,请检查修改后重新运行本脚本"
131
+ )
132
+ sys.exit(1)
133
+
134
+ try:
135
+ with path.open("r", encoding="utf-8") as f:
136
+ loaded = yaml.safe_load(f)
137
+ except (UnicodeDecodeError, yaml.YAMLError) as exc:
138
+ logger.error(
139
+ f"配置文件加载/解析失败: {path},错误信息: {exc},"
140
+ f"坏文件原样保留,请人工处置后重新运行,脚本退出"
141
+ )
142
+ sys.exit(1)
143
+
144
+ logger.info(f"配置已加载: {path}")
145
+ return loaded