【问题标题】:Python nested loops do not continue with the subprocessPython 嵌套循环不会继续子进程
【发布时间】:2018-04-30 20:48:52
【问题描述】:

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

#!/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))

【问题讨论】:

  • 停止?还是块?
  • 你应该最后打电话给p3.wait()(其他人也一样)
  • 在第一个元素e in range(...)之后停止,p3.wait()不起作用!
  • 在这个三重循环中存在一个概念问题:第一个 p2 grep 进程消耗了 find 的所有输出。我会创建一个要 grep 的文件列表,然后是 grep。这可以使用纯python编写。

标签: python python-3.x for-loop nested subprocess


【解决方案1】:

概念错了

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)

(或逐行)

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2015-05-27
    相关资源
    最近更新 更多