像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
這個作者貌似有點懶,什么都沒有留下。