views:

4371

answers:

4

I'm a python newbie, so sorry for the simple question.

I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.

Thank you.

+5  A: 

You probably want this answer to the StackOverflow question "How to call an external command in Python": http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python/92395#92395

The simplest approach is to use the os.system function, e.g.

import os
os.system("some_command &")

Basically, whatever you pass to the system function will be executed the same as if you'd passed it to the shell in a script.

Eli Courtwright
+8  A: 

If you want your process to start in the background you can either use system() and call it in the same way your shell script did, or you can spawn it:

import os
os.spawnl(os.P_DETACH, 'some_log_running_command')

See the documentation here. Note os.P_DETACH is win32 specific: you can use os.P_NOWAIT for better portability.

jkp
Remark: you must specify the full path to the executable. This function will not use the PATH variable and the variant that does use it is not available under Windows.
Sorin Sbarnea
+1  A: 

You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs to take a list or tuple 'args' as an argument that contains the program's name and its parameters; you may also want to define stdin, out and err for the new thread):

try:
    pid = os.fork()
except OSError, e:
    ## some debug output
    sys.exit(1)
if pid == 0:
    ## eventually use os.putenv(..) to set environment variables
    ## os.execv strips of args[0] for the arguments
    os.execv(args[0], args)
Gerald Senarclens de Grancy
`os.fork()` is really useful, but it does have a notable downside of only being available on *nix.
Evan Fosmark
The only problem with os.fork is that it is win32 specific.
jkp
Thanks for the hint - I haven't actually used non- *nix OSes for serious work in a while.
Gerald Senarclens de Grancy
@Gerald: lucky bugger! Oh the pain of windows...
jkp