大网数据广告活动
服务器运维问答

Systemd : Run a Python Script At Startup (virtualenv)

· 52CE 我爱测

I have a python script that I normally run it with this command: (environment) python run.py I want to run this script at start. (I'm using ubuntu) Here is my service: [Unit] Description=My Script Service After=multi-user.target …

问题原文

原帖链接 · Jasmine · CC BY-SA 3.0

I have a python script that I normally run it with this command:

(environment) python run.py

I want to run this script at start. (I'm using ubuntu) Here is my service:

[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

BTW, I couldn't run this script, but I could run any script that is not inside environment. How can I run a python script at startup (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)

已采纳解答

原帖链接 · Daniel · CC BY-SA 3.0

Your unit file is correct. If you want to run any python file under an venv you just need to reference the python binary in the venv directory like you did with /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

What sticks out is the reason your unit fails: code=exited, status=200/CHDIR. This most likely indicates an issue within your script.

If you want to debug that, you would do the following:

  1. Run the command you added to ExecStart= exactly like that under root to see, if the issue is caused by your script.
  2. If that runs without errors, look at the journal with journalctl -u <unit_name>. That should give you some more information on issues with your unit.

Post Scriptum

Both of the following [Service] options work:

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

or

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

The only difference is that relative calls in your script run from different directories. So if your script contains a line open("my_file", "w"), in the first example it would create a file /my_file and the second a file /home/user/space/my_file.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-12-19)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。