如何在Linux中用SYSTEMD运行Python脚本

2,154 阅读1分钟

SYSTEMD如何帮助我们自动运行python脚本。

再次声明:我只在基于debian的linux系统上尝试过这个方法,比如ubuntu和raspbian。
不仅是Python脚本,也包括任何你想要的东西。
1.创建一个单元文件
首先,你应该创建一个服务单元的配置文件

sudo nano /lib/systemd/system/myservice.service

2.用基本知识描述服务
这是服务描述的基本工作实例。你可以用谷歌搜索它的每一行。

  1. 直接运行python
    我认为这是最简单的运行python脚本的方法,但不建议在大多数情况下使用。
    要确定python的路径,不要忘记给出python项目的完整路径。

[Unit]
Description=My Lovely Service
After=network.target

[Service]
Type=idle
Restart=on-failure
User=root
ExecStart=/usr/bin/python /path-to-your-python-project/python_file.py

[Install]
WantedBy=multi-user.target
  1. 在文件夹中运行python
    最好是到相关的文件夹中运行python脚本。
    我们现在使用bash来运行多个脚本。

[Unit]
Description=My Lovely Service
After=network.target

[Service]
Type=idle
Restart=on-failure
User=root
ExecStart=/bin/bash -c 'cd /home/ubuntu/project/ && python app.py'

[Install]
WantedBy=multi-user.target
  1. 在python虚拟环境中运行之后,你可以根据自己的需要添加任意多的命令

[Unit]
Description=My Lovely Service
After=network.target

[Service]
Type=idle
Restart=on-failure
User=root
ExecStart=/bin/bash -c 'cd /home/ubuntu/project/ && source env/bin/activate && python app.py'

[Install]
WantedBy=multi-user.target

3.为单元文件设置权限

sudo chmod 644 /lib/systemd/system/myservice.service

你可以在链接中发挥chmod的作用。
4.配置systemd
我们需要运行daemon-reload,然后启用该服务。

sudo systemctl daemon-reload
sudo systemctl enable myservice.service

维护systemd的额外命令

# start a service
sudo systemctl start application.service
sudo systemctl start application

# stop a service
sudo systemctl stop application.service

# restart a service
sudo systemctl restart application.service

# reload a service
sudo systemctl reload application.service

# enable a service
sudo systemctl enable application.service

# disable a service
sudo systemctl disable application.service

# get the status log of a service
systemctl status application.service