dongchangxi 2 weeks ago
parent
commit
9efa8ddf4d
  1. 18
      factory_sliceing/utils/config.py

18
factory_sliceing/utils/config.py

@ -6,10 +6,13 @@ import os @@ -6,10 +6,13 @@ import os
import sys
# 优先使用 Python 3.11+ 内置的 tomllib,否则回退到 toml 包
_USE_STDLIB_TOMLLIB = False
try:
import tomllib # Python 3.11+
_USE_STDLIB_TOMLLIB = True
except ImportError:
import toml as tomllib # 回退到 toml 包
_USE_STDLIB_TOMLLIB = False
def get_config_path():
@ -70,12 +73,12 @@ def cfg(key_name, default=None): @@ -70,12 +73,12 @@ def cfg(key_name, default=None):
return default
# tomllib 需要二进制模式,toml 包需要文本模式
if hasattr(tomllib, 'load'):
# Python 3.11+ 的 tomllib
if _USE_STDLIB_TOMLLIB:
# Python 3.11+ 的 tomllib,需要二进制模式
with open(config_path, 'rb') as f:
config = tomllib.load(f)
else:
# toml 包
# toml 包,需要文本模式
with open(config_path, 'r', encoding='utf-8') as f:
config = tomllib.load(f)
@ -105,7 +108,14 @@ def cfg(key_name, default=None): @@ -105,7 +108,14 @@ def cfg(key_name, default=None):
print(f"配置文件不存在,路径: {config_path}")
return default
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

Loading…
Cancel
Save