Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch an independent process with python

Its a really simple question really, but I cant seem to find any solution.

I have a python script and I want to launch an independent daemon process. I want to call ym python script, launch this system tray dameon, do some python magic on a database file and quit, leaving the system tray daemon running.

I've tried os.system, subprocess.call, subprocess.Popen, os.execl, but it always keeps my script alive until I close the system tray daemon.

This sounds like it should be a simple solution, but I can't get anything to work.

EDIT: Solution for Windows: os.startfile() http://docs.python.org/library/os.html?highlight=startfile#os.startfile

Sometimes giving up and asking means you're just on the cusp of the answer.

like image 575
Jtgrenz Avatar asked Jul 20 '12 18:07

Jtgrenz


People also ask

How do you start a separate process in python?

How to Start a Process in Python? To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.

How subprocess works in Python?

The subprocess module present in Python(both 2. x and 3. x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands.

What function is the suggested way to interact with external processes from Python?

As we said before, the run function is the recommended way to run an external process and should cover the majority of cases.


2 Answers

You can use a couple nifty Popen parameters to accomplish a truly detached process on Windows (thanks to greenhat for his answer here):

import subprocess

DETACHED_PROCESS = 0x00000008
results = subprocess.Popen(['notepad.exe'],
                           close_fds=True, creationflags=DETACHED_PROCESS)
print(results.pid)

See also this answer for a nifty cross-platform version (make sure to add close_fds though as it is critical for Windows).

like image 120
jtpereyda Avatar answered Oct 19 '22 03:10

jtpereyda


Solution for Windows: os.startfile()

Works as if you double clicked an executable and causes it to launch independently. A very handy one liner.

http://docs.python.org/library/os.html?highlight=startfile#os.startfile

like image 39
Jtgrenz Avatar answered Oct 19 '22 03:10

Jtgrenz