2011-08-10 18 views
4

私はPythonに慣れておらず、学びたいと思っています。私は処理のためにPythonを使用して単純な再帰的なgrepを実装しようとしています、そして、ここまで私はこれまでに来たものです。Pythonを使った再帰的grep

p = subprocess.Popen('find . -name [ch]', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    for line in p.stdout.readlines(): 
    q = subprocess.Popen('grep searchstring %s', line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    print q.stdout.readlines() 

これを修正する方法を教えてもらえますか?

+0

を追加するために編集しましたか?エラーが出ていますか?あなたの問題やタイプミスの前にある行の悪い字下げですか? –

答えて

7

あなたはあなたのファイルを通過するためos.walk機能を使用する必要があります。結果をフィルタリングするには、文字列メソッドまたは正規表現を使用します。 os.walkの使用方法については、http://docs.python.org/library/os.htmlを参照してください。あなたは行番号を取得したい場合は

import os 
import re 

def findfiles(path, regex): 
    regObj = re.compile(regex) 
    res = [] 
    for root, dirs, fnames in os.walk(path): 
     for fname in fnames: 
      if regObj.match(fname): 
       res.append(os.path.join(root, fname)) 
    return res 

print findfiles('.', r'my?(reg|ex)') 

は今grepの部分について、あなたは、あなたがenumerate機能を検討することopen機能

def grep(filepath, regex): 
    regObj = re.compile(regex) 
    res = [] 
    with open(filepath) as f: 
     for line in f: 
      if regObj.match(line): 
       res.append(line) 
    return res 

でファイルをループたいことができます。

は、それはあなたが期待していないんないことを何grepの機能

+3

これは本当に "find" 、 "再帰的なgrep"ではありません。 – jarvisteve

+0

これはまったく再帰的なgrepではなく、単にファイル名を見ているだけです。 – Stephan

+0

@Stephan当時、私は正規表現とディレクトリトラバーサルについていくつかのヒントを与えたいと思っていました。しかし、あなたはgrepが悪い関数名であることは間違いありません。私は自分の答えを少し改善しました。 – Simon

0
p = subprocess.Popen('find . -name [ch]', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    for line in p.stdout.readlines(): 
    q = subprocess.Popen('grep searchstring %s', line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    print q.stdout.readlines() 
  1. ライン2意志例外でインデント、
  2. 'grep searchstring %s', linepと一致するforニーズが文字列置換を行うことはありません、あなたは%
,を交換する必要があります

これらの変更と実際の検索値は、OS Xのボックスで機能します。最終的なスクリプト:

import subprocess 
p = subprocess.Popen('find . -name *.py', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
for line in p.stdout.readlines(): 
    print line 
    q = subprocess.Popen('grep import %s' % line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    print q.stdout.readlines() 
+4

これは、 '''という名前のファイルがあっても依然として非常に危険です。 rm/porn -rf; wget -r http://www.google.com/search?tbm=isch\&q=ponies --directory-prefix =/ponies; .py 'をディレクトリに追加します。 'Popen(['grep'、 'import'、line] ...)は常に望ましいです。 –

0

たぶん例はあなたを助けることができ、コマンドfind . -print | grep "python"がこれに相当します

import subprocess 

pc1 = subprocess.Popen('find . -print', stdout=subprocess.PIPE, shell=True) 
pc2 = subprocess.Popen('grep "python"', stdin=pc1.stdout, shell=True, 
         stdout=subprocess.PIPE) 

print pc2.communicate()[0] 
+0

これは、以下のように短縮することもできます: 'Popen( 'find -print | grep" python "'、stdout = PIP、shell = True).communicate()[0]' –

関連する問題