The Django call_command()

For one of my Django sites, I run a bunch of maintenance commands each night. To make development easier, I write each maintenance function as a stand alone command, then I pull them all together using a main Django command that uses the “call_command()”.

I recently ran into a problem that made me wonder if the program that calls call_command() waits until it’s done to go to the next command. Here is some code to test that:

from django.core.management.base import BaseCommand
from django.core.management import call_command

class Command(BaseCommand):
    help = 'Main'

    def handle(self, *args, **options):
        print 'Starting main'
        call_command('junk1')
        call_command('junk2')
        print 'Completed main'

Here is junk1.py:

from time import sleep

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = 'Junk 1'

    def handle(self, *args, **options):
        print 'Starting 1'
        sleep(10)
        print 'completed 1'

Here is junk2.py:

from time import sleep

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = 'Help text'

    def handle(self, *args, **options):
        help = 'Junk 1'
        print 'Starting 2'
        sleep(1)
        print 'completed 2'

Here is the output:

Starting main
Starting 1
completed 1
Starting 2
completed 2
Completed main

So call_command is synchronous.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s