使用python递归grep

Kir*_*ran 4 python grep subprocess popen

我是python的新手并且正在努力学习.我正在尝试使用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()
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何解决这个问题来做它应该做的事情吗?

Sim*_*got 9

您应该使用该os.walk功能来浏览您的文件.使用字符串方法或正则表达式过滤掉结果.查看http://docs.python.org/library/os.html,了解有关如何使用os.walk的信息.

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)')
Run Code Online (Sandbox Code Playgroud)

现在对于grep部分,您可以使用该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
Run Code Online (Sandbox Code Playgroud)

如果要获取行号,可能需要查看该enumerate函数.

编辑添加grep功能

  • 这实际上更像是一个"发现",而不是"递归grep". (5认同)
  • 这根本不是递归 grep,它只是查看文件名 (2认同)