2

I have been reading how to write a django management command by reading this.

I did also read the django documentation but I am wondering if it's possible to write few commands to run using only one file?

instead of writing a few different files.

2 Answers 2

3

I don't think so. If I'm reading the source correctly commands are discovered from CLI by looking for modules:

https://github.com/django/django/blob/master/django/core/management/init.py#L26

Which collects using:

https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules

Sign up to request clarification or add additional context in comments.

3 Comments

Well I read the docs and it clearly states that it discovers commands from each of the module which defines a class Command. Agrees with dm completely.
thx thx, just thought there might be a chance for alternatives
Check this out - I think you can rework this to meet our needs. Really cool script. masnun.com/2015/09/29/…
1

You can write multiple commands in one file. Follow below steps

  1. Create management/init.py folder under your app root directory
  2. Under management directory create commands/init.py folder
  3. Create mycommand.py file under commands directory
  4. Write below codes in mycommand.py file

from django.core.management.base import BaseCommand
from subprocess import Popen
from sys import stdout, stdin, stderr
import time
import os
import signal


class Command(BaseCommand):
    help = 'Run all commands'
    commands = [
        'python manage.py schedule',
        'python manage.py runserver'

    ]

    def handle(self, *args, **options):
        proc_list = []

        for command in self.commands:
            print("$ " + command)
            proc = Popen(command, shell=True, stdin=stdin,
                         stdout=stdout, stderr=stderr)
            proc_list.append(proc)

        try:
            while True:
                time.sleep(10)
        except KeyboardInterrupt:
            for proc in proc_list:
                os.kill(proc.pid, signal.SIGKILL)

  1. Change you cmd directory to yourProject root dir
  2. Run: python manage.py mycommand

This link helped me.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.