Python应用安装成systemd守护进程

问题:怎么将Python脚本以systemd的方式运行?怎么把Python应用设置为自动启动?

Step 1 编写Python应用(最好以virtualenv的方式,将python和模块安装到Python应用目录中),不管以模式或者其他方式运行,只要记下可以正常运行的命令行以及相应的目录。

/data/xncd/python/xnbatchpersistence/venv/bin/python -m  app.schedule.scheduler

Step 2 生成systemd服务文件

vi /lib/systemd/system/xnbatch.service

文件内容如下:

 [Unit]
 Description=xnBatch Service
 After=multi-user.target
 [email protected]

 [Service]
 Type=simple
 WorkingDirectory=/data/xncd/python/xnbatchpersistence
 ExecStart=/data/xncd/python/xnbatchpersistence/venv/bin/python  -m  app.schedule.scheduler
 StandardInput=tty-force

 [Install]
 WantedBy=multi-user.target

Step 3 启用服务

systemctl daemon-reload
systemctl enable xnbatch
systemctl start xnbatch

Step 4 检测服务是否正常运行

systemctl status xnbatch

如果显示为activate,则表示安装成功:

systemctl status xnbatch
● xnbatch.service - xnBatch Service
   Loaded: loaded (/usr/lib/systemd/system/xnbatch.service; enabled; vendor preset: disabled)
   Active: active (running) since 二 2019-10-08 21:55:57 CST; 18min ago
 Main PID: 13755 (python)
   CGroup: /system.slice/xnbatch.service
           └─13755 /data/xncd/python/xnbatchpersistence/venv/bin/python -m app.schedule.scheduler

10月 08 21:55:57 izuf66xttbby2as7xqznx2z systemd[1]: Started xnBatch Service.

Step 4 服务控制

停止服务

systemctl stop xbatch

启动服务

systemctl start xnbatch

重启服务

systemctl restart xnbatch

你可能感兴趣的:(Python应用安装成systemd守护进程)