python获取C文件中枚举值的操作

用于检测文件夹中头文件中枚举值:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os,sys
import re

if __name__ == '__main__':
    try:
        os.remove("_AllEnum")
    except:
        pass
    enumValue = []
    for dirroot, dirs, files in os.walk(os.path.abspath(".")):
        for filename in files:
            if filename.endswith(".hh") or filename.endswith(".h"):
                print("----------------"+ filename)
                content = ""
                with open(os.path.join(dirroot, filename),"r", encoding="utf-8") as file:
                    content = file.read()

                # 匹配正常格式 enum Struname {}
                pattern = re.compile(r'\benum\s+(\w+)\s*{([^}]*)}', re.DOTALL)

                enum_matches = pattern.finditer(content)
                # 遍历匹配的枚举类型
                for enum_match in enum_matches:
                    enum_name = enum_match.group(1)
                    enum_values_str = enum_match.group(2)
                    # 移除多行注释
                    enum_values_str = re.sub(r'/\*.*?\*/', '', enum_values_str, flags=re.DOTALL)
                    # 移除行注释
                    enum_values_str = re.sub(r'//.*', '', enum_values_str)

                    enum_values = re.findall(r'(\w+)(?:\s*=\s*\w+)?', enum_values_str)
                    for name in enum_values:
                        print(name)
                        enumValue.append(name)


                # 匹配typedef enum { } AAA;格式
                pattern = re.compile(r'typedef\s+enum\s*{([^}]*)}\s*(\w+)\s*;', re.DOTALL)

                enum_matches = pattern.finditer(content)
                # 遍历匹配的枚举类型
                for enum_match in enum_matches:
                    enum_values_str = enum_match.group(1)
                    enum_name = enum_match.group(2)
                    # 移除多行注释
                    enum_values_str = re.sub(r'/\*.*?\*/', '', enum_values_str, flags=re.DOTALL)
                    # 移除行注释
                    enum_values_str = re.sub(r'//.*', '', enum_values_str)

                    enum_values = re.findall(r'(\w+)(?:\s*=\s*\w+)?', enum_values_str)
                    for name in enum_values:
                        print(name)
                        enumValue.append(name)

    with open("_AllEnum","w") as file:
        file.write("\n".join(enumValue))

简单的工具脚本,方便使用。