ubuntu20.04使用systemd服务设置python程序开机自启动

1. 使用 systemd 服务设置开机自启动

  1. 假设已经有一个可执行的python程序,然后用一个sh脚本去启动python程序,正常情况使用挂起的方式nohup启动,日志输出到指定文件:

    sudo touch run.sh
    sudo chmod 777 run.sh

sh文件内容如下,-u可以把print的打印也输出到nohup.log文件中,使用./run.sh即可在后台运行python程序:

复制代码
#! /bin/bash
nohup /usr/bin/python3 -u test.py > nohup.log 2>&1 &
  1. 在/etc/systemd/system目录下创建一个service文件,文件内容如下

    [Unit]
    Description=My Python Program
    After=network.target

    [Service]
    Type=simple
    ExecStart=/path/to/your/sh/run.sh
    WorkingDirectory=/path/to/working/directory
    User=your_user
    Group=your_group
    Environment="PYTHONPATH=/path/to/python/lib"
    Restart=on-failure

    [Install]
    WantedBy=multi-user.target

  2. 重新加载 systemd 配置:

    sudo systemctl daemon-reload

设置开机自启服务:

复制代码
sudo systemctl enable my_program.service

立即启动服务:

复制代码
sudo systemctl start my_program.service

查看服务状态

复制代码
sudo systemctl status my_program.service
  1. 查看系统日志, -f 可以查看实时日志

    journalctl -f -u your_service_name.service

  2. 系统日志太多时,可以删除旧日志,比如清除1天之前的日志

    journalctl --vacuum-time=1d

在 Ubuntu 20 中使用 systemd 服务运行 Python 程序时,systemd 有自己的日志管理机制,不会直接生成 nohup.out 文件,而是将服务的输出重定向到系统日志中

  1. 可能遇到'permission denied'的问题,导致无法生成nohup.out文件,也可能生成空的nohup.out文件,直到程序遇到错误,才会生成out文件然后把错误日志输出

2. 建议直接在service文件中运行python程序,不使用nohup,另外配置日志输出

  1. 使用绝对路径
  2. nohup不适合开机启动:nohup主要用于在交互式shell中运行命令,使其在后台运行并忽略挂起(HUP)信号。在开机启动脚本中,你通常不需要nohup,因为这些脚本本身就是在系统启动时以非交互式方式运行的。

service文件内容如下

复制代码
[Unit]
Description=My Python Program
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 -u /path/to/your/python_program.py
WorkingDirectory=/path/to/working/directory
StandardOutput=file:/home/to/yourfile.log
StandardError=file:/home/to/yourfilerror.log
User=your_user
Group=your_group
Restart=on-failure
Environment="PYTHONPATH=/path/to/python/lib"

[Install]
WantedBy=multi-user.target

3. 停止删除服务

  1. 禁用并停止服务

    复制代码
     sudo systemctl stop your_service_name.service
     sudo systemctl disable your_service_name.service
  2. 删除服务文件(可选):

    复制代码
     sudo rm /etc/systemd/system/your_service_name.service
相关推荐
Magnum Lehar23 分钟前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Mcworld85737 分钟前
java集合
java·开发语言·windows
成功人chen某38 分钟前
配置VScodePython环境Python was not found;
开发语言·python
2301_786964361 小时前
EXCEL Python 实现绘制柱状线型组合图和树状图(包含数据透视表)
python·microsoft·excel
skd89991 小时前
小蜗牛拨号助手用户使用手册
python
「QT(C++)开发工程师」1 小时前
STM32 | FreeRTOS 递归信号量
python·stm32·嵌入式硬件
海绵宝宝贾克斯儿2 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01122 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
胡耀超2 小时前
18.自动化生成知识图谱的多维度质量评估方法论
人工智能·python·自动化·知识图谱·数据科学·逻辑学·质量评估
isyangli_blog2 小时前
(1-4)Java Object类、Final、注解、设计模式、抽象类、接口、内部类
java·开发语言