Getting Python to fork?

Bernard bernard.chhun at gmail.com
Mon Feb 4 09:58:51 EST 2008


On 3 fév, 21:52, Gilles Ganault <nos... at nospam.com> wrote:
> Hello
>
>         I need to launch a Python script, and fork it so that the calling
> script can resume with the next step will the Python script keeps
> running.
>
> I tried those two, but they don't work, as the calling script is stuck
> until the Python script ends:
>
> sys.stdout = open(os.devnull, 'w')
>
> =====
> #if os.fork():
> pid = os.fork()
> if pid > 0:
>         sys.exit(0)
> =====
>
> Should I use another library to do this?
>
> Thank you.

this works out for me:

def tryToFork(cbk, fork=True):
    '''
    If possible, start the process as a daemon under linux
    otherwise start it normally under Windows

    the 'fork' flag may deactivate the forking if it is set to False
    '''

    #UNIX/LINUX: FORK
    if fork:
        try:
            #Fork and commit suicide
            if os.fork():
                sys.exit(0)

            #What to do in parent process
            else:
                os.setsid()
                sys.stdin = open('/dev/null')
                sys.stdout = open('/dev/null', 'w')
                sys.stderr = open('/dev/null', 'w')
                cbk()

        #WINDOWS: JUST RUN
        except AttributeError:
            cbk()

    #PLAIN, NORMAL RUN
    else:
        cbk()

def whateverFunctionToFork():
    pass
tryToFork(whateverFunctionToFork, True)



More information about the Python-list mailing list