Created
January 19, 2024 12:05
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- 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