Popen 管道 2 cmd 挂起并且没有给出预期的结果

Popen piping 2 cmd hanging and not giving expected result

我正在尝试使用 grep 并将其通过管道传输到 uniq 以获得独特的结果...(在此处对 ip 地址进行 greping)

process = subprocess.Popen(['grep','-sRIEho', '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', '/tmp/test'])
p2 = subprocess.Popen(['uniq'],stdin=process.stdout)    
stdout,stderr = p2.communicate()

问题是它挂起并且没有向我显示独特的结果... 这是“/tmp/test”文件:

127.0.0.1
127.0.0.1
127.0.0.1
1.9.12.12
192.168.1.2
192.168.1.2
192.168.1.3
192.168.1.4

结果也好……一样的 知道这里发生了什么吗? 顺便说一句,我不能在这里使用 Shell=True(用户提供的文件名)

.communicate() returns None 除非你通过 PIPEstdout, stderr 总是 None你的例子。此外,您应该关闭父级中的 process.stdout,以便 grep 知道 uniq 是否过早死亡。它没有解释为什么 grep "hangs"。问题可能是 grep 参数,例如 -R(递归,遵循符号链接)。

尝试 How do I use subprocess.Popen to connect multiple processes by pipes? 中的有效解决方案,例如:

#!/usr/bin/env python3
from subprocess import Popen, PIPE

with Popen(['uniq'], stdin=PIPE, stdout=PIPE) as uniq, \
     Popen(['grep'] + grep_args, stdout=uniq.stdin):
    output = uniq.communicate()[0]

或:

#!/usr/bin/env python
from plumbum.cmd import grep, uniq  # $ pip install plumbum

output_text = (grep[grep_args] | uniq)()