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

2024-10-03 11:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在raspbian上运行一个Python3程序,它必须将一个字符串值写入配置文件。 我设法在主脚本中写入config,但不在“辅助”脚本中。你知道吗

->;在VS代码(远程调试器)中调试时,辅助脚本将正确写入配置.txt. 你知道吗

->;当作为带有sudo systemctl start myservicesu -c 'systemctl start myservice'的服务运行时,辅助脚本不会写入配置.txt. 你知道吗

在这两种情况下,程序无一例外地运行到最后。你知道吗

/主页/pi/项目/my-脚本.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/次要.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/项目/配置.txt(chmoded到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
  • 类似的问题,但没有有效的答案:running python script as a systemd service
  • 通过检查日志,我可以看到服务可以正常运行到脚本的末尾(无论哪种方式,日志都可以正常工作)
  • 日志中没有错误
  • 我已经重新启动了覆盆子派
  • Python版本3.5.3

Tags: thepyimporttxt脚本confighomemain