【问题标题】:removing enabled/disabled piece of code from text or c file using python使用python从文本或c文件中删除启用/禁用的代码段
【发布时间】:2021-05-03 01:07:48
【问题描述】:

/我正在为整个项目启用一项功能,我需要保留启用的代码段,我需要使用 python 脚本删除。 示例:下面的代码在 text.c 中可用“甜蜜来了”在整个项目中启用.. 执行脚本后 text.c 应该像输出 /

#include <stdio.h>
#include <main.h>
#if define (sweety is coming)
  do somethinhg
#else
  hey
  #if define (lalli is coming)
    please go away
  #endif
#endif
if(great) 
  do something something
  you can stop the Program

输出:

#include <stdio.h>
#include <main.h>
do somethinhg
if(great) 
  do something something
  you can stop the Program

【问题讨论】:

    标签: python c python-3.x list python-2.7


    【解决方案1】:

    有几种方法可以比我向您建议的更好(您可以使用一些专用库,如 flex&Bison,或使用 define at compilation time,如果是您的情况)。我写这个答案只是为了好玩。这是python代码:

    import re
    
    IF_REGEX = re.compile(r'^\s*#if define\s*\((.*)\)\s*$')
    ELSE_REGEX = re.compile(r'^\s*#else\s*$')
    ENDIF_REGEX = re.compile(r'^\s*#endif\s*$')
    
    def parse_text(filepath, conditions):
        # Read file
        with open(filepath, 'r') as f:
            lines = f.readlines()
    
        parsed_text = []
        keeps = []
        for line in lines:
            m = IF_REGEX.match(line)
            if m is not None:
                keeps.append(m.groups()[0] in conditions)
            elif ELSE_REGEX.match(line):
                keeps[-1] = not keeps[-1]
            elif ENDIF_REGEX.match(line):
                keeps = keeps[:-1]
            elif all(keeps):
                parsed_text.append(line)
    
        # Join lines back together
        return ''.join(parsed_text)
    

    假设input_code.c是您问题中包含C代码的文件,那么:

    parse_text('input_code.c', conditions=['sweety is coming'])
    

    将产生:

    #include <stdio.h>
    #include <main.h>
      do somethinhg
    if(great)
      do something something
      you can stop the Program
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      相关资源
      最近更新 更多