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:

from django.core.management import call_command
from StringIO import StringIO 
content = StringIO()
call_command("dumpdata", stdout=content)
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.


10 Responses to “Quicktip: capture the output of a Django command”
  1. pkeeper says:

    That’s what I was searching for

  2. some dude says:

    Thanks Nicolae

  3. Bernd says:

    Excellent! Saved me a lot of work. Thank you very much.

  4. julz says:

    or you can pipe the output to a file:

    python manage.py dumpdata > dumpdata.json

  5. Izkata says:

    A note, this only works if the manage command *returns* the data to be printed out after completion.

    Others, like “migrate”, return nothing and instead use “print”, so django’s management system doesn’t redirect the output for them.

    Here’s how to capture everything:

    from django.core.management import call_command
    from StringIO import StringIO
    import sys

    orig_stdout = sys.stdout
    sys.stdout = content = StringIO()
    call_command(‘migrate’, db_dry_run=True)
    sys.stdout = orig_stdout
    print content.read()

  6. Nimmi says:

    Thanks a lot ! I had been looking for this.

  7. Andrew says:

    Thanks a lot!

  8. elmar says:

    In the meanwhile ( python 3.4, django 1.7 ) I found an easier solution. No StringIO library needed!

    f_stream = open( “my_dumpfile.txt”, ‘w’, encoding=”utf-8″ )
    management.call_command( “dumpdata”, indent=4, stdout=f_stream )



Check out what others are saying about this post...
  1. […] here why. This runs the command without the stdout=content […]

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!