简体   繁体   中英

Capture output of complex shell command in python

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 for grep`, etc. Suggestions appreciated. Ken

import subprocess


find_p = subprocess.Popen(["find", ".", "-name", "*.txt"], stdout=subprocess.PIPE)
grep_p = subprocess.Popen(["xargs", "grep", "rabbit"], stdin=find_p.stdout)

grep_p.wait()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM