Skip to content

Instantly share code, notes, and snippets.

@anandadake
Created January 19, 2024 12:05
Show Gist options
  • Select an option

  • Save anandadake/4a26cbc5a444d2815658e7d38122c031 to your computer and use it in GitHub Desktop.

Select an option

Save anandadake/4a26cbc5a444d2815658e7d38122c031 to your computer and use it in GitHub Desktop.
Flask - Subprocess - Termination : Kill process and all its child processes after a Popen
# -*- encoding: utf-8 -*-
import os
import sys
from psutil import Process
from subprocess import Popen
from flask import Flask, jsonify, current_app
app = Flask(__name__)
@app.route('/api/operation/start', methods=['POST'])
def operation_start():
# sys.executable => Use the current environment
p = Popen([sys.executable, '-u', './foo.py'])
current_app.config['JOB_FOO_PID'] = p.pid
return jsonify({'message': 'Started successfully'}), 200
@app.route('/api/operation/stop', methods=['DELETE'])
def operation_stop():
pid = current_app.config['JOB_FOO_PID']
if pid:
parent = Process(pid)
for child in parent.children(recursive=True):
child.kill()
parent.kill()
return jsonify({'message': 'Stopped successfully'}), 200
# ----------------------------------------
# launch
# ----------------------------------------
if __name__ == "__main__":
host = str(os.environ.get("HOST", '0.0.0.0'))
port = int(os.environ.get("PORT", 5000))
debug = bool(os.environ.get("DEBUG", True))
app.run(host=host, port=port, debug=debug)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment