gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:28 26 4
gpt4 key购买 nike

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

#!/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.stdoutp2 完全消耗。因此 p2 的下一个生成会得到空输出。

(内循环也是如此)

我会用纯Python编写它。

第一个循环来匹配您想要 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)

(或逐行)

关于Python 嵌套循环不会继续子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47344495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com