-1

I am trying the following:

#!/usr/bin/python

import os, subprocess

func = 'print("Hello World")'

x = subprocess.Popen(['mongo', '--eval', func], stdout=subprocess.PIPE,            
stderr=subprocess.PIPE, stdin=subprocess.PIPE)
print x.stdout.read()
print x.stderr.read()

But all I am getting is:

MongoDB shell version: 2.2.3

followed by two new lines. How do I capture the output of function execution?

WeaklyTyped
  • 1,331
  • 4
  • 16
  • 31
  • And what's wrong with the pymongo driver? – Spencer Rathbun May 10 '13 at 17:43
  • pymongo is not the question here. Here is something that is behaving not as expected and I want to understand why. :) – WeaklyTyped May 10 '13 at 17:45
  • I've tried your code locally and it worked - I do see `Hello world!`. – alecxe May 10 '13 at 17:57
  • The problem is, as others have said, in not waiting for the output to to finish before examining the output streams. Take a look at [this question](http://stackoverflow.com/questions/12965023/python-subprocess-popen-communicate-equivalent-to-popen-stdout-read). – aestrivex May 10 '13 at 19:26

2 Answers2

1

Reading the pipes gets whatever is currently inside said pipe. Your mongo is waiting to connect to the localhost. Since it doesn't return quickly enough, your read command is not getting the results. This may be because you don't have mongo running locally, but you will run into this problem repeatedly if you don't wait for the subprocess to complete.

Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73
0

Also, keep in mind that subprocess.Popen, to my knowledge, doesn't block. You would probably need to make a x.wait() call if you want the function to complete before trying to grab the output.

K.Niemczyk
  • 1,130
  • 3
  • 12
  • 26