3

I have created a service which consists of a web fronted (nginx), python runner glue handler (uwsgi) and my own python code (fetcher). I have made a script (deploy.sh) to start the difference services:

nginx
uwsgi --ini inifie.ini
python fetcher.py & disown

My question is regarding how I start my python daemon. I want it to run in the background. It should not print anything to my current terminal. If I add "print" calls to my fetcher script I currently see them in the terminal window.

So my question is: how do I start my fetcher.py script as a daemon?

2
  • Quick solution use "screen". Start your screen with "screen -S fetcher" then start your script and send it to background. Or follow this example stackoverflow.com/questions/1423345/…
    – deagh
    Oct 26, 2013 at 10:53
  • If you're on Fedora you could use systemd to glue everything together. Oct 27, 2013 at 18:25

5 Answers 5

4

Use the python-daemon package or use daemontools.

Please also see Process Management.

2

Do you want to do this from the shell script or from the Python program?

If from the shell script, it's quite simple:

nohup fetcher.py >/dev/null 2>&1 </dev/null & disown

If you want to do it from the Python program, I suggest you look into using the python-daemon module, also probably available as a pre-made package for your favorite Unix-like OS.

2

I often do a fork like this in the python program:

if __name__ == '__main__':
    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
    except OSError:
        report( "unable to fork: %s" % sys.exc_info()[1])
        raise
    [program starts here ]
2
  • It's not that simple. You should at least do a double fork, and also setsid(). And what about stdout/stderr? Simpler to just use the python-daemon module.
    – Teddy
    Oct 26, 2013 at 20:27
  • 1
    True, it's not quite that simple, but at least he's pointing the poster toward an actual daemon vs a hack with nohup or screen. Handle cwd and standard file handles then you get even closer to an actual daemon. Do you run apache in a screen session? Oct 27, 2013 at 5:16
1

Simple workaround is: nohup

nohup myprogram > myprogram.log &
0

supervisord works well, and can be confied to send out alerts on failures

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .