作为systemd服务运行时,Python脚本不会写入文件

问题描述 投票:0回答:1

以下名为“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

你有什么想法解决这个问题吗?

python systemd
1个回答
1
投票

正如丛马在评论中提到的,最明显的问题是你可能正在寻找错误的地方。在您的代码中,输出文件为:with open('test_file', 'a'),当您测试此脚本时,它将出现在与脚本相同的文件夹中。

问题是,Python不会将file_name解释为/path/to/python/script/file_name,而是相对于当前工作目录读取相对路径。如果您从systemd开始,您当前的工作目录与脚本所在的位置不同。

您可以通过配置服务来处理这个问题,但在这种情况下更容易提供输出文件的绝对路径:

import time

if __name__ == '__main__':
    with open('/home/gilles/test_file', 'a') as fd:
        while True:
            for i in range(10):
                fd.write('test' + str(i) + '\r\n')
                time.sleep(3)
            break

如果您更喜欢使用该服务,则可以更改systemd的工作目录。此信息可能会有所帮助:Changing Working Directory of systemd service

© www.soinside.com 2019 - 2024. All rights reserved.