#!/usr/bin/env python # coding=utf-8 """ @author: CNWei @Software: PyCharm @contact: t6i888@163.com @file: file_processing @date: 2025/4/8 21:22 @desc: """ from pathlib import Path from tomlkit import parse, dumps from tomlkit.toml_file import TOMLFile import logging from typing import Union from dataclasses import dataclass, asdict, field from pathlib import Path import tomlkit from utils.file_processors.base import BaseFileProcessor logger = logging.getLogger(__name__) class TomlProcessor(BaseFileProcessor, dict): """ 用于处理 YAML 文件的类,继承自 dict。 提供了从文件加载、保存到文件、转换为字符串和从字符串转换的功能, 并可以直接像字典一样访问 YAML 数据。 """ def __init__(self, filepath: Union[str, Path], data: Union[dict, None] = None): """ 初始化 YamlFile 对象。 Args: filepath: YAML 文件的路径 (可以是字符串或 pathlib.Path 对象). data: 可选的初始数据字典。如果提供,则用该字典初始化 YamlFile。 如果不提供,则尝试从 filepath 加载数据。 """ super().__init__() # 初始化父类 dict self.filepath: Path = Path(filepath) # 确保 filepath 是 Path 对象 if data is not None: self.update(data) # 如果提供了初始数据,则更新字典 else: self.load() # 否则,尝试从文件加载 def load(self) -> None: self.clear() # 清空现有数据 if self.filepath.exists(): try: with open(self.filepath, 'r', encoding='utf-8') as f: result = tomlkit.parse(f.read()) or {} # print(result) self.update(result) except Exception as e: logger.error(f"加载 TOML 文件 {self.filepath} 时出错: {e}") else: logger.warning(f"文件 {self.filepath} 不存在, 字典保持为空.") @staticmethod def to_string(data: dict) -> str: try: return tomlkit.dumps( dict(data), # 使用dict转换为标准的字典 sort_keys=False ) except TypeError as e: logger.error(f"将数据转换为 TOML 字符串时出错: {e}") return "" @staticmethod def to_dict(data: str) -> Union[None, dict]: try: loaded_data = tomlkit.loads(data) or {} return loaded_data except Exception as e: logger.error(f"将 TOML 字符串转换为字典时出错: {e}") def save(self, new_filepath: Union[str, Path, None] = None): filepath = Path(new_filepath) if new_filepath else self.filepath try: with open(filepath, "w", encoding="utf-8") as f: tomlkit.dump( dict(self), # 使用dict转换为标准的字典 fp=f, sort_keys=False, ) except (TypeError, OSError) as e: logger.error(f"保存 TOML 文件 {filepath} 时出错: {e}") if __name__ == '__main__': ... toml_path =r'E:\PyP\WebAutoTest\data\var.toml' toml_file = TomlProcessor(toml_path) print(toml_file) print(type(toml_file)) print(toml_file.to_string(toml_file)) print(toml_file.to_dict(toml_file.to_string(toml_file))) print(toml_file.to_dict(toml_file.to_string(toml_file))) toml_file.to_dict(toml_file.to_string(toml_file)) # toml_file.save() print(toml_file.to_string( {'用例ID': None, '内容': '打开浏览器', '标记': 'browser', '参数': 'edge', '_BlankField': [None, None]}))