【发布时间】:2018-03-02 13:32:08
【问题描述】:
以下名为“tst_script.py”的 Python 脚本写入文件。它在通过命令行启动时有效,但在通过 systemd 服务启动时无法创建文件。
#!/usr/bin/python
#-*- coding: utf-8 -*-
import time
if __name__ == '__main__':
with open('test_file', 'a') as fd:
while True:
for i in range(10):
fd.write('test' + str(i) + '\r\n')
time.sleep(3)
break
名为“tst_script.service”的服务脚本如下:
[Unit]
Description=Python test script
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
ExecStart=/usr/bin/python -O /home/gilles/tst_script.py
服务脚本被复制到“/lib/systemd/system”文件夹并通过以下方式激活:
sudo systemctl daemon-reload
sudo systemctl enable tst_script.service
我们检查服务是否已安装并启用:sudo systemctl status tst_script.service
结果是:
tst_script.service - Python test script
Loaded: loaded (/lib/systemd/system/tst_script.service; enabled)
Active: inactive (dead) since ven. 2018-03-02 13:35:00 CET; 16min ago
Main PID: 10565 (code=exited, status=0/SUCCESS)
我们通过以下方式启动服务:sudo systemctl start tst_script.service
我们检查脚本是否正在运行:sudo systemctl status tst_script.service
结果是:
tst_script.service - Python test script
Loaded: loaded (/lib/systemd/system/tst_script.service; enabled)
Active: active (running) since ven. 2018-03-02 13:51:17 CET; 1s ago
Main PID: 10738 (python)
CGroup: /system.slice/tst_script.service
└─10738 /usr/bin/python -O /home/gilles/tst_script.py
30 秒后,我们检查该过程是否完成:
tst_script.service - Python test script
Loaded: loaded (/lib/systemd/system/tst_script.service; enabled)
Active: inactive (dead) since ven. 2018-03-02 13:51:47 CET; 3s ago
Process: 10738 ExecStart=/usr/bin/python -O /home/gilles/tst_script.py (code=exited, status=0/SUCCESS)
Main PID: 10738 (code=exited, status=0/SUCCESS)
但是,结果,文件“tst_file”不存在...
我用谷歌搜索,但没有找到任何解决我问题的答案。我找到的最接近的答案是running python script as a systemd service。
你有什么办法解决这个问题吗?
【问题讨论】:
-
您在哪里寻找文件
tst_file?你能在根目录/(systemd执行的命令的默认工作目录)下找到它吗? -
由系统运行的程序不应期望特定的环境。使用文件的绝对路径。不要使用 -O(但在安装包之前)。
-
@马聪:我该休息一下了。 ;-) 我没想到要在根目录中查找文件。它就在那里。感谢您的快速答复!