Skip to main content

Wondering how to start/stop a Python script from init.d ?


If you just looking for the solution please go to solution heading directly!!

So I have been asked to start my python server at the time of boot up. As I am pretty new to Python and have never done this, I have to go and find some help from none other than our best bud google.
So when I googled I had found couple solution like

http://www.pietervanos.net/knowledge/start-python-script-from-init-d/

The problem with the above solution is that when you want to stop your Python script using the above solution it kills all of the python scripts running on the machine. Obviously we don't want to kill other Python script, don't we?

And had found couple of other solutions which I was not able to understand or I could not make them work. So the solution which I am using is.

Solution :

The plan is to make your Python script in my case my Python server to store its pid in some file, lets say in location /var/run/your_script.pid.
So I am making your life easy, use this below function to do it  :D
def store_pid():
    """ Writes the PID into a pidfile as /var/run/your_script.pid """
    pidfile = "/var/run/your_script.pid"
    pid = str(os.getpid())
    if os.path.exists(pidfile):
        os.remove(pidfile)

    file(pidfile, 'w').write(pid)

So as you see one has to
import os;
for this piece of code to work.

So once you have this function, its your responsibility to call this function at the right place in your Python script. Cause you need to take care of the situation where some user is trying to run your script again at that time you may loose your old PID file and hence never able to stop the script with out killing it explicitly.

Once you figure it out where to call it and how to handle the situation lets dig into the init script !
So again lets not make you look around the places for example inti script and all so find the script below !!
#!/bin/sh
#
# source function library
. /etc/rc.d/init.d/functions

RETVAL=0
prog="PATH_TO_YOUR_SCRIPT"
# Users can connect to server through any of the assiged IP.
# This location and file must be same as the one created in your script.
pidfile="/var/run/your_script.pid"
lock_file=/var/lock/subsys/you_script_name

start() {
    $prog &
    echo "Starting $prog"

    RETVAL=$?
    [ "$RETVAL" = 0 ] && touch $lock_file
    echo
}

stop() {
    killproc -p $pidfile
    #rm -f $LOCK_FILE
    rm -f $pidfile

    RETVAL=$?
    [ "$RETVAL" = 0 ] && touch $lock_file
    echo
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
        status $prog
        RETVAL=$?
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|status}"
      RETVAL=1
esac
exit $RETVAL


One of the most import thing to do to make your script run at the start time is
chkconfig --add <your_init.d_script>
chkconfig --level 345 <your_init.d_script> on

So now lets discuss some of the problems.

When we use the normal init.d script to start and stop, it gives you warning if that program is already running ! unfortunately I could not figure it out how to do it with this.
So one has to carefully handle the situation where someone tries to start the already running script by calling the store pid in appropriate locations !!

FYI, OS I was running.


# uname -a 
Linux Dell620 2.6.32-220.17.1.el6.x86_64 #1 SMP Wed May 16 00:01:37 BST 2012 x86_64 x86_64 x86_64 GNU/Linux
# cat /etc/redhat-release 
CentOS release 6.2 (Final)

Please do let me know in the comment, if this method is wrong or if there is any other better method to do the same.

                                                                                                                           - Cheers :)

Comments

Popular posts from this blog

Enable stats GUI on haproxy.

Add bottom snippet to the haproxy.conf below the defaults section. listen  stats         bind 19.41.259.10:1234         mode            http         log             global         maxconn 10         clitimeout      100s         srvtimeout      100s         contimeout      100s         timeout queue   100s         stats enable         stats hide-version         stats refresh 30s         stats show-node         stats auth admin:password         stats uri  /haproxy?stats Make sure you are updating the IP address on the bind to your VIP and if you want, you can change th...

PART 1: How to use SoftLayer Python library.

Install the SoftLayer's Python library.  pip install softlayer or clone the source code from the github and install from source code. git clone https://github.com/softlayer/softlayer-python.git python setup.py install Once we have installed the SoftLayer Python library we are ready to use it as shown in the following example. You need your username and api key to run the below example. One can get both user name and api key at the following link once you login successfully. https://control.softlayer.com/account/user/profile Accounts username and API key E.g. showing how to use SoftLayer Python library. import SoftLayer from SoftLayer.managers.image import ImageManager client = SoftLayer.Client(username='', api_key='') image_manager = ImageManager(client) mask = "mask[id,name,note]" imageTemplates = image_manager.list_private_images(mask='id,name,note') print("ID - Name - Note") for template in imageTem...

atoi implementation in C

Algo for you own implementation of atoi :) :) int val = 0;    for each char in the string       val = val *10 + char-48 lets write some code for it :) int myatoi(char *convetIt) {      int val = 0;      while(*convetIt)      {           val = (val * 10) + *convetIt - 48;           convetIt++;      } } So how it works? lets see how it works take an example of string "123" formula : val = (val * 10 ) + *convetIt - 48                 val = (0 * 10 ) + '1' - 48      =>      0*10  + 49 - 48 =  0  + 1 = 1                 val = (1 * 10)  + '2' - 48      =>     1*10  + 50 - 48 = 10...