【问题标题】:Systemd service for python not writing data in filepython的Systemd服务没有在文件中写入数据
【发布时间】:2020-06-23 05:32:14
【问题描述】:

我有一个 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 或offline 到network.txt 文件中。所以我为此创建了一个systemd 服务,它可以继续在后台运行并且可以将数据写入文件。以下是服务:

[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 检查了文件的创建时间,它不会改变。这意味着服务文件中有问题,不允许它写入文件,但在我看来一切正常。

谁能帮我找出问题所在?

【问题讨论】:

    标签: python file-io systemd


    【解决方案1】:

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

    更改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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多