首页 > 解决方案 > python的Systemd服务没有在文件中写入数据

问题描述

我有一个 python 脚本,它检查网络状态并相应地将数据写入文件。下面是代码:

cmd = "ping -c 1 www.google.com"
res = (subprocess.call(cmd, shell=True))
if res == 0:
    if os.path.exists('network.txt') == False:
        #File is not present, create it (This will only happen for the 1st time)
        log.error("Writing data to file")
        f= open('network.txt', "w+")
        f.write("online")
        f.close()
    else:
        #File is present
        log.error("Writing data to file")
        f= open('network.txt', "w")
        f.write("online")
        f.close()
else:
    if os.path.exists('network.txt') == False:
        #File is not present, create it (This will only happen for the 1st time)
        log.error("Writing data to file")
        f= open('network.txt', "w+")
        f.write("offline")
        f.close()
    else:
        #File is present
        log.error("Writing data to file")
        f= open('network.txt', "w")
        f.write("offline")
        f.close()

time.sleep(1)

当我运行这段代码时,我可以看到脚本正在将数据写入online文件。所以我为此创建了一个服务,它可以继续在后台运行并可以将数据写入文件。下面是服务:offlinenetwork.txtsystemd

[Unit]
Description=log health of device on regular interval 

[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/pi/Documents/health.py
Restart=on-failure
RestartSec=30s
StandardOutput=null

[Install]
WantedBy=multi-user.target

当我启动服务时,我可以看到状态为正在运行,我也可以从日志中看到,Writing data to file但没有数据写入文件。我还检查了使用ls-lh它创建文件的时间不会改变。这意味着服务文件中有问题,不允许它写入文件,但在我看来一切正常。

谁能帮我确定这里的问题是什么?

标签: pythonfile-iosystemd

解决方案


由于您的文件路径network.txt是相对的,而不是绝对的,因此将从调用 python 脚本的位置(当前工作目录,cwd)创建文件。对于 systemd,这将是 root ( /)。根据这个答案,您可以通过以下方式更改 systemd 中的 cwd

[Service]
WorkingDirectory=/your/path/here

您将在 中找到您的文件/your/path/here/network.txt

或者,在您的 python 脚本中使用绝对路径,file_path = "/your/path/here/network.txt". 用 替换所有出现"network.txt"file_path

更好的是,让它成为一个论点:

import sys

if len(sys.argv) > 1:
    file_path = sys.argv[1]
else:
    file_path = "/your/default/path"

file_name = file_path + "/network.txt"

network.txt现在,您可以在调用脚本时选择放置文件的路径:

ExecStart=/usr/bin/python3 /home/pi/Documents/health.py /custom/path

推荐阅读