10

I've seen a ton of questions for the opposite of this which I find odd because I can't keep my subprocess from closing but is there a way to call subprocess.Popen and make sure that it's process stays running after the calling python script exits?

My code is as follows:

dname = os.path.dirname(os.path.abspath(__file__))
script = '{}/visualizerUI.py'.format(dname)
self.proc = subprocess.Popen(['python', script, str(width), str(height), str(pixelSize)], stdout=subprocess.PIPE)

This opens the process just fine, but when I close out of my script (either because it completes or with Ctrl+C) it also closes the visualizerUI.py subprocess, but I want it to stay open. Or at least have the option.

What am I missing?

3
  • 1
    Does this answer work for you? Commented Aug 4, 2014 at 21:18
  • Have you tried forking your script to the background? Commented Aug 4, 2014 at 21:51
  • huh?? Don't think Windows has forking Commented Aug 4, 2014 at 21:52

2 Answers 2

2

Remove stdout=subprocess.PIPE and add shell=True so that it gets spawned in a subshell that can be detached.

Sign up to request clarification or add additional context in comments.

3 Comments

If I add shell=True it doesn't work on Mac. And it does the samething without the stdout part.
By doesn't work on Mac I mean that the window doesn't come up (visualizerUI.py runs a Tkinter app)
It still does the same thing with shell=True
2

Another option would be to use:

import os
os.system("start python %s %s %s %s" % (script, str(width), str(height), str(pixelSize)))

To start your new python script in a new process with a new console.

Edit: just saw that you are working on a Mac, so yeah I doubt this will work for you.

How about:

import os
import platform

operating_system = platform.system().lower()
if "windows" in operating_system:
    exe_string = "start python"
elif "darwin" in operating_system:
    exe_string = "open python"
else:
    exe_string = "python"
os.system("%s %s %s %s %s" % (exe_string, script, str(width),
          str(height), str(pixelSize))))

3 Comments

I'm targeting Mac, Windows AND Linux... so it needs to work everywhere.
apparently on a Mac the equivalent command is "open", but I don't have one nearby to test.
I'm doing this in a FastAPI program, launched using uvicorn. As soon as the program terminates, the process I launched does too. even with nohup ... & put on it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.