Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django管理命令中停止子进程?_Python_Django_Subprocess - Fatal编程技术网

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

我有一个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

这可能是我想的吗?如果没有,你能想出一些其他的方法来处理这种行为吗?我当然希望使用相同的管理命令和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)
好的,很高兴知道。我现在要试试这个,如果它有效的话,我会把你的答案标记为被接受的答案。谢谢!:)