您的位置:首页 > 编程语言 > Python开发

如何在ubuntu16.04上添加开机自启动的python脚本

2017-06-21 16:15 711 查看

如何在ubuntu16.04上添加开机自启动的python脚本

复制脚本到/目录/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 ***


赋予python脚本执行权限

$ chmod +x ***.py


将bash脚本添加到初始化执行的队列中去

$ update-rc.d *** defaults


重启即可发现python脚本已在运行

$ reboot


注意

对于python脚本,start-stop-daemon –exec不能限制python脚本只启动一次,因而使用start-stop-daemon –startas

需要进行文件读写的,确保运行python脚本的用户对文件有足够的权限

对于运行python脚本的用户,确保第三方库已经安装

参考文献

START-STOP-DAEMON: –EXEC VS –STARTAS

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: