Capture mongo shell output using subprocess.Popen
Question: 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?


Answer: 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.

