#!/usr/bin/env python3 """ 计算策略文件中 propertyGroup 块的数量 用于解决 hyperopt 多阶段执行时,日志显示的总阶段数硬编码问题 现在可以根据实际的 propertyGroup 块数量动态确定总数 """ import re import sys from pathlib import Path def count_property_groups(strategy_file_path: str) -> int: """ 从策略文件中计算 propertyGroup 块的数量 Args: strategy_file_path: 策略文件的路径 Returns: propertyGroup 块的数量 """ try: with open(strategy_file_path, 'r', encoding='utf-8') as f: content = f.read() except FileNotFoundError: print(f"❌ 文件不存在: {strategy_file_path}", file=sys.stderr) return 0 except Exception as e: print(f"❌ 读取文件失败: {e}", file=sys.stderr) return 0 # 查找所有 [propertiesGrp step=... 的匹配 # 使用 (?<=...) 正向后查断言来匹配 step 属性 pattern = r'\[\s*propertiesGrp\s+step\s*=\s*["\']?\d+["\']?' matches = re.findall(pattern, content) count = len(matches) if count == 0: # 尝试另一种模式,没有 step 属性 pattern_alt = r'\[\s*propertiesGrp\b' matches_alt = re.findall(pattern_alt, content) count = len(matches_alt) return count def get_property_groups_details(strategy_file_path: str) -> list: """ 获取所有 propertyGroup 块的详细信息 Args: strategy_file_path: 策略文件的路径 Returns: 包含每个 propertyGroup 信息的列表 """ try: with open(strategy_file_path, 'r', encoding='utf-8') as f: content = f.read() except Exception as e: print(f"❌ 读取文件失败: {e}", file=sys.stderr) return [] # 匹配完整的 propertiesGrp 标签,包括所有属性 pattern = r'\[\s*propertiesGrp\s+([^\]]+)\s*\]' matches = re.findall(pattern, content) groups = [] for match in matches: group_info = { 'raw': match, 'attributes': {} } # 解析各个属性 attr_pattern = r'(\w+)\s*=\s*["\']?([^"\']*)["\']?' attrs = re.findall(attr_pattern, match) for attr_name, attr_value in attrs: group_info['attributes'][attr_name] = attr_value groups.append(group_info) return groups def main(): """主函数""" if len(sys.argv) < 2: print("用法: python count_property_groups.py <策略文件路径> [--details]") print() print("示例:") print(" python count_property_groups.py /path/to/freqaiprimer.py") print(" python count_property_groups.py /path/to/freqaiprimer.py --details") sys.exit(1) strategy_file = sys.argv[1] show_details = '--details' in sys.argv count = count_property_groups(strategy_file) if show_details: groups = get_property_groups_details(strategy_file) print(f"📊 propertyGroup 总数: {count}") print() for idx, group in enumerate(groups, 1): print(f"[{idx}] propertyGroup:") attrs = group['attributes'] if attrs: for key, value in attrs.items(): print(f" {key}: {value}") else: print(f" {group['raw']}") print() else: print(f"{count}") if __name__ == '__main__': main()