Quicktip: capture the output of a Django command
So, you want to programmatically call a Django command, and then capture it’s output? The documentation is very slim when it talks about how to call a Django command from code. To call a Django command from code it’s easy: just use call_command. To solve the trick of capturing the output of this I had to dig a little into the Django source.
The secret is: you can pass to call_command an argument called stdout to which you assign where the output is written (a file or any bite stream). Next, it’s a small sample code:
1 2 3 4 5 6 7
from django.core.management import call_command from StringIO import StringIO content = StringIO() call_command("dumpdata", stdout=content) content.seek(0) print content.read()
Here, we call python manage.py dumpdata, which will output all the data from all the models in all the installed apps from the current project in form of a JSON.
Hope it helped.