blaylockbk / Herbie

Download numerical weather prediction datasets (HRRR, RAP, GFS, IFS, etc.) from NOMADS, NODD partners (Amazon, Google, Microsoft), ECMWF open data, and the University of Utah Pando Archive System.
https://herbie.readthedocs.io/
MIT License
480 stars 72 forks source link

Make process Herbie loads/creates its config file more robust. #251

Closed blaylockbk closed 9 months ago

blaylockbk commented 9 months ago

The Herbie config settings are a convenience; if a user works more with GFS data rather than HRRR, they can set the default model, or default priority, etc.

One problem with the implementation is #243, caused because Herbie requires the config file. But Herbie should work even if the config file doesn't exist and/or can't be made.

I could implement something like this...(thanks ChatGPT for doing the thinking for me)

In my python package, when I import it i want to do these three things...

If a config file exists at ~/.config/herbie/config.toml, then load it

If the config file does not exist, try to create it with some default settings.

If the file can't be written (like if there are permission issues), then load some default config settings.

import os
import toml

def load_config():
    default_config = {
        'setting1': 'default_value1',
        'setting2': 'default_value2'
        # Add other default settings here
    }

    config_file_path = os.path.expanduser('~/.config/herbie/config.toml')

    try:
        if os.path.exists(config_file_path):
            # Load config file if it exists
            with open(config_file_path, 'r') as file:
                config = toml.load(file)
        else:
            # Create config file with default settings
            with open(config_file_path, 'w') as file:
                toml.dump(default_config, file)
            config = default_config
    except (FileNotFoundError, PermissionError, IOError):
        # If file can't be written or doesn't exist, use default settings
        config = default_config

    return config

# Example usage
loaded_config = load_config()
print(loaded_config)