作为systemctl服务运行时,Python脚本未写入配置

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

我正在raspbian上运行python 3脚本,该脚本必须将字符串值写入配置文件。

->使用VS代码调试脚本(远程调试器)时,该值已正确写入config.txt。

->将脚本作为服务运行:sudo systemctl start myservice时,该值未写入config.txt。

在两种情况下,脚本都毫无例外地运行到最后。

/ home / pi / project / my-script.py

import configparser
import logging

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('main', 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

def main()
    authenticate()

if __name__ == '__main__':
    main()

/ home / pi / project / config.txt(更改为666)

[main]
sid = dummy

/ 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
  • 这里有类似问题,但没有有效答案:running python script as a systemd service
  • 通过检查日志,我可以看到该服务可以正常运行到脚本末尾(无论哪种记录方式都可以正常工作)
  • Journalctl中没有错误
  • 我已经重新启动了树莓派
  • Python版本3.5.3
python service raspbian configuration-files configparser
1个回答
0
投票

我不确定,但似乎您从未将config ['main']设置为新值。尝试configWrite(field,value):config ['main'] = {field:value},然后像bevor一样将其写入到config.txt中。

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