0

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!

pemistahl
  • 9,304
  • 8
  • 45
  • 75

1 Answers1

1

Well, the p variable does indeed not exist in your context of status == False.
You could use a pidfile where you write down p's pid when the command is ran with status == True and kill (os.kill would work well) the process whose pid is in that pidfile when you run the command is ran with status == False.

You probably make the whole thing a bit simpler by just writing down the pid of the Python script that's running the subprocess command in the first place and kill that one.

That's not very graceful however.

Community
  • 1
  • 1
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • Ah, your first option sounds like a good idea. Is there a Python module to write such a pidfile automatically or do I simply take `Popen.pid` and manually write that to a file? – pemistahl Oct 04 '12 at 20:59
  • @PeterStahl Just write it to a file, you're basically just doing: `with open('proc.pid', 'w') as pidfile: pidfile.write(p.pid)` – Thomas Orozco Oct 04 '12 at 21:02
  • Alright, good to know. I'm going to try this now and if it works I will mark your answer as the accepted one. Thank you! :) – pemistahl Oct 04 '12 at 21:17