[Lunix] 将 Python 任务设为守护进程(二)

接着上一篇文章 将 Python 任务设为守护进程(一),当python任务中包含相对路径引用时,在service文件中执行python文件会报错,为了解决这个问题,还需借助shell脚本的力量。假设项目存在/root/python路径中,且必须运行该目录下的main.py文件才能运行该项目,那么可以进行以下操作:

1. 创建shell脚本

在项目目录中创建shell脚本

vim  /root/python/start.sh

start.sh中写入

#!/bin/sh
cd  /root/python
python3 /root/python/main.py

2. 修改shell脚本权限

不修改权限时,root用户可以直接运行shell脚本,但是systemctl无法运行,所以需要执行下面这条命令:

chmod 777 /root/python/start.sh

3. 配置service文件

创建service文件

Centos:vim /usr/lib/systemd/system/python_taskd.service
Ubuntu:vim /lib/systemd/system/python_taskd.service

在service文件中写入

[Unit]
Description=start python task
After=network.target

[Service]
Type=simple
ExecStart=/root/python/start.sh
ExecReload=/root/python/start.sh
ExecStop=

[Install]
WantedBy=multi-user.target

4. 启动守护进程

systemctl daemon-reload
systemctl start python_taskd.service
systemctl restart python_taskd.service
systemctl status -l python_taskd.service
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章