Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Daemonizing a python script in debian using virtualenv

I've seen a lot of scripts for daemonizing a python script in linux, but not much information about how to use them. Could anyone guide me on this?

I currently have a lengthy python script that listens on a socket for an incoming message, if it's the correct format accepts it and then stores it into the database. The script itself just opens the socket and then listens on a while true (which does the job!) and does all the work in there.

To daemonize it, would I have to modify my current script or call it from a separate script? I've seen examples of both but got neither to work.

Also, I'm using virtualenv which might the root of my problems, any hints on using this with daemonized scripts?

like image 290
ingh.am Avatar asked Oct 18 '11 12:10

ingh.am


1 Answers

Create a shell-script that activates the virtual environment, and runs your Python script in the background.

Also, there should by a python module in the virtual environment that you can import and activate the environment from too. I don't have virtualenv working at the moment, so I can not check where it is, but search for activate (or something similar) in the virtual environment and you should find it.

Edit: Added a minimal Debian init.d script

The absolute minimal script needed to start a daemon when the computer boots, is this:

#!/bin/sh
/path/to/program &

The & makes the program run in the background, so it wont stop the rest of the boot process.

For a more complete script, copy /etc/init.d/skeleton and edit the new file. The important part to edit is the block at the beginning (between ### BEGIN INIT INFO and ### END INIT INFO, which is used by the update-rc.d program), and the NAME, DAEMON and DAEMON_ARGS variables. Hopefully that should be all that's needed for making a startup-script.

Activate the script as this:

sudo update-rc.d <name of script> defaults
sudo update-rc.d <name of script> enable

And to start it:

sudo update-rc.d <name of script> start

The <name of script> is just the name, not the full path.

like image 128
Some programmer dude Avatar answered Oct 01 '22 11:10

Some programmer dude