reading a os.popen(command) into a string

Lyndon White picture Lyndon White · Feb 26, 2010 · Viewed 87.3k times · Source

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?

Answer

Brian McKenna picture Brian McKenna · Feb 26, 2010

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.