centos7.8 开机自动启动python 程序的方法

您所在的位置:网站首页 aria2开机自启服务 centos7.8 开机自动启动python 程序的方法

centos7.8 开机自动启动python 程序的方法

2024-01-13 15:53| 来源: 网络整理| 查看: 265

写了一个python 的服务程序,放在服务器上,如果服务器重启动那么就要人上去重新开程序,从运维解度来说太麻烦,于是想要做一个自动启动的程序,有两种方法,启动python应用时有个小坑,一定要全路径写上python.

我的py代码叫 start_server.py 放在/opt/pic/centos_readhead_detection/release/ 大家可以根据自己情况改写

方法一:

打开/etc/rc.d/rc.local或/etc/rc.local文件,在末尾增加如下内容

注/etc/rc.local是/etc/rc.d/rc.local的软链接,有的机器可能没有,就直接编辑/etc/rc.d/rc.local即可 iptables -I INPUT -p TCP --dport 5000 -j ACCEPT nohup /root/anaconda3/bin/python /opt/pic/centos_readhead_detection/release/start_server.py >  start_server_log.txt &

保存后

在centos7中,/etc/rc.d/rc.local的权限被降低了,所以需要执行如下命令赋予其可执行权限 chmod +x /etc/rc.local

切记一定要加上python 的全路径,不然没有任何反应。

或者自己写一个.sh文件 

linux_run_server.sh iptables -I INPUT -p TCP --dport 5000 -j ACCEPT nohup /root/anaconda3/bin/python /opt/pic/centos_readhead_detection/release/start_server.py > log.txt &

赋予脚本可执行权限(/opt/pic/centos_readhead_detection/release/start_server.py 是你的脚本路径) chmod +x /opt/pic/centos_readhead_detection/release/start_server.py

打开/etc/rc.d/rc.local或/etc/rc.local文件,在末尾增加如下内容

/opt/pic/centos_readhead_detection/release/linux_run_server.sh

切记一定要加上python 的全路径,不然没有任何反应。

切记一定要加上python 的全路径,不然没有任何反应。

切记一定要加上python 的全路径,不然没有任何反应。

注:该方法

1)rc.local脚本在操作系统启动时只执行一次。

2)环境变量的问题。

在rc.local脚本中执行程序时是没有环境变量的,如果您执行的程序需要环境变量,可以在脚本中设置环境变量,比如我们需要用到gpu的库,这时如果没加环境变量就会出错,还要加入gpu库的环境变量。

export LD_LIBRARY_PATH=/usr/local/cuda-10.0/lib64:/usr/local/cuda-10.0/extras/CUPTI/lib64:$LD_LIBRARY_PATH export CUDA_HOME=/usr/local/cuda-10.0 export PATH=$CUDA_HOME/bin:$PATH nohup /root/anaconda3/bin/python /opt/image_class_install/centos_readhead_detection/release/start_server.py > /opt/image_class_install/centos_readhead_detection/release/start_server_log.txt &

方法二:

以服务启动python程序

用文本编辑器生成 centos_image_classification.servics文件

并放入/etc/systemd/system/目录下

[Unit] Description=imageclassification After=multi-user.target

[Service] StartLimitInterval=5 StartLimitBurst=10 ExecStart=/root/anaconda3/bin/python /opt/pic/centos_readhead_detection/release/start_server.py WorkingDirectory=/opt/pic/centos_readhead_detection/release/ Restart=always

[Install] WantedBy=multi-user.target 

需要注意的是,ExecStart后的python和程序所在路径必须是绝对路径

切记一定要加上python 的全路径,不然没有任何反应。

centos_image_classification.servics放到指定位置后,需要更改该文件权限,

使用命令chmod 644 centos_image_classification.servics完成。 命令行输入systemctl daemon-reload完成服务重载。 输入命令systemctl start centos_image_classification.servics和systemctl stop centos_image_classification.servics,查看程序是否正常启停。 根据实际需要,输入systemctl enable centos_image_classification.servics,将服务设为开机自启动

输入systemctl disable centos_image_classification.servics,将服务设为开机自启动

切记一定要加上python 的全路径,不然没有任何反应。

切记一定要加上python 的全路径,不然没有任何反应。

切记一定要加上python 的全路径,不然没有任何反应。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3