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?
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-anymoreos.popen
.Here is another approach which captures both regular output plus error output:
and
The
os.popen
function just returns a file-like object. You can use it like so:As others have said, you should be using
subprocess.Popen
. It's designed to be a safer version ofos.popen
. The Python docs have a section describing how to switch over.The os.popen() has been deprecated since Python 2.6. You should now use the subprocess module instead: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:
If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:
you should use
subprocess.Popen()
there are numerous examples on SOHow to get output from subprocess.Popen()