はじめに
こちらの記事ではsystemd
によるpythonスクリプトをdaemon化する方法を記載した。
本記事では、sysvinit
でのpythonスクリプトをデーモン化する方法を書く。
手順
- テスト用のpythonスクリプトを用意する。
/opt/hello.py
#!/usr/bin/env python3
import time
def main():
filepath = "/tmp/hello.log"
log = open(filepath,'a')
log.write("hello!\n")
if __name__ == '__main__':
while True:
main()
time.sleep(30)
- こちらを参考に、sysvinit用のスクリプトを作成する。
/etc/init.d/hello.sh
#! /bin/sh
### BEGIN INIT INFO
# Provides: Python script
# Required-Start: $local_fs $remote_fs $network $syslog
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start Python script at boot time
# Description: Start Python script at boot tim
#
### END INIT INFO
DAEMON=/opt/hello.py
NAME=hello
PIDFILE=/var/run/$NAME.pid
test -x $DAEMON || exit 0
. /lib/lsb/init-functions
case "$1" in
start)
log_daemon_msg "Starting system $DAEMON_NAME daemon"
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --exec $DAEMON --startas $DAEMON
log_end_msg $?
;;
stop)
echo -n "Stopping daemon: "$NAME
start-stop-daemon --stop --oknodo --retry 30 --pidfile $PIDFILE
;;
restart)
start-stop-daemon --stop --oknodo --retry 30 --pidfile $PIDFILE
start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON
;;
*)
echo "Usage: python-script {start|stop|restart}" >&2
exit 3
;;
esac
exit 0
- pythonスクリプトに権限を付与
$ sudo chmod 755 /opt/hello.py
-
hello.sh
の起動スクリプト用シンボリックリンクを作成する。
$ sudo update-rc.d hello.sh defaults
- reboot後、プロセスを確認する。
ps -ef | grep hello
おわりに
本記事とこちらの記事で記載したように、pythonスクリプトに#!(shebang)
を書いてやれば、シェルスクリプトを扱うのに近い感覚でpythonスクリプトを扱うことができる。