【问题标题】:Python script not writing to config when run as a systemctl service作为 systemctl 服务运行时,Python 脚本未写入配置
【发布时间】:2019-12-17 11:55:15
【问题描述】:

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

-> 在 VS 代码(远程调试器)中调试时,辅助脚本正确写入 config.txt。

-> 当使用sudo systemctl start myservicesu -c 'systemctl start myservice' 作为服务运行时,辅助脚本不会写入config.txt。

在这两种情况下,程序都会毫无例外地运行到最后。

/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(修改为 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
  • 通过检查日志,我可以看到服务正常运行到脚本末尾(无论哪种方式,日志都可以正常运行)
  • journalctl 中没有错误
  • 我已经重启了树莓派
  • Python 3.5.3 版

【问题讨论】:

    标签: python service raspbian configuration-files configparser


    【解决方案1】:

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

    【讨论】:

    • 在为 stackoverflow 粘贴编辑代码时,该行丢失了。我编辑了这个问题。很抱歉
    • 然后我会尝试在 ExecStart 处添加 scipt 的绝对路径。这为我解决了问题。比如 ExecStart=/usr/bin/python3 -u /home/pi/project/my-script.py
    • 不,脚本仍然没有写入配置
    • 我猜请求导入在复制时也丢失了?您是否尝试过以 root 身份运行该服务?
    • 我编辑了问题以恢复请求导入。我还尝试了 su 命令(不幸的是,它产生了与 sudo 命令相同的结果)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2016-06-09
    • 1970-01-01
    • 2017-08-01
    • 2013-05-01
    • 1970-01-01
    • 2011-12-17
    相关资源
    最近更新 更多