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?
for command in self.commands:
print "$ " + command
proc = Popen(command, shell=True, stdin=stdin, stdout=stdout, stderr=stderr)
proc_list.append(proc)
while True:
time.sleep(10)
except KeyboardInterrupt:
for proc in proc_list:
os.kill(proc.pid, signal.SIGKILL)
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
)