I have a Python program that I want to run as a subprocess which should be invoked by a Django custom management command. It is a long-running program which I have to stop manually. It is easy to start the subprocess but how to stop it?
Here is a theoretical example of what I'm thinking about:
import subprocess
from optparse import make_option
from django.core.management.base import BaseCommand
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--start',
action='store_true',
dest='status'
),
make_option('--stop',
action='store_false',
dest='status',
default=False
)
)
def handle(self, *args, **options):
status = options.get('status')
# If the command is executed with status=True it should start the subprocess
if status:
p = subprocess.Popen(...)
else:
# if the command is executed again with status=False,
# the process should be terminated.
# PROBLEM: The variable p is not known anymore.
# How to stop the process?
p.terminate() # This probably does not work
Is that possible what I'm thinking about? If not, can you come up with some other possibilities of how to handle this behavior? I definitely would like to start and stop the same subprocess using the same management command using optparse options. Thanks a lot!