Hi there!
I' m newbie in Python applications development.
I'm coding an application that has several modules and I'm looking for the best way to access the configuration file (YAML) from each module without having to read it every time.
Can anybody help me?
Thank you in advance.
--
Adrián E. Córdoba
If its a user config, save the YAML file in
~/.config/APPNAME/config.yaml
and on Windows in
%localappdata%\APPNAME\config.yaml
.
To get the home path, use pathlib.
Example for Linux and Windows in one function:
import os
import platform
from pathlib import Path
import yaml
def load_config(appname):
system = platform.system()
if system == "Windows":
config = Path.home().joinpath(
os.environ.get("localappdata"), appname, "config.yaml"
)
elif system == "Linux":
config = Path.home().joinpath(".config", appname, "config.yaml")
else:
raise RuntimeError(f"{system} is not supported.")
with config.open() as fd:
return yaml.load(fd, yaml.SafeLoader)
config = load_config("YourAppName")
If it should belong to your module and is not a user config, just use a Python file, place it next to your modules and import it, where you need the config. Then yaml is not required. A dependency lesser is good.
(Oct-22-2024, 07:30 PM)DeaD_EyE Wrote: [ -> ]If it should belong to your module and is not a user config, just use a Python file, place it next to your modules and import it, where you need the config. Then yaml is not required. A dependency lesser is good.
Thank you very much, DeaD_EyE!