LoginSignup
2
1

More than 5 years have passed since last update.

pythonスクリプトをdaemonにする[sysvinit編]

Last updated at Posted at 2018-12-04

はじめに

こちらの記事では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スクリプトを扱うことができる。

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1