DkM
DkM

Reputation: 800

Popen Communicate with PIPE does not catch all output of process

I'm trying to run a python script and capture the output of it. It seems like after the first output line it redirects to the console instead of to my string. Manage.py is a command-line utility for managing Django projects, like starting the production server or running unit tests.

This is my code:

import os, string, datetime
from subprocess import Popen, PIPE

def runProcess(command, parameters):
    process =  Popen([command]+parameters, stdout=PIPE)
    output=process.communicate()[0]
    return output

testStatus=runProcess('python',['manage.py','test','coffeebean'])

print ("*****Own output*****")
print(testStatus)

This is the output:

Ran 1 test in 0.000s

OK
*****Own output*****
Creating test database for alias 'default'...
Destroying test database for alias 'default'...

Why are the first lines not catched?

Best regards, Daniel

Upvotes: 2

Views: 2373

Answers (1)

phihag
phihag

Reputation: 287825

Because they're written to stderr, not stdout. Try

def runProcess(command, parameters):
    process = Popen([command]+parameters, stdout=PIPE,stderr=PIPE)
    return process.communicate()

out,err =runProcess('python',['manage.py','test','coffeebean'])

print ("*****Own output*****")
print(out)
print ("*****Own error output*****")
print(err)

Upvotes: 3

Related Questions