Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Keep processes started by subprocess.Popen alive after exiting

I am making a virtual assistant that can start several programs using subprocess.Popen("path/to/app.exe"). But when I exit the python program, all of processes are killed. I want the processes (the applications started with Popen) to be independent and remain alive after main process is killed.

I have tried adding start_new_session=True as argument in subprocess.Popen() as some posts have suggested, but it's still not working.

I don't think showing the code is necessary, but still, here you go.

app_path = r'C:\Users\myusername\AppData\Local\Discord\app-1.0.9001\discord.exe'
subprocess.Popen(app_path)  # also tried adding start_new_session=True as argument
like image 919
Kirk KD Avatar asked May 20 '26 19:05

Kirk KD


1 Answers

Since you're on Windows, you can call the start command, which exists for this very purpose: to run another program independently of the one that starts it.

The start command is provided by the command-line interpreter cmd.exe. It is not an executable: there is no start.exe. It is a "shell command" (in Linux terminology), which is why shell=True must be passed when creating the subprocess.

You won't be able to communicate with the subprocess started in this way, that is, not via the pipe mechanism provided by the subprocess module. So instead of Popen, you may just use the convenience function run:

from subprocess import run
app = 'notepad'
run(['start', app], shell=True)

The example starts the Notepad editor (instead of Discord in the question) in order to make it easier to reproduce.

In cases where the full path to the app contains spaces, we can either call start like so

app = r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
run(f'start "" "{app}"', shell=True) 

using the Edge browser in this example, or pass the directory separately:

folder = r'C:\Program Files (x86)\Microsoft\Edge\Application'
app = 'msedge.exe'
run(['start', '/d', folder, app], shell=True)

This is needed because start treats a single argument as the window title if that argument is in quotes. And only if not does it treat it as the command. See "Can I use the start command with spaces in the path?" (on SuperUser) for more details.

like image 50
john-hen Avatar answered May 24 '26 09:05

john-hen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!