1. Skip to navigation
  2. Skip to content

Using call_command

While creating the most recent Django Screencast on Custom Management Commands, I had it in my show notes to mention how you can call Django’s management commands from an external script. There’s probably several different ways to accomplish this, but the simplest and “baked in” way to do this is through the use of the call_command function. This function is part of django.core.management.

For example, if we wanted to call sqlall from the shell we could do something like the following:


>>> from django.core.management import call_command
>>> call_command('sqlall', 'delinkuent')

The call_command function’s signature looks like:


call_command(name, *args, **options)

It accepts the name of the command we’re executing, any required arguments, and options to the command. If we have a command with an argument and options it might look like the following:


>>> call_command('say_hello_name', 'michael', capitalize=True)
Hello Michael

This approach works fine with any custom management commands you may have created as well.

There is a caveat to this approach. You must be sure that you’ve properly set up your DJANGO_SETTINGS_MODULE environment variable. For more information about this see James Bennett’s excellent writeup on the subject.


Discussion