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?
"&"
. The process you start (which is returned inprocess
) 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.Popen
already runs it in the background. That's why your code can continue to run while the process runs.