像Nginx、MySQL等服务一样,在后台运行自己编写的抓取天气信息的Python脚本。
1.以管理员权限新建一个服务脚本文件
sudo vim /etc/init.d/weather_service
2.用下列模板修改该服务脚本文件
#!/bin/bash
### BEGIN INIT INFO
#
# Provides: weather_service
# Required-Start: $local_fs $remote_fs
# Required-Stop: $local_fs $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: initscript
# Description: This file should be used to construct scripts to be placed in /etc/init.d.
#
### END INIT INFO
## Fill in name of program here.
PROG="weather_service.py" ##可执行文件的名字,这里是.py脚本,记得在Python文件头加上“#!/usr/bin/env python”就可以像运行可执行文件一样直接运行py脚本
PROG_PATH="/service/weather/" ##可执行文件所在的目录
PROG_ARGS="" ##程序启动的各参数
PID_PATH="/var/run/" ##PID文件保存的路径,用户判断是否服务已经启动
start() {
if [ -e "$PID_PATH/$PROG.pid" ]; then
## Program is running, exit with error.
echo "Error! $PROG is currently running!" 1>&2
exit 1
else
## Change from /dev/null to something like /var/log/$PROG if you want to save output.
$PROG_PATH/$PROG $PROG_ARGS 2>&1 >/var/log/$PROG &
pid=`ps ax | grep -i 'weather_service.py' | sed 's/^\([0-9]\{1,\}\).*/\1/g' | head -n 1` ##过滤ps命令的结果,得到weather_service的进程ID
echo "$PROG started"
echo $pid > "$PID_PATH/$PROG.pid"
fi
}
stop() {
echo "begin stop"
if [ -e "$PID_PATH/$PROG.pid" ]; then
## Program is running, so stop it
pid=`ps ax | grep -i 'weather_service.py' | sed 's/^\([0-9]\{1,\}\).*/\1/g' | head -n 1`
kill $pid
rm -f "$PID_PATH/$PROG.pid"
echo "$PROG stopped"
else
## Program is not running, exit with error.
echo "Error! $PROG not started!" 1>&2
exit 1
fi
}
## Check to see if we are running as root first.
## Found at http://www.cyberciti.biz/tips/shell-root-user-check-script.html
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
case "$1" in
start)
start
exit 0
;;
stop)
stop
exit 0
;;
reload|restart|force-reload)
stop
start
exit 0
;;
**)
echo "Usage: $0 {start|stop|reload}" 1>&2
exit 1
;;
esac
3.添加服务
sudo update-rc.d weather_service defaults
4.启动服务
sudo service weather_service start
5.停止服务
sudo service weather_service stop
6.删除服务
sudo update-rc.d -f weather_service defaults
最后编辑:2019-08-28作者:Searky
这个作者貌似有点懒,什么都没有留下。