Launch an independent process with python

Question:

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 have 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.

Asked By: Jtgrenz

||

Answers:

I would recommend using the double-fork method.

Example:

import os
import sys
import time

def main():
    fh = open('log', 'a')
    while True:
        fh.write('Still alive!')
        fh.flush()
        time.sleep(1)

def _fork():
    try: 
        pid = os.fork() 
        if pid > 0:
            sys.exit(0) 
    except OSError, e: 
        print >>sys.stderr, 'Unable to fork: %d (%s)' % (e.errno, e.strerror) 
        sys.exit(1)


def fork():
    _fork()

    # remove references from the main process
    os.chdir('/')
    os.setsid()
    os.umask(0)

    _fork()

if __name__ == '__main__':
    fork()
    main()
Answered By: Wolph

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

Answered By: Jtgrenz

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).

Answered By: jtpereyda