Skip to content

Instantly share code, notes, and snippets.

@phpenterprise
Last active February 8, 2021 02:04
Show Gist options
  • Save phpenterprise/101679894fc15c51c628c299df56a64a to your computer and use it in GitHub Desktop.
Save phpenterprise/101679894fc15c51c628c299df56a64a to your computer and use it in GitHub Desktop.
Configure Python as a service in AWS EC2
#!/bin/bash
#
# custom-service Start up custom-service
#
# chkconfig: 2345 55 25
# description: the custom service (Python)
#
# processname: custom-service
# Source function library
. /etc/init.d/functions
# set the python script name
SNAME=custom-service.py
# the path directory and name of the python program (warning: do not change $SNAME var)
PROG=/var/www/python/$SNAME
# start function
start() {
#check the daemon status first
if [ -f /var/lock/subsys/$SNAME ]
then
echo "$SNAME is already started!"
exit 0;
else
echo $"Starting $SNAME ..."
nohup python $PROG &
[ $? -eq 0 ] && touch /var/lock/subsys/$SNAME
echo $"$SNAME started."
exit 0;
fi
}
#stop function
stop() {
echo "Stopping $SNAME ..."
pid=`ps -ef | grep "$PROG" | grep -v 'grep' | awk '{ print $2 }' | head -1`
if [ "$pid" != "" ]; then
echo "Kill proccess " + $pid
kill $pid
rm -rf /var/lock/subsys/$SNAME
else
echo "$SNAME is stoped."
rm -rf /var/lock/subsys/$SNAME
fi
exit 0;
}
case "$1" in
start)
start
;;
stop)
stop
;;
reload|restart)
stop
start
;;
status)
pid=`ps -ef | grep "$PROG" | grep -v 'grep' | awk '{ print $2 }' | head -1`
if [ "$pid" = "" ]; then
echo "$SNAME is stoped. "
else
echo "$SNAME (pid $pid) is running..."
fi
;;
*)
echo $"\nUsage: $0 {start|stop|restart|status}"
exit 1
esac
@microgenios
Copy link

sudo chmod +x /etc/init.d/custom-service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment