我在raspbian上运行一个Python3程序,它必须将一个字符串值写入配置文件。 我设法在主脚本中写入config,但不在“辅助”脚本中。你知道吗
->;在VS代码(远程调试器)中调试时,辅助脚本将正确写入配置.txt. 你知道吗
->;当作为带有sudo systemctl start myservice
或su -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
我不确定,但看起来您从未将config['main']设置为新值。 尝试configWrite(field,value):config['main']={field:value},然后将其写入配置.txt就像贝弗。你知道吗
相关问题 更多 >
编程相关推荐