1

I'm trying to get familiar with subprocess.Popen mechanism.

In the bellow example, I try to run netstat then run grep on the output.

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

However this does not result in a desired output.

triple fault
  • 13,410
  • 8
  • 32
  • 45

1 Answers1

1

You need to reference the first process' stdout as the stdin for the second process:

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
Anonymous
  • 11,740
  • 3
  • 40
  • 50
  • I'm getting "broken pipe" error... :( – triple fault Jul 28 '15 at 17:26
  • Weird, I just tried it (with slightly different commands since I'm presently on windows) and it worked just fine. You're calling `grep.communicate()` after, right? – Anonymous Jul 28 '15 at 17:48
  • I didn't run grep.communicate(), why it is necessary? – triple fault Jul 28 '15 at 17:49
  • Then how did you run it? You get the desired output by running `stdout, stderr = grep.communicate()`. – Anonymous Jul 28 '15 at 17:53
  • I'm not sure regarding the stdout, stderr = grep.communicate(). Can you please edit the answer to include this? I'm totally unfamiliar to Python... – triple fault Jul 28 '15 at 17:56
  • Updated. The `communicate()` method returns a tuple of 2 elements, and you unpack them into individual variables `stdout` and `stderr`. You then use the `stdout` however you want, it's just a string. – Anonymous Jul 28 '15 at 18:03