2011-11-18 32 views
0

我正在使用Python(python 2.6)中的子進程模塊和Popen方法。Python子流程模塊 - 在bash中使用-exec查找命令的Popen方法

我想實現:

我嘗試使用下面的bash命令與POPEN如果發現有「標準錯誤」的字符串的文件,將返回匹配。

代碼:

慶典

find . -exec grep "stderr" {} + 

我在蟒蛇正在做

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' 

任何想法爲什麼?

* 編輯: 我沒有{+}之間的空格,這就是爲什麼我得到了上述。道歉! *

乾杯,

邁克

+0

我無法在Mac OS X上的python2.6中重現您的錯誤。您的「dir」參數的值是多少? – noio

+0

爲什麼不使用'grep -r' –

+0

@Noio只是我希望命令運行的字符串。在這種情況下,它是在我的Linux機器上的一個/數據區域 – MWright

回答

0

嘗試使你的命令的參數列表:

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

編輯:對不起,我不知道POPEN()可以採取一個字符串。這個答案不正確。

+0

這不起作用。它工作沒有分裂,但我得到的消息發送到上面的屏幕? – MWright

+0

@MWrite對,對不起。我太急於發佈我的答案。我認爲Popen()所需的語法與exec *()相似,但事實上並非如此。 –

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 
+0

它不會在文件內容中搜索'stderr',而是在文件名中搜索。 – glglgl

+0

我需要它的文件內容,但謝謝。 Popen方法的工作原理,但我不知道爲什麼這條消息到屏幕上? – MWright

+0

@好的抱歉,我沒有意識到您想搜索內容。如果你只是想要匹配的線,看看Beazley先生的gen_grep例子。 –