【Python】subprocessで外部プログラムを呼び出し、外部から実行/終了できるようにする
Author: 水卜
Author: 水卜
以下の処理を実装したため知見をメモ
サンプルコードではイベントの発火/受け取りは独自のpubsubクラスで行なっているが、ここはなんでもいい。
重要なのは、callbackの中でsubprocessを呼ぶ関数を別スレッドで呼ぶところ。
こうすることで、終了のイベントを受け取ってプロセスを終了させることができる。
from subprocess import Popen, PIPE
from pathlib import Path
import threading
from logging import getLogger
def __exec_external_program(commands: str, exe_dir: str):
global process
os.chdir(exe_dir)
process = Popen(commands.split(' '))
process.wait()
if process.returncode != 0:
logger.info('process is aborted.')
sys.exit(1)
def callback(data):
"""
:param data: Subscribeした値
"""
global process
if 'OK' in data:
logger.info('start')
thread = threading.Thread(target=__exec_external_program, args=['python mock.py', config.exec_dir()])
thread.start()
elif 'STOP' in data:
logger.info('stop')
if process is not None:
process.kill()
if __name__ == '__main__':
pubsub.subscribe('sample_topic', callback)