我有一个 systemd 单元文件:
[Unit]
Description = testtesttest
After = network.target
[Service]
Type = simple
ExecStart = /usr/bin/python3.9 -u /home/pi/initialize.py
PIDFile=/home/pi/faulty.pid
User = root
Group = root
Restart = on-failure
RestartSec = 5
TimeoutStartSec = infinity
[Install]
WantedBy = multi-user.target
初始化.py:
import subprocess
# Pretend like there is some initialization here
s = subprocess.run(['su', 'pi', "-c", "python3.9 -u faulty.py"], cwd="/home/pi", text=True)
# faulty.py is located under /home/pi
错误.py:
import os, time
with open("faulty.pid", "w") as f:
f.write(str(os.getpid()))
print("AAAAAAAAAAAAAA")
time.sleep(60)
raise NameError("Boom")
我遇到的问题是,无法使用以下命令查看 failed.py 的输出systemctl状态测试或者Journalctl -u 测试。但是,我能在系统日志中找到它。我还尝试了类型分叉而不是简单,但没有帮助。另外,如果我手动执行initialize.py,faulty.py的输出将出现在终端中。
更换
s = subprocess.run(['su', 'pi', "-c", "python3.9 -u faulty.py"], cwd="/home/pi", text=True)
和
s = subprocess.run(["python3.9", "-u", "faulty.py"], cwd="/home/pi", text=True)
还产生预期的日志。
更新:
s = subprocess.run("sudo -u pi bash -c 'python3.9 -u faulty.py'", cwd='/home/pi', text=True, shell=True)
还作品并更改用户。 (所以我猜 sudo 更好)
Journalctl 日志(案例分叉):
Aug 03 12:35:42 raspberrypi systemd[1]: Starting testtesttest...
Aug 03 12:35:42 raspberrypi su[52929]: (to pi) root on none
Aug 03 12:35:42 raspberrypi su[52929]: pam_unix(su:session): session opened for user pi(uid=1000) by (uid=0)
Aug 03 12:36:43 raspberrypi systemd[1]: test.service: New main PID 52947 does not exist or is a zombie.
Aug 03 12:36:43 raspberrypi systemd[1]: test.service: Failed with result 'protocol'.
Aug 03 12:36:43 raspberrypi systemd[1]: Failed to start testtesttest.
Aug 03 12:36:48 raspberrypi systemd[1]: test.service: Scheduled restart job, restart counter is at 1.
Aug 03 12:36:48 raspberrypi systemd[1]: Stopped testtesttest.
Journalctl日志(简单情况):
Aug 03 12:42:29 raspberrypi systemd[1]: Started testtesttest.
Aug 03 12:42:29 raspberrypi su[53443]: (to pi) root on none
Aug 03 12:42:29 raspberrypi su[53443]: pam_unix(su:session): session opened for user pi(uid=1000) by (uid=0)
Aug 03 12:43:29 raspberrypi systemd[1]: test.service: Succeeded.