I'm running a python 3 program on raspbian that must write a string value to a config file. I manage to write to config within the main script, but not within the "secondary" one.
-> When debugging in VS code (remote debugger), the secondary script correctly writes to config.txt.
-> When running as a service with sudo systemctl start myservice
or su -c 'systemctl start myservice'
, the secondary script doesn't write to config.txt.
In both cases, the program runs to the end with no exception.
/home/pi/project/my-script.py
# This is the main script.
# If I move the configWrite method in this one, it writes correctly to config.
from lib import *
def main():
secondary.authenticate()
if __name__ == '__main__':
main()
/home/pi/project/lib/secondary.py
# This is the script which can't write to config.
import configparser
import logging
import requests
config = configparser.ConfigParser()
configFilePath = r'/home/pi/project/config.txt'
config.read(configFilePath)
cfg = config['main']
sid = cfg['sid']
def configWrite(field, value):
config.set('secondary', field, value)
with open(configFilePath, 'w') as configfile:
config.write(configfile)
def authenticate():
authenticate_url = '...'
headers = { ... }
try:
response = requests.post(authenticate_url, headers=headers, timeout=(30, 10))
response.raise_for_status()
except Exception as err:
logging.warning('Error occurred: {}'.format(err))
return False
else:
global sid
sid = response.json()['sid']
configWrite('sid', str(sid))
return True
/home/pi/project/config.txt (chmodded to 666)
[main]
someitem = foo
[secondary]
sid = bar
/etc/systemd/system/myservice.service
[Unit]
Description=My service description
After=network.target
[Service]
ExecStart=/usr/bin/python3 -u my-script.py
WorkingDirectory=/home/pi/project
StandardOutput=Inherit
StandardError=Inherit
Restart=always
User=pi
[Install]
WantedBy=multi-user.target
- Similar question here but with no valid answer : running python script as a systemd service
- I can see that the service runs properly to the end of the script by checking the logs (logging works just fine either way)
- No error in journalctl
- I rebooted the raspberry pi already
- Python version 3.5.3