python程序配置守护进程

参考博客

python Supervisor 使用与配置_a35155的博客-CSDN博客

1. Ubuntu系统下:apt-get install supervisor,通过这种方式安装后,自动设置为开机启动
2. 也可以通过 pip install supervisor 进行安装,但是需要手动启动,然后设置为开机启动(不推荐这种安装方式)

Supervisor 配置
Supervisor 是一个 C/S 模型的程序,supervisord 是 server 端,supervisorctl 是 client 端。

supervisord

  • /etc/supervisor/
; supervisor config file
 
[unix_http_server]
file=/var/run/supervisor.sock   ; (the path to the socket file) UNIX socket 文件,supervisorctl 会使用
chmod=0700                       ; sockef file mode (default 0700) socket 文件的 mode,默认是 0700
 
[supervisord]
logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) 日志文件,默认是 $CWD/supervisord.log
pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) pid 文件
childlogdir=/var/log/supervisor            ; ('AUTO' child log dir, default $TEMP)
 
; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
 
[supervisorctl]
serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL  for a unix socket 通过 UNIX socket 连接 supervisord,路径与 unix_http_server 部分的 file 一致
 
; 在增添需要管理的进程的配置文件时,推荐写到 `/etc/supervisor/conf.d/` 目录下,所以 `include` 项,就需要像如下配置。
; 包含其他的配置文件
[include]
files = /etc/supervisor/conf.d/*.conf ; 引入 `/etc/supervisor/conf.d/` 下的 `.conf` 文件

查看python虚拟环境

进入项目目录
pipenv shell
echo $PATH   #获取虚拟环境环境变量,写入supervisor

program 配置

program 的配置文件就写在,supervisord 配置中 include 项的路径下:/etc/supervisor/conf.d/,然后 program 的配置文件命名规则推荐:app_name.conf

root@ubuntu:/etc/supervisor/conf.d# cat python-alert.conf 
[program:python-alert] ; #程序名称,在 supervisorctl 中通过这个值来对程序进行一系列的操作
autorestart=True      ; #程序异常退出后自动重启
autostart=True        ; #在 supervisord 启动的时候也自动启动
redirect_stderr=True  ;#把 stderr 重定向到 stdout,默认 false
environment=PATH="/root/.local/share/virtualenvs/python-alert-MSbsqBd4/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"  ; #可以通过 environment 来添加需要的环境变量,一种常见的用法是使用指定的 virtualenv 环境
command=python3 /root/zhangwenqiang/python-alert/send_weixin.py ; #启动命令,与手动在命令行启动的命令是一样的
user=root           ; #用哪个用户启动
directory=/root/zhangwenqiang/python-alert/  ; #程序的启动目录
stdout_logfile_maxbytes = 20MB  ; stdout #日志文件大小,默认 50MB
stdout_logfile_backups = 20     ; stdout #日志文件备份数
; stdout #日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)
stdout_logfile = /etc/supervisor/conf.d/python-alert-stdout.log

supervisor命令

supervisorctl status
supervisorctl restart python-alert
supervisorctl update

报错

Supervisorctl error: unix:///var/run/supervisord.sock refused connection? - Stack Overflow

微信:jinmuqq222
原文地址:https://www.cnblogs.com/jinmuqq222/p/14393837.html