How should I use grep from python?

Matthew Wilson matt at tplus1.com
Thu May 7 08:58:50 EDT 2009


I'm writing a command-line application and I want to search through lots
of text files for a string.  Instead of writing the python code to do
this, I want to use grep.

This is the command I want to run:

$ grep -l foo dir

In other words, I want to list all files in the directory dir that
contain the string "foo".

I'm looking for the "one obvious way to do it" and instead I found no
consensus.  I could os.popen, commands.getstatusoutput, the subprocess
module, backticks, etc.  

As of May 2009, what is the recommended way to run an external process
like grep and capture STDOUT and the error code?


TIA

Matt



More information about the Python-list mailing list