0

I have method that runs a bash script in the background via subprocess.Popen():

def my_method():
        try:
            process = subprocess.Popen(["bash", "my_script.sh", "&" ],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            )
        except Exception as e:
            print(f"Error running the script: {e}")
        return process

def caller():
        process = my_method()

Now, I want the caller method to properly terminate the background script. I tried several solutions like process.kill() and process.terminate(). But, none of them works. I was wondering is the best solution for this?

4
  • The problem is your "&" . The process you start (which is returned in process) ends immediately. Your script is running in a completely separate process that you can't access. So, remove the "&". Popen already runs it in the background. Sep 27 at 18:46
  • but I need that process to run in the background. So, the thing is that I am trying to write a small code that launches a local server in the background, makes sure the server is up and running. Sends some requests to the server. And once done has to release all the resources of the server and terminate it. Now, the problem is that I can launch the server in the background, but I can't terminate it properly so that it releases all the resources.
    – amin
    Sep 27 at 18:52
  • 1
    Maybe you didn't read where I wrote that Popen already runs it in the background. That's why your code can continue to run while the process runs. Sep 27 at 18:56
  • oh sorry. I missed that. Thanks.
    – amin
    Sep 27 at 19:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.