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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With