Here’s the scneario:
I have 4-5 different commands which I need to run every time I want to test my app. So I decided to write one command to rule them all. I run this one command and it runs the others using the subprocess module. It stores the processes created in a list. Then it goes to sleep inside a while loop waiting for a KeyboardInterrupt exception (which is fired when you press Ctrl + C – that is you send an interrupt signal from your keyboard). When this exception occurs, we iterate through the process ids we stored and kill them all. Simple, No?
Talk is cheap, here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
from django.core.management.base import BaseCommand from subprocess import Popen from sys import stdout, stdin, stderr import time, os, signal class Command(BaseCommand): help = 'Run all commands' commands = [ 'redis-server', 'python manage.py spider', 'python manage.py schedule', 'python manage.py postprocess', '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) |
So this is how it looks on my machine:
🙂
4 replies on “Python/Django: Running multiple commands in subprocesses”
Thank you for the post. I’m wondering where you put this code in your Django project…
The django docs gives a good idea of where you can place this: https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/
Nice post ,i want to know if we dont add “runserver” command , can we stop it with out kill signal
You don’t know how much you helped me. I have spent full one day searching to run this. Thanks MASNUN