Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do NOT terminate python subprocess when script ends

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?

like image 475
Adam Haile Avatar asked Oct 01 '22 04:10

Adam Haile


2 Answers

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

like image 89
synthesizerpatel Avatar answered Oct 17 '22 03:10

synthesizerpatel


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))))
like image 2
derricw Avatar answered Oct 17 '22 04:10

derricw