Search code examples
pythonflasksubprocessinstancekill

python - instance of class gets deleted once executed. cannot kill subprocess anymore


I am trying to run Flask in a subprocess, so it gets its own core. so far so good. The code that starts flask in a subprocess is in my flaskSubprocess.py file, and can be seen below. In my main I import the flaskSubprocess file, and call it as seen below. Everything works, except the fact that the instance of flaskSubprocess is deleted right after it starts the subprocess, and thus i cant kill it anymore. How can I change my code so the instance does not get killed and i can kill it by calling the stop_server function?

The end goal is to start flask as subprocess so it runs on its own core, and then to terminate flask whenever the main process is terminated. I am running this on windows.

in my main.py:

    flaskSubprocess.flaskSubprocess()

the flaskSubprocess.py file:

import subprocess
from flask import Flask
import atexit
import sys

cli = sys.modules['flask.cli']
cli.show_server_banner = lambda *x: None
app = Flask(__name__)
prid = 0

class flaskSubprocess():
    # Start the server as a subprocess
    command = ['python', 'webserver.py']
    p = subprocess.Popen(command)
    prid = p.pid

    def stop_server(self):
        # Check if process is running
        if self.p.poll() is None:
        # Terminate the process
        self.p.terminate()
        # Wait for process to terminate
        self.p.wait()

    def __del__(self):
        # Stop server when instance is deleted
        self.stop_server()

# Register stop_server function with atexit
atexit.register(flaskSubprocess().stop_server)

Solution

  • What you want to do, is instead of saying:

    flaskSubprocess.flaskSubprocess()
    

    you want to say something like this to create an instance of the flaskSubprocess class:

    main_proc = flaskSubprocess.flaskSubprocess()
    

    to start the process, you would say:

    main_proc()
    

    and when you want to kill it, you can say:

    main_proc.stop_server()
    

    Hope this is a bit clearer.