views:

226

answers:

3

I'm not to sure if my title is right. What I'm doing is writing a python script to automate some of my code writing. So I'm parsing through a .h file. but I want to expand all macros before I start. so I want to do a call to the shell to:

gcc -E myHeader.h

Which should out put the post preprocessed version of myHeader.h to stdout. Now I want to read all that output straight into a string for further processing. I've read that i can do this with popen, but I've never used pipe objects.

how do i do this?

+2  A: 

The os.popen function just returns a file-like object. You can use it like so:

import os

process = os.popen('gcc -E myHeader.h')
preprocessed = process.read()
process.close()

As others have said, you should be using subprocess.Popen. It's designed to be a safer version of os.popen. The Python docs have a section describing how to switch over.

Brian McKenna
+3  A: 

you should use subprocess.Popen() there are numerous examples on SO

http://stackoverflow.com/questions/1388753/how-to-get-output-from-subprocess-popen

gnibbler
+2  A: 
import subprocess

p = subprocess.popen('gcc -E myHeader.h'.split(),
                     stdout=subprocess.PIPE)
preprocessed, _ = p.communicate()

String preprocessed now has the preprocessed source you require -- and you've used the "right" (modern) way to shell to a subprocess, rather than old not-so-liked-anymore os.popen.

Alex Martelli