9. 自制 Python 服务实验

这节课我们将自己写的 Python 程序设置为系统服务并能够使用 systemctl 进行管理。这是一节实验课,他能让我们更深入理解服务概念和管理服务。

这节课还是使用我们写的一个 Python 程序 always_run.py,内容如下:

import os

print("PID:", os.getpid())
while True:
    pass

这个程序在程序启动时打印一下自己的 PID,然后进入无限的死循环,什么都没有做,但他会将 一个 CPU 的资源占满。当你使用 top 或 htop 命令查看 CPU 使用率情况就能看出此进程是否运行了。

将这个程序放置于用户主文件夹。我的这个程序的路径是:/home/weimingze/always_run.py

which 命令

which 命令能够帮我们打印出命令所在文件的位置,我们通过这个命令找到 python3 这个命令的路径,如下:

weimingze@mzstudio:~$ which python3
/usr/bin/python3

python3 对应的文件位于 /usr/bin/python3

创建服务单元文件

我们创建一个服务单元,服务名为 myfirstd

使用 vim 或 nano 编写文本文件 /usr/lib/systemd/system/myfirstd.service

执行命令:

weimingze@mzstudio:~$ sudo vi /usr/lib/systemd/system/myfirstd.service
[sudo] password for weimingze:

写入如下内容:

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

[Service]
Type=simple
User=root
ExecStart=/usr/bin/python3 /home/weimingze/always_run.py
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target

ExecStart=/usr/bin/python3 /home/weimingze/always_run.py 这一行内容需要根据自己的实际路径进行修改。

参数说明:

保存上述文件。

重载 systemd 配置

每次修改服务文件后,需让 systemd 重新加载配置文件的内容,使用 systemctl daemon-reload 来重新加载配置,如下所示。

weimingze@mzstudio:~$ sudo systemctl daemon-reload

启动服务

weimingze@mzstudio:~$ sudo systemctl start myfirstd
weimingze@mzstudio:~$ ps -l -C python3
F S   UID     PID    PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
4 R     0    3777       1 99  80   0 -  7246 -      ?        00:00:20 python3

使用 top 或 ps 命令 查看服务进程是否存在。

停止服务

weimingze@mzstudio:~$ sudo systemctl stop myfirstd
weimingze@mzstudio:~$ ps -l -C python3
F S   UID     PID    PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD

服务进程退出了。

设置开机自启服务

weimingze@mzstudio:~$ sudo systemctl enable myfirstd
Created symlink /etc/systemd/system/multi-user.target.wants/myfirstd.service  /usr/lib/systemd/system/myfirstd.service.

重启 Ubuntu Linux 你会发现使用 /usr/bin/python3 /home/weimingze/always_run.py 命令启动的这个进程一直存在,一个 CPU 占有率 近乎达到 100%。

取消开机自启服务

weimingze@mzstudio:~$ sudo systemctl disable myfirstd
Removed "/etc/systemd/system/multi-user.target.wants/myfirstd.service".

停止服务,重启电脑,你的电脑不在运行这个 always_run.py 程序,CPU 占有率下降了。

练习:

  1. 按以上步骤自制 myfirstd.service
  2. 启动 myfirstd.service 服务。
  3. 停止 myfirstd.service 服务。
  4. 使用 sudo systemctl enable myfirstd 来设置开机自启器。
  5. 重新启动 Linux 操作系统。
  6. 使用 sudo systemctl status 查看 myfirstd 是否在运行。
  7. 使用 sudo systemctl disable myfirstd 来取消开机自启器。
  8. 使用 sudo systemctl stop myfirstd 来停止 myfirstd 服务。