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?

  • Quick solution use "screen". Start your screen with "screen -S fetcher" then start your script and send it to background. Or follow this example http://stackoverflow.com/questions/1423345/can-i-run-a-python-script-as-a-service – deagh Oct 26 '13 at 10:53
  • If you're on Fedora you could use systemd to glue everything together. – Cristian Ciupitu Oct 27 '13 at 18:25

5 Answers5

4

Use the python-daemon package or use daemontools.

Please also see Process Management.

Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151
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.

Teddy
  • 5,204
  • 1
  • 23
  • 27
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 ]
Petter H
  • 3,443
  • 1
  • 16
  • 19
  • 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 '13 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? – toppledwagon Oct 27 '13 at 05:16
1

Simple workaround is: nohup

nohup myprogram > myprogram.log &
Scott Pack
  • 14,907
  • 10
  • 53
  • 83
Veniamin
  • 863
  • 6
  • 11
0

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

nandoP
  • 2,021
  • 14
  • 15