将python程序注册为Ubuntu系统服务,并开机启动的方法

1,067次阅读
没有评论

共计 1393 个字符,预计需要花费 4 分钟才能阅读完成。

一、系统环境

  • 操作系统:ubuntu 18 以上 (该版本已默认使用 systemd 作为 init)
  • python 版本:3.8.5

二、步骤

(一) 准备 python 程序

1、在 /usr/bin/ 下新建 python 程序 svc-test.py

# nano /usr/bin/svc-test.py
#! /usr/bin/python3

import time

while True:
    f = open('/tmp/svc-test.log', 'a', encoding='utf8')
    now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    f.write(now+'\n')
    f.close()
    time.sleep(2)

2、添加执行权限

# chmod +x /usr/bin/svc-test.py

(二) 向系统注册服务

1、编写注册文件

在 /etc/systemd/system/ 下添加 svc-test.service 文件

# vi /etc/systemd/system/svc-test.service
[Unit]
Description=svc-test
After=basic.service // 启动顺序


[Service]
Type=oneshot
KillMode=control-group
WorkingDirectory=/tmp
ExecStart=/usr/bin/python3 /usr/bin/svc-test.py // 必须使用绝对路径


[Install]
Alias=svc-test.service
WantedBy=multi-user.target

2、添加执行权限

# chmod +x /etc/systemd/system/svc-test.service

3、重载系统服务

# systemctl daemon-reload

4、将服务注册为开机启动

# systemctl enable svc-test.service

三、附录 -- 一些关于 systemctl 的命令

查看所有服务的状态

# systemctl status

停止服务

# systemctl stop svc-test

手工启动服务

# systemctl start svc-test

查看单个服务的状态

# systemctl status svc-test
● svc-test.service - svc-test
   Loaded: loaded (/etc/systemd/system/svc-test.service; enabled; vendor preset: enabled)
   Active: activating (start) since Thu 2020-01-02 00:42:43 CST; 21min ago
 Main PID: 574 (python3)
    Tasks: 1 (limit: 4604)
   CGroup: /system.slice/svc-test.service
           └─574 /usr/bin/python3 /usr/bin/svc-test.py

Jan 02 00:42:43 NanoPi-M4 systemd[1]: Starting svc-test...

禁用开机启动

# systemctl disable svc-test.service
Removed /etc/systemd/system/multi-user.target.wants/svc-test.service.
打赏小哥

将 python 程序注册为 Ubuntu 系统服务,并开机启动的方法 微信打赏 将 python 程序注册为 Ubuntu 系统服务,并开机启动的方法 支付宝打赏

正文完
 0
评论(没有评论)