-1

I am getting no output from the following code but it is not producing an error either. When command is typed manually on command line I get a lot of output.

grepCommand = "box | grep " + grepHostKey
grepCommand = grepCommand.split()

p = subprocess.Popen(grepCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(hostString, err) = p.communicate()
print hostString    
print err

output:

If I add shell=True I get the expected response from just the "box" command and it is not piped into the grep. I have seen it is advised to not use shell=True. I have tried bufsize=8192 which is big enough to handle but still nothing. Any thoughts as to what is wrong?

futevolei
  • 180
  • 2
  • 14

1 Answers1

1

The pipe is a shell symbol. That is why this could only work with shell=True. But as you have said, this is not best practice. Here is a code you can use to manually pipe commands with subprocess.

box_process = Popen(["box"], stdout=PIPE)
grep_process = Popen(["grep", grepHostKey], stdin=box_process.stdout, stdout=PIPE)
box_process.stdout.close()
(hostString, err) = grep_process.communicate()
Anis
  • 2,984
  • 17
  • 21