Search code examples
pythonfile-iosystemd

Systemd service for python not writing data in file


I have a python script which checks for the network status and accordingly writes data in a file. Below is the code:

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)

When I run this code, I can see that the script is writing data as online or offline in network.txt file. So I created a systemd service for this which can keep on running in background and can write data to the file. Below is the service:

[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

When I am starting the service, I can see the status as running and I can also see from the logs that Writing data to file but there is no data written into the file. Also I checked the time creation of the file using ls-lh it do not changes. This means that something is wrong in the service file which is not letting it write to file, but to me everything looks ok.

Can anyone please help me identify what is the issue here?


Solution

  • As your file path network.txt is relative, and not absolute, the file will be created from where the python script is called (current working directory, cwd). For systemd, this would be root (/). As per this answer, you may change the cwd in systemd by

    [Service]
    WorkingDirectory=/your/path/here
    

    You will find your file at /your/path/here/network.txt.

    Alternatively, use an absolute path in your python script, file_path = "/your/path/here/network.txt". Replace all occurrences of "network.txt" with file_path.

    Even better yet, make it an argument:

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

    Now, you can choose the path where the network.txt file is put when calling the script:

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