How should I use grep from python?

Nick Craig-Wood nick at craig-wood.com
Thu May 7 10:30:11 EDT 2009


Matthew Wilson <matt at tplus1.com> wrote:
>  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.  

backticks is some other language ;-)

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

This is the one true way now-a-days

>>> from subprocess import Popen, PIPE
>>> p = Popen(["ls", "-l"], stdout=PIPE)
>>> for line in p.stdout:
...     print line
...
total 93332

-rw-r--r--  1 ncw ncw      181 2007-10-18 14:01 -

drwxr-xr-x  2 ncw ncw     4096 2007-08-29 22:56 10_files

-rw-r--r--  1 ncw ncw   124713 2007-08-29 22:56 10.html
[snip]
>>> p.wait() # returns the error code
0
>>>

There was talk of removing the other methods from public use for 3.x.
Not sure of the conclusion.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list