222
This commit is contained in:
1 parent
e67251153e
commit
9efa8ddf4d
1 file changed
+14
-4
@@ -6,10 +6,13 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
|
|
||||||
# 优先使用 Python 3.11+ 内置的 tomllib,否则回退到 toml 包
|
# 优先使用 Python 3.11+ 内置的 tomllib,否则回退到 toml 包
|
||||||
|
_USE_STDLIB_TOMLLIB = False
|
||||||
try:
|
try:
|
||||||
import tomllib # Python 3.11+
|
import tomllib # Python 3.11+
|
||||||
|
_USE_STDLIB_TOMLLIB = True
|
||||||
except ImportError:
|
except ImportError:
|
||||||
import toml as tomllib # 回退到 toml 包
|
import toml as tomllib # 回退到 toml 包
|
||||||
|
_USE_STDLIB_TOMLLIB = False
|
||||||
|
|
||||||
|
|
||||||
def get_config_path():
|
def get_config_path():
|
||||||
@@ -70,12 +73,12 @@ def cfg(key_name, default=None):
|
|||||||
return default
|
return default
|
||||||
|
|
||||||
# tomllib 需要二进制模式,toml 包需要文本模式
|
# tomllib 需要二进制模式,toml 包需要文本模式
|
||||||
if hasattr(tomllib, 'load'):
|
if _USE_STDLIB_TOMLLIB:
|
||||||
# Python 3.11+ 的 tomllib
|
# Python 3.11+ 的 tomllib,需要二进制模式
|
||||||
with open(config_path, 'rb') as f:
|
with open(config_path, 'rb') as f:
|
||||||
config = tomllib.load(f)
|
config = tomllib.load(f)
|
||||||
else:
|
else:
|
||||||
# toml 包
|
# toml 包,需要文本模式
|
||||||
with open(config_path, 'r', encoding='utf-8') as f:
|
with open(config_path, 'r', encoding='utf-8') as f:
|
||||||
config = tomllib.load(f)
|
config = tomllib.load(f)
|
||||||
|
|
||||||
@@ -105,7 +108,14 @@ def cfg(key_name, default=None):
|
|||||||
print(f"配置文件不存在,路径: {config_path}")
|
print(f"配置文件不存在,路径: {config_path}")
|
||||||
return default
|
return default
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"读取配置文件时发生错误: {e}")
|
# 提供更详细的错误信息
|
||||||
|
lib_type = "tomllib (标准库)" if _USE_STDLIB_TOMLLIB else "toml (第三方包)"
|
||||||
|
error_msg = str(e)
|
||||||
|
print(f"读取配置文件时发生错误 (使用 {lib_type}): {error_msg}")
|
||||||
|
print(f"配置文件路径: {config_path}")
|
||||||
|
# 如果是 TOML 解析错误,提供额外提示
|
||||||
|
if "Expecting" in error_msg or "parse" in error_msg.lower() or "syntax" in error_msg.lower():
|
||||||
|
print("提示: 请检查配置文件格式是否正确,确保使用 UTF-8 编码")
|
||||||
return default
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user