Python 嵌套循环不会继续子进程



>我试图在代码下面运行,但它只是在最内部循环然后停止,我不明白为什么它不继续到外部循环?

#!/usr/bin/python3                                                                                                                                                                               
import os
import sys
import subprocess
p1 = subprocess.Popen([find...],stdout=subprocess.PIPE)
for i in range(...):
        p2 = subprocess.Popen([grep...],stdin=p1.stdout,stdout=subprocess.PIPE)
        for e in range(...):
               p3=subprocess.Popen([grep...],stdin=p2.stdout,stdout=subprocess.PIPE)
               for file in p3.stdout:
                        print(str(i)+str(e)+str(file))

这个概念是错误的

p1 = subprocess.Popen([find...],stdout=subprocess.PIPE)
for i in range(...):
        p2 = subprocess.Popen([grep...],stdin=p1.stdout,stdout=subprocess.PIPE)

运行此代码(第一次迭代(时,p1.stdout 完全由 p2 使用。因此,接下来生成p2得到一个空输出。

(内循环也是如此(

我会用纯蟒蛇写。

第一个循环来匹配要 grep 的文件:

files_to_process = []
for root,dirs,files in os.walk(start_directory):
    files_to_process += [f for f in files if <some condition> ]

获得文件列表后,您可以在很多循环中打开它们并搜索它们的内容。我建议避免grep并做这样的事情:

with open(filename) as f:
    contents = f.read()
    results = re.search(regexp,contents)

(或逐行(

最新更新