3

I would like to run django unittest via python subprocess and I would like to store all the data (especially the words Failure or OK) in a variable. However when I use subprocess to run this the output only contains the parts:

"Creating test database for alias 'default'..." "Destroying test database for alias 'default'..."

The rest just comes out on the screen which is what I don't want. How can I get all of the output from a django unittest into a variable.

args_list = ['python', '/path/to/manage.py', 'test', 'myapp']
process=subprocess.Popen(args_list, stdout=subprocess.PIPE)
output, errors = process.communicate()
print output

output will just equal: Creating test database for alias 'default'... Destroying test database for alias 'default'...

However on my screen the whole standard output of the django unittest appears. How can all of the output be stores to a variable.

Christopher H
  • 2,044
  • 6
  • 24
  • 30

4 Answers4

2

You need to redirect stderr to stdout. Here is the fixed code:

args_list = ['python', '/path/to/manage.py', 'test', 'myapp']
process=subprocess.Popen(args_list, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
output, errors = process.communicate()
print output

Alternatively in the shell, you can type something like this:

python manage.py test myapp > stdout.txt 2> stderr.txt
Nate-Bit Int
  • 165
  • 9
1

You can process test results with the unittest.TestResult object. See https://stackoverflow.com/a/284192/579461 for an example.

Community
  • 1
  • 1
Brian Cajes
  • 3,274
  • 3
  • 21
  • 22
1

If you truly want to redirect stdout to a variable for examination, then you can do it using the following code:

from cStringIO import StringIO
import sys

output = StringIO()
sys.stdout = output
print "Hello World!"
print 42
sys.stdout = sys.__stdout__
print output.getvalue()
>>>
Hello World!
42
Talvalin
  • 7,789
  • 2
  • 30
  • 40
0

How can all of the output be stores to a variable.

Redirect stderr to stdout:

from subprocess import check_output, STDOUT

output = check_output(args_list, stderr=STDOUT)
print output,
jfs
  • 399,953
  • 195
  • 994
  • 1,670