1. import configparser
  2. import sys
  3. def load_config(config_file):
  4. """Loads configuration from a file, suppressing errors."""
  5. config = configparser.ConfigParser()
  6. try:
  7. config.read(config_file)
  8. except Exception as e:
  9. print(f"Error loading config file {config_file}: {e}", file=sys.stderr)
  10. return None # Or raise, depending on desired behavior
  11. return config
  12. def get_config_value(config, section, key, default=None):
  13. """Retrieves a value from the config, returning a default if not found."""
  14. try:
  15. value = config[section][key]
  16. return value
  17. except KeyError:
  18. return default
  19. def main():
  20. """Main function to demonstrate configuration loading and usage."""
  21. config_file = "config.ini" # Replace with your config file
  22. config = load_config(config_file)
  23. if config:
  24. # Example usage:
  25. db_host = get_config_value(config, "database", "host")
  26. db_port = get_config_value(config, "database", "port", 5432) #default value
  27. log_level = get_config_value(config, "logging", "level", "INFO")
  28. print(f"Database Host: {db_host}")
  29. print(f"Database Port: {db_port}")
  30. print(f"Log Level: {log_level}")
  31. if __name__ == "__main__":
  32. main()

Add your comment