0

Django カスタム管理コマンドによって呼び出されるサブプロセスとして実行したい Python プログラムがあります。手動で停止する必要がある長時間実行プログラムです。サブプロセスを開始するのは簡単ですが、停止するにはどうすればよいですか?

これが私が考えていることの理論的な例です:

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オプションを使用して、同じ管理コマンドを使用して同じサブプロセスを開始および停止したいと思います。どうもありがとう!

4

1 に答える 1

1

まあ、p変数は確かにあなたのコンテキストには存在しませんstatus == False. コマンドが実行されたときに を書き留めて、コマンドを実行したときにその中にあるプロセスを強制終了することができ
ます。pidfileppidstatus == Trueos.killpidpidfilestatus == False

pid最初に subprocess コマンドを実行している Python スクリプトを書き留めて、それを強制終了するだけで、おそらく全体が少し簡単になります。

しかし、それはあまり優雅ではありません。

于 2012-10-04T20:41:28.477 に答える