Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

removing enabled/disabled piece of code from text or c file using python

/I am enabling one feature for whole project, I need to keep enabled piece of code rest I need to remove using python script. example: below code is available in a text.c "sweety is coming" is enabled whole project.. after executing the script the text.c should be like output /

#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

output:

#include <stdio.h>
#include <main.h>
do somethinhg
if(great) 
  do something something
  you can stop the Program
question from:https://stackoverflow.com/questions/65948953/removing-enabled-disabled-piece-of-code-from-text-or-c-file-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several ways to do this better than what I'm going to suggest to you (you could use some dedicated library, like flex&Bison, or using define at compilation time, if it is your case). I'm writing this answer only for fun. This is the python code:

import re

IF_REGEX = re.compile(r'^s*#if defines*((.*))s*$')
ELSE_REGEX = re.compile(r'^s*#elses*$')
ENDIF_REGEX = re.compile(r'^s*#endifs*$')

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)

Suppose that input_code.c is the file with the C code in your question, then:

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

will produce:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...