Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save output from django call_command to a variable or file

Tags:

I am calling commands in Django from within a script similar to:

#!/usr/bin/python
from django.core.management import call_command
call_command('syncdb')
call_command('runserver')
call_command('inspectdb')

How to I assign the output from for instance call_command('inspectdb') to a variable or a file?

I've tried

var = call_command('inspectdb')

but 'var' remains none: purpose: inspect existing tables in legacy databases not created by django

like image 997
Fenrir Avatar asked Oct 24 '14 21:10

Fenrir


2 Answers

You have to redirect call_command's output, otherwise it just prints to stdout but returns nothing. You could try saving it to a file, then reading it in like this:

with open('/tmp/inspectdb', 'w+') as f:
    call_command('inspectdb', stdout=f)
    var = f.readlines()

EDIT: Looking at this a couple years later, a better solution would be to create a StringIO to redirect the output, instead of a real file. Here's an example from one of Django's test suites:

from io import StringIO

def test_command(self):
    out = StringIO()
    management.call_command('dance', stdout=out)
    self.assertIn("I don't feel like dancing Rock'n'Roll.\n", out.getvalue())
like image 136
BingsF Avatar answered Sep 22 '22 00:09

BingsF


This is documented in the Django Documentation under "Running management commands from your code > Output redirection".

To save to a variable, you could do:

import io
from django.core.management import call_command


with io.StringIO() as out:
   call_command('dumpdata', stdout=out)
   print(out.getvalue())

To save to a file, you could do:

from django.core.management import call_command


with open('/path/to/command_output', 'w') as f:
    call_command('dumpdata', stdout=f)
like image 38
Michael B Avatar answered Sep 21 '22 00:09

Michael B