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?

4

1 回答 1

2

这个适用于subprocess.PIPE(os.popen() 已弃用),您还需要-向 gcc 传递和附加参数以使其处理标准输入:

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()
于 2013-05-14T21:30:45.047 回答