【发布时间】:2019-12-17 11:55:15
【问题描述】:
我在 raspbian 上运行一个 python 3 程序,它必须将字符串值写入配置文件。 我设法在主脚本中写入配置,但不是在“辅助”脚本中。
-> 在 VS 代码(远程调试器)中调试时,辅助脚本正确写入 config.txt。
-> 当使用sudo systemctl start myservice 或su -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