1

I have a piece of code that is in charge of spawning new independent processes (which should live after the main process terminates).

When I run this code using 'run' from PyCharm they do get spawned independently and stay alive even after their parent terminates.

The problem is when running from a cmd shell (in windows), they get spawned but it seems as if they are bound to the spawning shell (Not the python script), so the main script finishes but the shell stays active and once I close it the processes gets terminated.

service_path = "some_service_path" service_arguments = "some arguments" python_execution_location = os.path.join(os.environ["PYTHON3_ROOT"], "python.exe") execution_value = "{} {} {}".format(python_execution_location, service_path, service_arguments) my_process = subprocess.Popen(execution_value, shell=True) 
6
  • @Abhineet Why should that change anything? According to the documentation setting shell=true sets the CREATE_NEW_CONSOLE flag to true by default, meaning it should be completley independent. Commented Mar 18, 2019 at 6:34
  • okay, I read about that. Are you trying to run some service code using Python.exe? And when you say, the child terminates, you mean the Python.exe and service, both of them terminates on closing the console, right? Commented Mar 18, 2019 at 6:56
  • The python scripts are "services" which need to get raised by the main python script (main process). When I close the shell all processes terminate. Commented Mar 18, 2019 at 7:00
  • @Rohi - Does this help? stackoverflow.com/questions/32808730/… Commented Mar 20, 2019 at 14:38
  • @ScottSkiles I wasn’t aware of the pythonw.exe so I learned something new. But unfortunately it doesn’t help me because I do want the console to be visible. I just want the spawned processes to not be bound to it. Commented Mar 20, 2019 at 21:18

2 Answers 2

2
+50

In windows, you could make use of creationflags option of Popen.

DETACHED_PROCESS = 8 # bit mask taken from the linked doc below subprocess.Popen(executable, creationflags=DETACHED_PROCESS, close_fds=True) 

Which will create a detached process (demon process).

https://learn.microsoft.com/en-us/windows/desktop/ProcThread/process-creation-flags

For console processes, the new process does not inherit its parent's console (the default). The new process can call the AllocConsole function at a later time to create a console. For more information, see Creation of a Console.

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

1 Comment

Just use subprocess.DETACHED_PROCESS.
1

You might need to send a creationflags arg to make it a seperate process altogether

subprocess.Popen(executable, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP, close_fds=True) 

python.org link

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.