之前使用screen后台运行jupyter,但是电脑重启后后台进程也会自动停止,又需要重新启动,作为程序员,本着一件事重复多次就要自动化的精神,打算写一个可以开机自启jupyter的脚本
目标:实现jupyter(或别的程序)的开机自启
步骤1:实现jupyter的状态检查、启动、停止
#!/usr/bin/bash
#-----------------------------------------------------------------
# Author: lm
# Filename: jupyter.sh
# Datetime: 2020-11-11
# Description: 有关于jupyter服务控制:启动,重启,停止,检查
#-----------------------------------------------------------------
workPath=$(cd $(dirname $0)/; pwd)
pidFile=$workPath/jupyter.pid
logFile=$workPath/jupyter.log
# 通过PID检查正在运行进程
function check_pid(){
if [ -f $pidFile ];then
pid=$(cat $pidFile)
if [ -n $pid ];then
tasks=$(ps -p $pid | grep -v "PID TTY" | wc -l)
return $tasks
fi
fi
return 0
}
# 首先检查是否正常启动,然后在判断是否启动jupyter
function start(){
check_pid
tasks=$?
if [ $tasks -gt 0 ];then
echo -n "The jupyter Service is running already, PID="
$(cat $pidFile)
return 1
fi
source /Users/limeng/opt/anaconda3/etc/profile.d/conda.sh
conda activate base
nohup jupyter notebook >> $logFile 2>&1 &
echo $! > $pidFile
echo "The Jupyter Service start to run, PID=$!"
}
# 检查是否正在运行,关闭指定PID
function stop(){
check_pid
tasks=$?
pid=$(cat $pidFile)
if [ $tasks -gt 0 ];then
kill -9 $pid
echo "Jupyter Service stoped...."
else
echo "Jupyter Service not running....."
fi
}
function restart(){
stop
sleep 2
start
}
# 输出进程PID
function status(){
check_pid
tasks=$?
if [ $tasks -gt 0 ];then
echo -n "Jupyter Service is running, PID="
cat $pidFile
echo "Please check the log for details:"$logFile
else
echo "Jupyter Service has stopped"
fi
}
function help(){
echo "$0 start|stop|restart|status"
}
case $1 in
start) start;;
stop) stop;;
restart) restart;;
status) status;;
*) help;;
esac
步骤2:检查状态并启动jupyter
#!/usr/bin/bash
#-----------------------------------------------------------------
# Author: lm
# Filename: jupyter_run.sh
# Datetime: 2020-11-11
# Description: 监测jupyter是否允许,非运行则,启动
#-----------------------------------------------------------------
stat=`sh jupyter.sh status` # 查看状态
stop_flag="stopped"
result=$(echo $stat | grep "${stop_flag}") #查看状态是否为stopped
if [[ "$result" != "" ]]
then
echo "Jupyter Service has stopped" # 若已停止则重新启动
sh jupyter.sh start
else
echo "Jupyter Service has running"
fi
步骤3:定时检查jupyter状态(失败)
crontab -e
42 * * * * cd /Users/limeng/shell;sh /Users/limeng/shell/jupyter_run.sh > /Users/limeng/shell/jupyter_run.log 2>&1
由于crontab环境和默认环境有差异,虽然可以启动jupyter,但无法读取默认路径下的文件,由于时间问题未做深入研究
姑且每次电脑重启时,手动执行 sh jupyter_run.sh即可