プロセスをatexit.register
終了する関数を作成します。
import atexit
process = subprocess.Popen(args.server_file_path)
atexit.register(process.terminate)
pid = process.pid
または多分:
import atexit
process = subprocess.Popen(args.server_file_path)
@atexit.register
def kill_process():
try:
process.terminate()
except OSError:
pass #ignore the error. The OSError doesn't seem to be documented(?)
#as such, it *might* be better to process.poll() and check for
#`None` (meaning the process is still running), but that
#introduces a race condition. I'm not sure which is better,
#hopefully someone that knows more about this than I do can
#comment.
pid = process.pid
これは、Pythonを非優雅な方法で死に至らしめるために厄介なことをした場合には役に立たないことに注意してください(たとえば、経由os._exit
またはまたはを引き起こしたSegmentationFault
場合BusError
)