在Ubuntu上设定Service程序自启动,自动运行Conda环境下的Python脚本

Introduce

因为个人的项目需求,需要在计算机上部署一些Python脚本以达到自动化运行部分程序的目的。系统为Ubuntu Linux 20.04 LTS 版本。使用 Conda 控制 Python 运行环境。

Chapter 1 Shell 脚本的编写

在目标目录创建一个脚本

sudo vim get_data.sh

然后向创建的文件内贴入下面的内容:
Anaconda 安装目录及 activate 脚本的具体目录位置,需要替换成你的安装路径;
之后切换到你的项目的根目录;
使用 Python 指令运行目标 Python 程序;

#!/bin/bash

# activate conda env
source /home/{
    
    username}/anaconda3/bin/activate pmrGUI

# use target path
cd /home/{
    
    username}/program/

python getarduino.py

Chapter 2 创建 Service

在目标目录创建一个 Service 文件

sudo vim auto-get.service

贴入下面的内容:

[Unit]

Description=Run get_arduino_serial service at Startup

After=network.target

[Service]

ExecStart=/home/{
    
    username}/Desktop/SysShell/get_data.sh
User=root
Group=root
Restart=always

[Install]

WantedBy=multi-user.target

After 代表要在什么服务启动后再启动此服务;
ExecStart 是要运行的脚本的路径;
其它几项都设置成 root 代表使用 root 账户运行此服务;

保存后,需要将其移动到系统服务的文件夹内。

sudo cp auto-get.service /usr/lib/systemd/system/auto-get.service

然后刷新

sudo systemctl daemon-reload

启动

sudo systemctl start auto-get.service

设置开机自启动

sudo systemctl enable auto-get.service

关闭开机自启动

sudo systemctl disable auto-get.service

查看状态

sudo systemctl status auto-get.service

猜你喜欢

转载自blog.csdn.net/qq_17790209/article/details/131651383