3

I have a c++ style text file that I'm trying to pipe to gcc to remove the comments. Initially, I tried a regex approach, but had trouble handling things like nested comments, string literals and EOL issues.

So now I'm trying to do something like:

strip_comments(test_file.c)

def strip_comments(text):
    p = Popen(['gcc', '-w', '-E', text], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    p.stdin.write(text)
    p.stdin.close()
    print p.stdout.read()

but instead of passing the file, I'd like to pipe the contents because the files I'm trying to preprocess don't actually have the .c extension

Has anyone had any success with anything like this?

Mark Swift
  • 63
  • 5

1 Answers1

2

This one works with subprocess.PIPE (os.popen() is deprecated), and you also need to pass and additional - argument to gcc to make it process stdin:

import os
from subprocess import Popen, PIPE
def strip_comments(text):
    p = Popen(['gcc', '-fpreprocessed', '-dD', '-E', '-x', 'c++', '-'], 
            stdin=PIPE, stdout=PIPE, stderr=PIPE)
    p.stdin.write(text)
    p.stdin.close()
    return_code = p.wait()
    print p.stdout.read()
perreal
  • 94,503
  • 21
  • 155
  • 181