Systemd:启动时运行 Python 脚本 (virtualenv)

Jas*_*ine 11 python daemon virtualenv systemd

我有一个通常使用以下命令运行的 python 脚本:

(environment) python run.py
Run Code Online (Sandbox Code Playgroud)

我想在开始时运行这个脚本。(我正在使用 ubuntu)这是我的服务:

[Unit]
Description=My Script Service
After=multi-user.target

[Service]
Type=idle

ExecStart=/home/user/anaconda3/bin/python /home/user/space/run.py

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我无法运行这个脚本,但我可以运行任何不在环境内部的脚本。如何在启动时运行 python 脚本(virtualenv)?

sudo systemctl status user_sent
? user_sent.service - Mail Service
Loaded: loaded (/lib/systemd/system/user_sent.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since xxxxx 16:30:20 MSK; 3s ago
Process: 3713 ExecStart=/usr/bin/python run.py (code=exited,   status=200/CHDIR)
Main PID: 3713 (code=exited, status=200/CHDIR)
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 14

你的单元文件是正确的。如果你想在venv下运行任何 python 文件,你只需要像你一样在venv目录中引用 python 二进制文件/home/user/anaconda3/bin/python

[Unit]
Description=My Script Service
After=multi-user.target

[Service]
Type=idle

ExecStart=/home/user/anaconda3/bin/python /home/user/space/run.py

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

突出的是你的单位失败的原因:code=exited, status=200/CHDIR。这很可能表明您的脚本中存在问题。

如果要调试,可以执行以下操作:

  1. 运行您ExecStart=在 root 下添加的命令,以查看问题是否由您的脚本引起。
  2. 如果运行没有错误,请查看带有journalctl -u <unit_name>. 这应该会为您提供有关您的设备问题的更多信息。

后脚本

以下两个[Service]选项都有效:

ExecStart=/home/user/anaconda3/bin/python /home/user/space/run.py
Run Code Online (Sandbox Code Playgroud)

或者

WorkingDirectory=/home/user/space
ExecStart=/home/user/anaconda3/bin/python run.py
Run Code Online (Sandbox Code Playgroud)

唯一的区别是脚本中的相对调用从不同的目录运行。因此,如果您的脚本包含一行open("my_file", "w"),在第一个示例中它将创建一个文件/my_file,第二个将创建一个文件/home/user/space/my_file