如何在ubuntu16.04上添加開機自啓動的python腳本

如何在ubuntu16.04上添加開機自啓動的python腳本

  1. 複製腳本到/目錄/etc/init.d/下,並賦予腳本執行權限

    示例bash腳本如下所示

    
    #!/bin/sh
    
    
    ### BEGIN INIT INFO
    
    
    # Provides: monitor-agent
    
    
    # Short-Description: Start and stop monitor-agent
    
    
    # Description: monitor is the monitoring agent component for vinzor
    
    
    # Required-Start: $remote_fs $local_fs
    
    
    # Required-Stop: $remote_fs $local_fs
    
    
    # Default-Start: 2 3 4 5
    
    
    # Default-Stop: 0 1 6
    
    
    ### END INIT INFO
    
    
    . /lib/lsb/init-functions
    
    PATH=$PATH:/sbin # add the location of start-stop-daemon on Debian
    DAEMON="/home/sam/monitor/src/monitor_agent.py"
    DAEMON_PIDFILE="/home/sam/monitor/monitor-agent.pid"
    DAEMON_NAME="monitor-agent"
    
    case $1 in
        start)
            log_daemon_msg "Starting system $DAEMON_NAME daemon"
            start-stop-daemon -S --background -m --pidfile $DAEMON_PIDFILE --user root --startas $DAEMON
            log_end_msg $?
        ;;
        stop)
            log_daemon_msg "Stoping system $DAEMON_NAME daemon"
            start-stop-daemon -K --pidfile $DAEMON_PIDFILE
            log_end_msg $?
        ;;
        restart)
            log_daemon_msg "Restarting system $DAEMON_NAME daemon"
            $0 stop
            $0 start
            log_end_msg $?
        ;;
        *) 
            N=/etc/init.d/$NAME
            echo "Usage: $N {start|stop|restart}"
            exit 1
        ;;
    esac
    exit 0

    賦予bash腳本執行權限

    $ chmod +x ***
  2. 賦予python腳本執行權限

    $ chmod +x ***.py
  3. 將bash腳本添加到初始化執行的隊列中去

    $ update-rc.d *** defaults
  4. 重啓即可發現python腳本已在運行

    $ reboot

注意

  1. 對於python腳本,start-stop-daemon –exec不能限制python腳本只啓動一次,因而使用start-stop-daemon –startas
  2. 需要進行文件讀寫的,確保運行python腳本的用戶對文件有足夠的權限
  3. 對於運行python腳本的用戶,確保第三方庫已經安裝

參考文獻

  1. START-STOP-DAEMON: –EXEC VS –STARTAS
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章