The python script is used as the service startup implementation method in Linux
- 2021-07-03 00:39:20
- OfStack
Script service purpose:
python is widely used in text processing. In order to obtain text data, one crawler will be run every day to crawl data. However, the server bought online will be maintained from time to time, and the server will be restarted. In this way, our crawler service can't run. At this time, we can service the python script. After the server restarts, the script will run automatically. The python script needs to be run manually after solving the server maintenance.
Implementation method:
1. Add the beginning of the written python script
#!/usr/bin/python
2. Start shell scripting
vi pystock.sh
#vim /etc/init.d/httpd
#!bin/bash
lock="py_stock.py"
# Start service method
start(){
echo "service start...."
su root -c "python /root/python/py_stock/src/crawler/py_stock.py &"
}
<pre name="code" class="plain"># Stop service method
stop(){ echo "service stop...." pkill -f $lock}
# View service status
status(){
if [ -e $lock ];then
echo "$0 service start"
else
echo "$0 service stop"
fi
}
# Restart
restart(){
stop
start
}
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
echo "$0 start|stop|status|restart"
;;
esac
3. Copy the script to the/etc/init. d/directory: cp pystock. sh/etc/init. d/
4. Give execution permission to shell script: chmod + x/etc/init. d/pystock. sh
5. Add services: chkconfig-add pystock. sh
6. Set the service to boot: chkconfig-level 35 pystock. sh on
Problems arising:
When I run the shell script to start the python script, I am prompted with 1 error
syntax error near unexpected token `$'{\r''
This is because the newline under window is\ r\ n, and the newline under linux is\ n. The shell script I wrote under window was copied to linux. When interpreting shell command,/r will be interpreted first, and an error will be reported after interpreting the script. And this\ r is invisible on Linux. Pay attention to this principle
Solution:
sed 's/\ r//' Original file > Transformed file