[Django]-Can Django manage.py custom commands return a value? How, or why not?

35👍

If you want to get the output of call_command(), you need to capture stdout. Here’s how you can do it:

out = StringIO()
call_command('call_custom_command', stdout=out)

value = out.getvalue()
print value

This technique is actually used in django tests for testing management commands.

Demo:

>>> from django.core.management import call_command
>>> from StringIO import StringIO
>>> out = StringIO()
>>> call_command('validate', stdout=out)
>>> out.getvalue()
'0 errors found\n'

Hope that helps.

👤alecxe

Leave a comment