我有一个 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 选项使用相同的管理命令来启动和停止相同的子进程。非常感谢!