How should I use grep from python?
Diez B. Roggisch
deets at nospam.web.de
Thu May 7 09:09:53 EDT 2009
Matthew Wilson 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.
>
> As of May 2009, what is the recommended way to run an external process
> like grep and capture STDOUT and the error code?
subprocess. Which becomes pretty clear when reading it's docs:
"""
The subprocess module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes. This module
intends to replace several other, older modules and functions, such as:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
"""
Diez
More information about the Python-list
mailing list