I was to make a launcher application, I haven't found a way to detach a sub-process entirely from the spawning python process.
When I launch a program with my desktop's (cinnamon's) launcher the process tree goes:
/sbin/init -> mdm -> mdm -> cinnamon-session -> cinnamon -> the-app-i-launched
Of the threads I read, this one was the most insightful/helpful: Launch a completely independent process. But gets muddied answers as the OP is looking to run python code, which can often be achieved in many usually-preferred ways than by spawning an independent process.
From other posts from stack overflow that do not answer how to launch a detatched python process:
- Running daemonalized python code: Applicable to running python code/module as a daemon, (not another process/application) detached from the python instance.
- subprocess.call: Process spawns as a child of the python process.
- os.system: Process spawns as a child of the python process.
- close_fds: (Apparently) Windows(R)-only solution, need portable solution (primary target is Debian linux). Attempting to use
close_fds=True
on linux, process spawns as a child of the python process.
- creationflags: Windows(R)-only solution. On linux raises:
ValueError: creationflags is only supported on Windows platforms
.
- prefix launched process with
nohup
: Process spawns as a child of the python process. As far as I know, nohup
or equivalent is not available on all platforms, making it a linux-only solution.
- os.fork: Same as "Running daemonalized python code".
- multiprocessing: Same problem as "Running daemonalized python code": useful only for running python code/module.
- os.spawnl* + os.P_NOWAIT: Deprecated functions are undesirable to use for new code. In my testing I was not able to see my process actually spawned at all.
- os.spawnl* + os.P_DETACH: Windows(R)-only, seemingly removed in current python 2.X versions:
AttributeError: 'module' object has no attribute 'P_DETACH'.
- os.system + shell fork: I was able to actually see my process run detatched from the python process with this, however I am woried that it has the faults:
- Relies on running commands in a shell, which is more vulnerable to maliciousness, intentional or otherwise?.
- Relies on non-portable? POSIX/shell? syntaxies that may not be interpenetrate on non-Linux platforms. Which I haven't dug up any good reference for portability on Partial Ref.
- subprocess.Popen Alt: I still only observed the sub-process running as a child of the python process.
A working solution can be found in JonMc's answer here. I use it to open documents using 'xdg-open'.
You can change the stderr argument to stderr=open('/dev/null', 'w'),
if you do not want a logfile.