用python在进程之间传递数据

用python在进程之间传递数据,python,pipe,subprocess,Python,Pipe,Subprocess,我正在努力熟悉subprocess.Popen机制 在下面的示例中,我尝试运行netstat,然后对输出运行grep netstat = subprocess.Popen("netstat -nptl".split(), stdout = subprocess.PIPE) grep = subprocess.Popen("grep 192.168.46.134".split(), stdin = subprocess.PIPE) 但是,这不会产生所需的输出。您需要将第一个进程的stdout引用

我正在努力熟悉subprocess.Popen机制

在下面的示例中,我尝试运行netstat,然后对输出运行grep

netstat = subprocess.Popen("netstat -nptl".split(), stdout = subprocess.PIPE)
grep = subprocess.Popen("grep 192.168.46.134".split(), stdin = subprocess.PIPE)

但是,这不会产生所需的输出。

您需要将第一个进程的
stdout
引用为第二个进程的
stdin

import subprocess

netstat = subprocess.Popen("netstat -nptl".split(), stdout=subprocess.PIPE)
grep = subprocess.Popen("grep 192.168.46.134".split(), stdin=netstat.stdout, stdout=subprocess.PIPE)

stdout, stderr = grep.communicate()
print stdout # this is a string containing the output

我收到“断管”错误…:(奇怪的是,我只是尝试了一下(因为我现在在windows上,所以使用的命令略有不同),效果很好。你在之后调用了
grep.communicate()
,对吧?我没有运行grep.communicate(),为什么有必要?那么你是如何运行它的?你通过运行
stdout,stderr=grep.communicate()获得了所需的输出)
。关于stdout,我不太确定,stderr=grep.communicate()。请编辑答案,将其包括在内。我对Python完全不熟悉。。。