Python子进程模块 - 在bash find命令中使用-exec的Popen方法

时间:2011-11-18 15:44:09

标签: python bash

我使用Python(python 2.6)中的子进程模块和Popen方法。

我想要实现的目标:

我正在尝试将以下bash命令与Popen一起使用,如果找到带有“stderr”字符串的文件,将返回匹配。

代码:

的bash

find . -exec grep "stderr" {} +

我在python中做什么

from subprocess import Popen, PIPE


command = "find . -exec grep 'stderr' {} +"
stream  = Popen(command, stdout=PIPE, shell=True, cwd=dir)
stream_stdout, stream_stderr = stream.communicate()

我得到了什么:

它看起来像stream_stdout一样工作,而stream_stderr返回我怀疑的东西, 但是我把这个txt发送到了屏幕:

 find: missing argument to `-exec'

任何想法为什么?

*的 编辑: 我没有{}之间的空格+这就是为什么我得到了上面的结果。道歉! *

干杯,

麦克

2 个答案:

答案 0 :(得分:0)

尝试将命令列为参数列表:

command = "find . -exec grep 'stderr' {} +".split(" ")

编辑:对不起,我没有意识到Popen()可以接受一个字符串。这个答案不正确。

答案 1 :(得分:0)

为什么使用子进程模块?

这段代码from Mr. Beazley会完成这项工作吗?

import os
import fnmatch
import re

def gen_find(filepat,top):
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist,filepat):
            yield os.path.join(path,name)

def grep(pat,lines):
    patc = re.compile(pat)
    for line in lines:
        if patc.search(line): return True

for f in gen_find("*","."):
    fopen = open(f, 'rb')
    if grep("stderr",fopen.readlines()):
         print f