I would like to embed a command in a python script and capture the output. In this scenario I'm trying to use "find" to find an indeterminate number of files in an indeterminate number of subdirs, and grep each matching file for a string, something like:
grep "rabbit" `find . -name "*.txt"`
I'm running Python 2.6.6 (yeah, I'm sorry too, but can't budge the entire organization for this right now).
I've tried a bunch of things using subprocess, shlex, etc. that have been suggested in here, but I haven't found a syntax that will either swallow this, or ends up sucking the "find..."as the search string forgrep`, etc. Suggestions appreciated.
Ken
subprocess.call(..., shell=True)but such use of the shell actually makes for unsafe Python code. Why not traverse the directory from within Python and also do what grep does in Python? It's fairly simple and makes your code more portable.shell=Truecompared to other ways to run it. It probably improves readability -- in a sense it might make the code safer (less bugs)..will be replaced by some variable. If so, all doors for shell code injection are wide open. If the command is indeed a hard-coded string it will probably be fine as you say. Except that it ties your Python program to the POSIX platform for no good reason. Personally, I would almost never use the shell. Python is so powerful that it doesn't really add any convenience to spawn a shell.