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,147 @@
1
+ """工作时段判断:按星期几 + `HHMM-HHMM` 时段判断当前时间是否在上班时间内。
2
+
3
+ 失败约定:配置写法不合法(键或值的任何一处)记 ERROR 后 `exit(1)`,不猜、不补全;
4
+ 配置为空或今天没有排班则返回 False。
5
+ """
6
+
7
+ import logging
8
+ import re
9
+ import sys
10
+ from datetime import datetime
11
+ from typing import Optional
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ _DAY_RE = re.compile(r"[1-7]") # 单个星期数字:1=周一 … 7=周日
16
+ _PERIOD_RE = re.compile(r"([0-9]{4})-([0-9]{4})") # 时段:"0900-1200",两端各 4 位数字
17
+
18
+
19
+ def is_worktime(worktime_config: Optional[dict] = None) -> bool:
20
+ """判断当前时间是否落在工作时段内。
21
+
22
+ 配置形如 `{星期: ["HHMM-HHMM", ...]}`:
23
+
24
+ - 键:1=周一 … 7=周日,写单个数字(`"3"`)或 `"起-止"` 区间(`"1-5"`)。
25
+ 区间两端都是 1–7 且起 ≤ 止,不支持跨周;同一星期写多次以最后一次为准。
26
+ - 值:`"HHMM-HHMM"` 字符串列表,两端各 4 位数字且起 ≤ 止,左闭右开 `[起, 止)`;
27
+ 这天不上班写空列表 `[]`;不支持跨零点。
28
+
29
+ 参数:
30
+ worktime_config: 工作时段配置,省略或为空(None / {})时返回 False。
31
+
32
+ 返回:
33
+ 当前时间在任一时段内返回 True,否则 False。
34
+ 只校验形状不校验语义:`"2400-2500"`、`"0961"` 这类写法会放行,
35
+ 但因为匹配不上而一直返回 False。
36
+
37
+ 退出:
38
+ 键或值写法不合法时,ERROR 说清是哪个键、哪个时段、错在哪,然后 `exit(1)`。
39
+ 整个配置都会校验,不是只看今天那一行;不做任何猜测或自动补全
40
+ (`"900"` 不会补成 `"0900"`,裸字符串不会补成单元素列表)。
41
+
42
+ 注意:
43
+ 每次调用只写一条 INFO 结论;逐时段的比较过程和时段列表写在 DEBUG,
44
+ 只在 `*_debug.log` 里,不会刷屏。
45
+ """
46
+ weekday_names = {1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 7: "日"}
47
+
48
+ if not worktime_config:
49
+ logger.warning("工作时段配置为空 → False")
50
+ return False
51
+
52
+ if not isinstance(worktime_config, dict):
53
+ logger.error(
54
+ f"is_worktime 配置格式错误:worktime_config 是 {type(worktime_config).__name__},"
55
+ f"要求形如 {{星期: [\"HHMM-HHMM\", …]}} 的字典,脚本退出"
56
+ )
57
+ sys.exit(1)
58
+
59
+ expanded = {}
60
+ for key, periods in worktime_config.items():
61
+ key_text = str(key).strip()
62
+
63
+ # —— 校验键:单个 1-7,或 "起-止" 区间(起 <= 止)——
64
+ if "-" in key_text: # 区间写法,例如 "3-5" 表示星期三到星期五
65
+ head, _, tail = (part.strip() for part in key_text.partition("-"))
66
+ if not _DAY_RE.fullmatch(head) or not _DAY_RE.fullmatch(tail):
67
+ logger.error(
68
+ f"is_worktime 星期键格式错误:{key_text!r},区间写法必须是 \"起-止\","
69
+ f"两端都是 1-7 的单个数字(1=周一 … 7=周日),例如 \"1-5\",脚本退出"
70
+ )
71
+ sys.exit(1)
72
+ first_day, last_day = int(head), int(tail)
73
+ if first_day > last_day:
74
+ logger.error(
75
+ f"is_worktime 星期键格式错误:{key_text!r},起 {first_day} 大于止 {last_day},"
76
+ f"不支持跨周——周六日再加周一请拆成 \"6-7\" 和 \"1\" 两行,脚本退出"
77
+ )
78
+ sys.exit(1)
79
+ days = [str(day) for day in range(first_day, last_day + 1)]
80
+ elif _DAY_RE.fullmatch(key_text):
81
+ days = [key_text]
82
+ else:
83
+ logger.error(
84
+ f"is_worktime 星期键格式错误:{key_text!r},键只能是 1-7 的单个数字"
85
+ f"(1=周一 … 7=周日),或 \"1-5\" 这种起不大于止的区间,脚本退出"
86
+ )
87
+ sys.exit(1)
88
+
89
+ # —— 校验值:空列表,或 "HHMM-HHMM" 字符串列表(起 <= 止)——
90
+ if not isinstance(periods, (list, tuple)):
91
+ logger.error(
92
+ f"is_worktime 时段格式错误:{key_text!r} 的值是 {type(periods).__name__},"
93
+ f"必须是 \"HHMM-HHMM\" 字符串组成的列表,这天不上班写空列表 [],脚本退出"
94
+ )
95
+ sys.exit(1)
96
+
97
+ for period in periods:
98
+ matched = _PERIOD_RE.fullmatch(period) if isinstance(period, str) else None
99
+ if matched is None:
100
+ logger.error(
101
+ f"is_worktime 时段格式错误:{key_text!r} 里的 {period!r}"
102
+ f"{'' if isinstance(period, str) else f'({type(period).__name__})'},"
103
+ f"时段必须是 \"HHMM-HHMM\",两端各 4 位数字,例如 \"0900-1200\",脚本退出"
104
+ )
105
+ sys.exit(1)
106
+ if int(matched.group(1)) > int(matched.group(2)):
107
+ logger.error(
108
+ f"is_worktime 时段格式错误:{key_text!r} 里的 {period!r},"
109
+ f"起 {matched.group(1)} 大于止 {matched.group(2)},不支持跨零点——"
110
+ f"22:00 上到次日 02:00 请拆成 \"2200-2400\" 和 \"0000-0200\",脚本退出"
111
+ )
112
+ sys.exit(1)
113
+
114
+ for day in days:
115
+ expanded[day] = periods
116
+
117
+ now = datetime.now()
118
+ weekday = str(now.weekday() + 1)
119
+ current = now.hour * 100 + now.minute
120
+ today_periods = expanded.get(weekday, [])
121
+ day_label = f"星期{weekday_names[int(weekday)]} {now:%H:%M}"
122
+
123
+ if not today_periods:
124
+ logger.info(f"{day_label} 今天没有排班 → False")
125
+ return False
126
+
127
+ logger.debug(f"{day_label} 时段列表 = {today_periods}")
128
+
129
+ for period in today_periods:
130
+ # 能走到这里说明上面已整体校验通过,period 必定是 "HHMM-HHMM",可以放心拆
131
+ start, end = period.split("-")
132
+ start_value, end_value = int(start), int(end)
133
+ hit = start_value <= current < end_value
134
+ logger.debug(
135
+ f"{day_label} 检查时段 {period} → "
136
+ f"{start_value:04d} <= {current:04d} < {end_value:04d} → "
137
+ f"{'命中' if hit else '未命中'}"
138
+ )
139
+ if hit:
140
+ logger.info(f"{day_label} 命中时段 {period} → True")
141
+ return True
142
+
143
+ logger.info(
144
+ f"{day_label} 未命中任何时段 → False"
145
+ f"(今天排班:{'、'.join(today_periods)})"
146
+ )
147
+ return False
@@ -0,0 +1,193 @@
1
+ """MQTT 一次性发布器:`MqttPublisher`。
2
+
3
+ 凭据只来自构造函数参数:本文件不硬编码、不读环境变量(本包会发布到 PyPI,源码里的
4
+ 任何真实凭据都会公开)。建议放在自己的 YAML 配置里,用 `read_yaml()` 读出来再传。
5
+
6
+ 失败约定:构造只保存参数,不校验也不抛异常;`publish()` 负责校验和执行,任何可预期
7
+ 失败(参数错误、paho-mqtt 不可用、连接 / 发布 / 超时)都 `logger.error` + 返回
8
+ False,不抛 Exception(SystemExit / KeyboardInterrupt 属于主动退出,照常向外抛)。
9
+ paho-mqtt 导入失败也不阻塞 `import sc92_lib`。
10
+ """
11
+
12
+ import logging
13
+ import math
14
+ from typing import Optional
15
+
16
+ try:
17
+ import paho.mqtt.client as mqtt
18
+ _MQTT_IMPORT_ERROR = None
19
+ except Exception as _exc: # 缺包 / 包损坏都不阻塞 import sc92_lib,留到 publish() 报错
20
+ mqtt = None
21
+ _MQTT_IMPORT_ERROR = _exc
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class MqttPublisher:
27
+ """一次性 MQTT 发布器:连接、发一条消息、断开。
28
+
29
+ 流程:connect → loop_start → publish → wait_for_publish → 收尾 disconnect / loop_stop。
30
+ 构造只保存参数(不校验、不抛异常),参数校验和所有失败处理都在 `publish()`。
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ host: str,
36
+ port: int = 1883,
37
+ username: Optional[str] = None,
38
+ password: Optional[str] = None,
39
+ topic: Optional[str] = None,
40
+ qos: int = 2,
41
+ client_id: Optional[str] = None,
42
+ connect_timeout: float = 5,
43
+ publish_timeout: float = 10,
44
+ ):
45
+ """保存连接参数,不做校验(校验在 publish() 里)。
46
+
47
+ 参数:
48
+ host: broker 地址,必填。
49
+ port: broker 端口,默认 1883。
50
+ username / password: 认证信息;username 为 None 时匿名连接。
51
+ topic: 默认主题,`publish()` 可单次覆盖。
52
+ qos: 默认 QoS,默认 2,`publish()` 可单次覆盖。
53
+ client_id: 客户端 ID,None 交给 paho 自动生成。
54
+ connect_timeout: TCP 连接建立超时(秒),必须大于 0。
55
+ publish_timeout: 等待 broker 确认的超时(秒),必须不小于 0。
56
+ """
57
+ self.host = host
58
+ self.port = port
59
+ self.username = username
60
+ self.password = password
61
+ self.topic = topic
62
+ self.qos = qos
63
+ self.client_id = client_id
64
+ self.connect_timeout = connect_timeout
65
+ self.publish_timeout = publish_timeout
66
+
67
+ def publish(self, msg, topic: Optional[str] = None, qos: Optional[int] = None) -> bool:
68
+ """发布一条消息;只有 broker 确认收到才返回 True。
69
+
70
+ 参数:
71
+ msg: 消息内容;bytes / bytearray 原样发送,其它类型走 `str()`。
72
+ topic: 单次覆盖实例的 topic。
73
+ qos: 单次覆盖实例的 qos。
74
+
75
+ 返回:
76
+ QoS 1/2 拿到 broker 的确认才算 True;QoS 0 没有确认机制,True 只表示
77
+ 已写入 socket。参数错误、paho 不可用、连不上、超时、其它异常都返回 False。
78
+
79
+ 退出:
80
+ 不退出(SystemExit / KeyboardInterrupt 除外)。
81
+
82
+ 注意:
83
+ - 参数和超时值在这里统一校验:`connect_timeout` 必须大于 0 且有限,
84
+ `publish_timeout` 必须不小于 0 且有限,否则记 ERROR 并返回 False。
85
+ - 整条消息载荷会写进 INFO 日志,别用它发明文密码 / token。
86
+ """
87
+ if mqtt is None:
88
+ logger.error(f"paho-mqtt 不可用,MQTT 消息未发送:{_MQTT_IMPORT_ERROR}")
89
+ return False
90
+
91
+ client = None
92
+ try:
93
+ topic = topic or self.topic
94
+ missing = [n for n, v in (("host", self.host), ("topic", topic)) if not v]
95
+ if missing:
96
+ logger.error(
97
+ f"缺少 MQTT 参数: {', '.join(missing)}。请在调用脚本中显式传入,"
98
+ "凭据建议存放在本地 YAML 配置文件里用 read_yaml() 读取"
99
+ "(本库源码与 PyPI 发布物中不包含任何真实凭据)。"
100
+ )
101
+ return False
102
+ if not isinstance(self.host, str):
103
+ logger.error(
104
+ f"MQTT 参数错误:host 必须是字符串,收到 {type(self.host).__name__},消息未发送"
105
+ )
106
+ return False
107
+ if not isinstance(topic, str):
108
+ logger.error(
109
+ f"MQTT 参数错误:topic 必须是字符串,收到 {type(topic).__name__},消息未发送"
110
+ )
111
+ return False
112
+
113
+ try:
114
+ port = int(self.port)
115
+ except Exception:
116
+ logger.error(
117
+ f"MQTT 参数错误:port 必须是整数,收到 {type(self.port).__name__},消息未发送"
118
+ )
119
+ return False
120
+ raw_qos = self.qos if qos is None else qos
121
+ try:
122
+ use_qos = int(raw_qos)
123
+ except Exception:
124
+ logger.error(
125
+ f"MQTT 参数错误:qos 必须是整数,收到 {type(raw_qos).__name__},消息未发送"
126
+ )
127
+ return False
128
+
129
+ try:
130
+ connect_timeout = float(self.connect_timeout)
131
+ publish_timeout = float(self.publish_timeout)
132
+ except Exception:
133
+ logger.error(
134
+ "MQTT 参数错误:connect_timeout / publish_timeout 必须是数字,"
135
+ f"收到 {type(self.connect_timeout).__name__} / "
136
+ f"{type(self.publish_timeout).__name__},消息未发送"
137
+ )
138
+ return False
139
+ if not math.isfinite(connect_timeout) or connect_timeout <= 0:
140
+ logger.error(
141
+ f"MQTT 参数错误:connect_timeout 必须是大于 0 的有限数字,"
142
+ f"收到 {connect_timeout},消息未发送"
143
+ )
144
+ return False
145
+ if not math.isfinite(publish_timeout) or publish_timeout < 0:
146
+ logger.error(
147
+ f"MQTT 参数错误:publish_timeout 必须是不小于 0 的有限数字,"
148
+ f"收到 {publish_timeout},消息未发送"
149
+ )
150
+ return False
151
+
152
+ payload = msg if isinstance(msg, (bytes, bytearray)) else str(msg)
153
+
154
+ # paho 2.x 才有 CallbackAPIVersion;3.6 上最高只能装 1.6.1,回调 API 是旧式。
155
+ # 本类不注册任何回调,所以两个分支只差 Client 的构造方式。
156
+ if hasattr(mqtt, "CallbackAPIVersion"):
157
+ client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=self.client_id)
158
+ else:
159
+ client = mqtt.Client(client_id=self.client_id)
160
+ if self.username is not None:
161
+ client.username_pw_set(self.username, self.password)
162
+ # paho 2.x 的 connect_timeout 是 property;1.6.1 只认私有的 _connect_timeout,
163
+ # 给公开属性赋值是个死变量。两个都设,保证两代 paho 都真正受这个超时限制。
164
+ client.connect_timeout = connect_timeout
165
+ if hasattr(client, "_connect_timeout"):
166
+ client._connect_timeout = connect_timeout
167
+
168
+ logger.info(f"正在连接 MQTT Broker {self.host}:{port} ...")
169
+ client.connect(self.host, port, keepalive=60)
170
+ client.loop_start()
171
+
172
+ info = client.publish(topic, payload=payload, qos=use_qos)
173
+ info.wait_for_publish(timeout=publish_timeout)
174
+ if info.rc == mqtt.MQTT_ERR_SUCCESS and info.is_published():
175
+ logger.info(f"消息已发布到主题 '{topic}' (QoS {use_qos}): {payload}")
176
+ return True
177
+ logger.error(
178
+ f"发布未被 broker 确认(超时 {publish_timeout}s):rc={info.rc} 主题={topic}"
179
+ )
180
+ return False
181
+ except Exception as e:
182
+ logger.error(f"MQTT 发布发生异常: {type(e).__name__}: {e}")
183
+ return False
184
+ finally:
185
+ if client is not None:
186
+ try:
187
+ client.disconnect()
188
+ except Exception:
189
+ pass
190
+ try:
191
+ client.loop_stop()
192
+ except Exception:
193
+ pass
sc92_lib/paths.py ADDED
@@ -0,0 +1,84 @@
1
+ """入口脚本定位与默认路径:推导脚本目录/脚本名,以及日志、配置的默认位置。
2
+
3
+ 锁、日志、配置文件三者的默认路径都以 `script_dir()` / `script_name()` 的结果为基准,
4
+ 所以要同时兼容:直接运行 .py、PyInstaller 打包的 exe、`python -m 包[.模块]`。
5
+ 各启动方式下的具体对应关系见 README「入口脚本定位」。
6
+ """
7
+
8
+ import pathlib
9
+ import sys
10
+ from typing import Optional
11
+
12
+
13
+ def _is_frozen() -> bool:
14
+ """是否运行在 PyInstaller 等打包环境(此时入口是 sys.executable)。"""
15
+ return getattr(sys, "frozen", False)
16
+
17
+
18
+ def _module_entry() -> Optional[str]:
19
+ """以模块方式启动时返回模块入口名,普通独立脚本返回 None。
20
+
21
+ `python -m pkg[.mod]`(或手动去跑某个包的 __main__.py)没有自己的入口脚本名:
22
+ sys.argv[0] 只给到 "__main__.py",而真正的模块通常躺在 site-packages 里 ——
23
+ 那里不该被写日志 / 锁 / 配置文件,所以这些情况返回模块名或包名。
24
+ `pkg.__main__` 会去掉 `.__main__` 后缀,得到包名。
25
+ """
26
+ if _is_frozen():
27
+ return None
28
+ spec = getattr(sys.modules.get("__main__"), "__spec__", None)
29
+ name = getattr(spec, "name", None)
30
+ if name and name != "__main__":
31
+ suffix = ".__main__"
32
+ return name[: -len(suffix)] if name.endswith(suffix) else name
33
+ first = pathlib.Path(sys.argv[0])
34
+ if first.stem == "__main__" and first.parent != pathlib.Path():
35
+ return first.resolve().parent.name
36
+ return None
37
+
38
+
39
+ def script_dir() -> pathlib.Path:
40
+ """入口脚本所在目录;打包后是 exe 所在目录,`python -m` 是当前工作目录。
41
+
42
+ `python -m` 跑的是模块不是脚本,模块自己的目录往往就是 site-packages,
43
+ 所以退回当前工作目录。
44
+ """
45
+ if _is_frozen():
46
+ return pathlib.Path(sys.executable).parent
47
+ if _module_entry() is not None:
48
+ return pathlib.Path.cwd()
49
+ first = pathlib.Path(sys.argv[0])
50
+ if not first.name or first.name == "-c":
51
+ return pathlib.Path.cwd()
52
+ return first.resolve().parent
53
+
54
+
55
+ def script_name() -> str:
56
+ """入口脚本名(不含扩展名):打包后取 exe 名,`python -m` 取模块名或包名。"""
57
+ if _is_frozen():
58
+ return pathlib.Path(sys.executable).stem
59
+ module = _module_entry()
60
+ if module is not None:
61
+ return module
62
+ stem = pathlib.Path(sys.argv[0]).stem
63
+ if not stem or stem == "-c":
64
+ return pathlib.Path.cwd().name
65
+ return stem
66
+
67
+
68
+ def default_log_file() -> str:
69
+ """默认日志路径前缀:<脚本目录>/logs/<脚本名>(`_debug.log` / `_info.log` 由初始化时追加)。"""
70
+ return str(script_dir() / "logs" / script_name())
71
+
72
+
73
+ def default_yaml_file() -> str:
74
+ """默认配置文件:<脚本目录>/configs/<脚本名>.config.yaml。"""
75
+ return str(script_dir() / "configs" / f"{script_name()}.config.yaml")
76
+
77
+
78
+ def default_lock_file() -> str:
79
+ """默认锁文件:<脚本目录>/<脚本名>.running.lock。
80
+
81
+ 换目录、改名或复制脚本都会得到另一个锁文件(另一把锁),
82
+ 细节见 `check_running_lock()` 的说明。
83
+ """
84
+ return str(script_dir() / f"{script_name()}.running.lock")
sc92_lib/py.typed ADDED
File without changes
sc92_lib/to_yaml.py ADDED
@@ -0,0 +1,134 @@
1
+ """值转 YAML 文本;转换失败原样返回,绝不抛异常。
2
+
3
+ 规则:dict / list 直接 `safe_dump`;其它类型先 `str()`,再依次用 ast、json5 解析,
4
+ 只有结果是 dict / list(顶层 tuple 按 list 对待)才 dump。
5
+
6
+ 失败约定:任何一步失败都 `logger.debug` 后返回入参,不 exit、不抛异常。
7
+ 为什么用 ast + json5 而不是 `yaml.safe_load`,见 README「值转 YAML 文本」。
8
+ """
9
+
10
+ import ast
11
+ import logging
12
+ from typing import Callable, List, Tuple
13
+
14
+ import json5
15
+ import yaml
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ # 两个候选解析器,按顺序尝试:
20
+ # ast 吃 Python 字面量(单引号、True/False/None、尾逗号、元组),
21
+ # json5 吃宽松 JSON(true/false/null、无引号键、`//` 和 `#` 注释、`.5`)。
22
+ # 两者都要求"带括号/引号的字面量形状",所以普通句子不会被误当成 dict。
23
+ _LOADERS: Tuple[Tuple[str, Callable[[str], object]], ...] = (
24
+ ("ast", ast.literal_eval),
25
+ ("json5", json5.loads),
26
+ )
27
+
28
+
29
+ def _safe_repr(value: object) -> str:
30
+ """尽量把原值转成可读文本,repr / str 都失败时给一个占位说明。"""
31
+ try:
32
+ return repr(value)
33
+ except Exception:
34
+ pass
35
+ try:
36
+ return str(value)
37
+ except Exception:
38
+ return f"<{type(value).__name__} 对象,repr/str 均失败>"
39
+
40
+
41
+ def to_yaml(value: object) -> object:
42
+ """尽可能输出 YAML 文本,失败则原样返回。
43
+
44
+ 参数:
45
+ value: 任意对象。dict / list 直接转换;其它类型先转字符串,再尝试按
46
+ Python 字面量(ast)或宽松 JSON(json5)解析。
47
+
48
+ 返回:
49
+ 转换成功返回 YAML 文本(保留 `safe_dump` 自带的末尾换行);任何一步失败
50
+ 返回入参本身,不抛异常。
51
+
52
+ 注意:
53
+ - 不解析 YAML 文本;`"123"`、`'"abc"'`、`{1, 2}`(set)这类标量或容器
54
+ 也原样返回。
55
+ - pandas 的 `str(df)` 不是字面量,会原样返回;要转先传 `df.to_dict()`。
56
+ - 成功和失败都写 `logger.debug`,成功时标出命中的是 ast 还是 json5。
57
+ """
58
+
59
+ # 阶段 1:dict / list 直接转(嵌套对象可能仍无法转换,失败就原样返回)
60
+ if isinstance(value, (dict, list)):
61
+ try:
62
+ result = yaml.safe_dump(
63
+ value,
64
+ allow_unicode=True,
65
+ sort_keys=False,
66
+ default_flow_style=False,
67
+ )
68
+ except Exception as exc:
69
+ logger.debug(
70
+ f"to_yaml 无法转换 {type(value).__name__} 对象,"
71
+ f"原样返回({type(exc).__name__}: {exc}):{_safe_repr(value)}"
72
+ )
73
+ return value
74
+ log_text = result.rstrip("\n")
75
+ logger.debug(f"to_yaml 转换结果:\n{log_text}")
76
+ return result
77
+
78
+ # 阶段 2:其它类型先转字符串
79
+ try:
80
+ text = str(value)
81
+ except Exception as exc:
82
+ logger.debug(
83
+ f"to_yaml 无法把 {type(value).__name__} 对象转成字符串,"
84
+ f"原样返回({type(exc).__name__}: {exc}):{_safe_repr(value)}"
85
+ )
86
+ return value
87
+
88
+ # 阶段 3:依次尝试 ast、json5,两个都失败就原样返回
89
+ parsed: object = None
90
+ hit = ""
91
+ failures: List[str] = []
92
+ for name, loader in _LOADERS:
93
+ try:
94
+ parsed = loader(text)
95
+ hit = name
96
+ break
97
+ except Exception as exc:
98
+ failures.append(f"{name}: {type(exc).__name__}: {exc}")
99
+ if not hit:
100
+ logger.debug(
101
+ f"to_yaml ast/json5 解析字符串失败({';'.join(failures)}),"
102
+ f"原样返回:{_safe_repr(value)}"
103
+ )
104
+ return value
105
+
106
+ # 顶层元组按列表处理;set 不接受(safe_dump 出来是 !!set 那种怪结果)
107
+ if isinstance(parsed, tuple):
108
+ parsed = list(parsed)
109
+
110
+ if not isinstance(parsed, (dict, list)):
111
+ logger.debug(
112
+ f"to_yaml {hit} 结果不是 dict/list({type(parsed).__name__}),"
113
+ f"原样返回:{_safe_repr(value)}"
114
+ )
115
+ return value
116
+
117
+ # 阶段 4:解析结果转 YAML,失败原样返回
118
+ try:
119
+ result = yaml.safe_dump(
120
+ parsed,
121
+ allow_unicode=True,
122
+ sort_keys=False,
123
+ default_flow_style=False,
124
+ )
125
+ except Exception as exc:
126
+ logger.debug(
127
+ f"to_yaml 无法转换 {hit} 解析结果,"
128
+ f"原样返回({type(exc).__name__}: {exc}):{_safe_repr(value)}"
129
+ )
130
+ return value
131
+
132
+ log_text = result.rstrip("\n")
133
+ logger.debug(f"to_yaml({hit})转换结果:\n{log_text}")
134
+ return result
sc92_lib/try_run.py ADDED
@@ -0,0 +1,45 @@
1
+ """局部异常兜底:with 包住一段代码,抛 Exception 时写日志并吞掉,脚本继续。
2
+
3
+ 失败约定:只吞 `Exception`;`SystemExit` / `KeyboardInterrupt` / `GeneratorExit`
4
+ 照常向外抛,本模块自己从不 exit。
5
+ """
6
+
7
+ import logging
8
+ import traceback
9
+ from contextlib import contextmanager
10
+ from types import SimpleNamespace
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ @contextmanager
16
+ def try_run(desc: str = "", level: int = logging.ERROR):
17
+ """包住一段语句,失败只记日志,不中断主流程。
18
+
19
+ 参数:
20
+ desc: 日志前缀,会拼成 `"<desc>失败"`;省略时为 `"try_run代码块异常"`。
21
+ level: 写日志的级别(走 `logger.log`),默认 `logging.ERROR`。
22
+
23
+ 返回(yield):
24
+ 状态对象:
25
+ - `r.ok`:块内是否顺利跑完;
26
+ - `r.e`:捕获到的异常,没有则 None;
27
+ - `r.traceback`:完整 traceback 文本,没有则 None。
28
+
29
+ 退出:
30
+ 不退出。块内抛 `Exception` 时记日志、吞掉,脚本从 with 之后继续执行。
31
+
32
+ 注意:
33
+ 只吞 `Exception`:`SystemExit` / `KeyboardInterrupt` / `GeneratorExit` 照常抛出,
34
+ 所以不会掩盖主动退出或 Ctrl+C。
35
+ 别用它兜"必须成功"的逻辑 —— 它的语义就是"这里失败也无所谓,记一笔接着跑"。
36
+ """
37
+ r = SimpleNamespace(ok=False, e=None, traceback=None)
38
+ try:
39
+ yield r
40
+ r.ok = True # 块内没抛异常才会走到这
41
+ except Exception as e:
42
+ r.e = e
43
+ r.traceback = traceback.format_exc()
44
+ prefix = f"{desc}失败" if desc else "try_run代码块异常"
45
+ logger.log(level, f"{prefix}\n{r.traceback}")