Here are the two requested items:
Create a file named config.toml with the following content:
[database]
host = "localhost"
[api_settings]
timeout_seconds = 30Create a file named read_config.py with the following Python code. This script dynamically imports tomllib (for Python 3.11+) or tomli (for older Python versions), reads config.toml, and prints the specified values.
import sys
# Dynamically import tomllib (Python 3.11+) or tomli
try:
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli
_toml_parser = tomllib if sys.version_info >= (3, 11) else tomli
except ImportError:
module_name = "tomllib" if sys.version_info >= (3, 11) else "tomli"
print(f"Error: Required module '{module_name}' not found.")
print(f"For Python versions < 3.11, install 'tomli': pip install tomli")
sys.exit(1)
CONFIG_FILE_PATH = "config.toml"
def read_and_print_config():
"""
Reads the config.toml file and prints database host and API timeout.
"""
try:
with open(CONFIG_FILE_PATH, "rb") as f:
config_data = _toml_parser.load(f)
database_host = config_data.get("database", {}).get("host")
api_timeout_seconds = config_data.get("api_settings", {}).get("timeout_seconds")
print(f"Database Host: {database_host}")
print(f"API Timeout (seconds): {api_timeout_seconds}")
except FileNotFoundError:
print(f"Error: The file '{CONFIG_FILE_PATH}' was not found. Please ensure it exists.")
except Exception as e:
print(f"An error occurred while reading the config file: {e}")
if __name__ == "__main__":
read_and_print_config()To execute the read_config.py script, use the following command in your terminal:
python read_config.py