红联Linux门户
Linux帮助

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

发布时间:2017-06-22 09:40:30来源:linux网站作者:saminsysu
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脚本的用户,确保第三方库已经安装
 
参考文献:START-STOP-DAEMON: –EXEC VS –STARTAS
如何在ubuntu16.04上添加开机自启动的python脚本
 
本文永久更新地址:http://www.linuxdiyf.com/linux/31656.html