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
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())
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With