Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

piping a string to gcc with python's subprocess.Popen

Tags:

python

linux

gcc

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?

like image 844
Mark Swift Avatar asked Mar 15 '26 07:03

Mark Swift


1 Answers

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()
like image 90
perreal Avatar answered Mar 16 '26 21:03

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!