Python 如何在Django管理命令中停止子进程?
我有一个Python程序,我想作为子进程运行,它应该由Django自定义管理命令调用。这是一个长期运行的程序,我必须手动停止。启动子流程很容易,但如何停止它 下面是我所想的一个理论例子:Python 如何在Django管理命令中停止子进程?,python,django,subprocess,Python,Django,Subprocess,我有一个Python程序,我想作为子进程运行,它应该由Django自定义管理命令调用。这是一个长期运行的程序,我必须手动停止。启动子流程很容易,但如何停止它 下面是我所想的一个理论例子: import subprocess from optparse import make_option from django.core.management.base import BaseCommand class Command(BaseCommand): option_list = B
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
这可能是我想的吗?如果没有,你能想出一些其他的方法来处理这种行为吗?我当然希望使用相同的管理命令和optpasse选项启动和停止相同的子流程。非常感谢 嗯,
p
变量确实不存在于status==False的上下文中
您可以使用一个脚本,当命令以status==True
运行时,您可以在其中写下p
的pid
,并且kill(os.kill
会很好地工作)当您以status==False>运行命令时,其pid
位于该pidfile
文件中的进程
通过写下首先运行subprocess命令的Python脚本的pid
,并杀死该脚本,您可能会使整个过程变得更简单
然而,这不是很优雅 啊,你的第一个选择听起来是个好主意。有没有Python模块可以自动编写这样的pid文件,或者我只是简单地使用Popen.pid
并手动将其写入一个文件?@PeterStahl只需将其写入一个文件,您基本上只需执行:以open('proc.pid','w')作为pid文件:pidfile.write(p.pid)
好的,很高兴知道。我现在要试试这个,如果它有效的话,我会把你的答案标记为被接受的答案。谢谢!:)