如何在Django管理命令中停止子进程?

时间:2012-10-04 20:35:09

标签: python django subprocess

我有一个Python程序,我想作为一个子进程运行,应该由Django自定义管理命令调用。这是一个长期运行的程序,我必须手动停止。很容易启动子流程但是如何阻止它?

以下是我正在考虑的理论示例:

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

这可能是我在考虑的吗?如果没有,你能想出一些其他可能性来处理这种行为吗?我绝对想使用optparse选项使用相同的管理命令启动和停止相同的子进程。非常感谢!

1 个答案:

答案 0 :(得分:1)

嗯,p变量确实不存在于status == False的上下文中 当命令与p一起运行并且kill(pid可以正常运行)时,您可以使用pidfile来记下status == True的{​​{1}}运行命令时os.kill位于pid的{​​{1}}与pidfile一起运行。

你可能只需要首先写下运行subprocess命令的Python脚本的status == False并将其删除就可以使整个事情变得更简单。

然而,这不是很优雅。