Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: ini_parser_test.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This script is an INI parser that allows users to parse INI-like configuration data from a string.
- - It provides a menu-based interface for selecting various test scenarios.
- - These include parsing basic configuration settings, application settings, database credentials, and multi-section key-value pairs.
- Requirements:
- - Python 3.x
- - io Module
- Functions:
- - parse_ini(input_string):
- Parses INI-like configuration data from a string and returns the section name and a dictionary of key-value pairs.
- - line():
- Prints a line of dashes for visual separation.
- - display_menu():
- Displays menu options for selecting different test scenarios.
- - run_test(test_num):
- Runs the selected test scenario based on the user's choice.
- Usage:
- - Run the script.
- - Select a test scenario from the menu by entering the corresponding number.
- - View the parsed results and continue to the menu to select another test or exit the script.
- Additional Notes:
- - Ensure that the input strings for each test scenario are correctly formatted in the input_strings list.
- - The script includes verbose output during the parsing process to display the sections and key-value pairs found.
- """
- # Get Essential Imports
- import io
- def line():
- """
- Prints a line of dashes for visual separation.
- """
- print("-" * 40)
- def parse_ini(input_string):
- """
- Parse INI-like configuration data from a string.
- Args:
- input_string (str): The input string containing INI-like configuration data.
- Returns:
- tuple: A tuple containing the section name and a dictionary of key-value pairs.
- """
- key_values = {} # Dictionary to store key-value pairs
- section = None # Current section name
- for line_num, line in enumerate(input_string.split("\n"), start=1):
- # Strip leading and trailing whitespace from each line
- line = line.strip()
- if not line:
- continue # Skip empty lines
- # Check if line represents a section header
- if line.startswith("[") and line.endswith("]"):
- section = line[1:-1] # Extract section name
- print(f"Found section: [{section}]")
- else:
- try:
- key, value = line.split("=", 1) # Split line into key and value
- except ValueError:
- raise ValueError(
- f"Error parsing line {line_num}: '{line}'"
- ) # Handle invalid format
- # Store key-value pair in the dictionary
- key = key.strip()
- value = value.strip()
- print(f"Found key-value pair: '{key}' = '{value}'")
- key_values[key] = value
- return section, key_values
- def display_menu():
- """
- Display menu options.
- """
- line()
- print("\t INI Parser Menu:")
- line()
- print("1: Test 1 - Basic Configuration")
- print("2: Test 2 - Application Settings")
- print("3: Test 3 - Database Credentials")
- print("4: Test 4 - Multi-Sect & Key-Value Pairs")
- print("0: Exit")
- def run_test(test_num):
- """
- Run the selected test.
- Args:
- test_num (int): The number of the test to run.
- """
- input_strings = [
- "[config]\n" "host = example.com\n" "port = 8080\n\n",
- "[settings]\n" "enabled = true\n" "debug_level = 2\n" "timeout = 30\n\n",
- "[database]\n" "username = admin\n" "password = leet1337\n\n",
- "[section1]\n"
- "key1 = value1\n"
- "key2 = value2\n\n"
- "[section2]\n"
- "key3 = value3\n"
- "key4 = value4\n\n",
- ]
- if test_num == "0":
- print("\n Program Exiting... Goodbye!\n")
- return
- try:
- input_string = input_strings[int(test_num) - 1]
- except IndexError:
- print("\nInvalid selection!\nPlease choose a number between 0 and 4.\n")
- return
- print(f"\nRunning Test {test_num} - {display_titles[int(test_num) - 1]}:\n")
- # Create a file-like object from the input string
- file_obj = io.StringIO(input_string)
- # Parse the input string and get section name and key-value pairs
- section, key_values = parse_ini(file_obj.read())
- line()
- print("\n\t Test completed!\n")
- line()
- input("\nPress Enter to continue to the menu...\n")
- # Main Menu
- display_titles = [
- "Basic Configuration",
- "Application Settings",
- "Database Credentials",
- "Multi-Sect & Key-Value Pairs",
- ]
- while True:
- display_menu()
- choice = input("\nSelect a test (0-4): ")
- line()
- if choice == "0":
- break
- elif choice in {"1", "2", "3", "4"}:
- run_test(choice)
- else:
- print("\nInvalid selection!\nPlease choose a number between 0 and 4.\n")
- print("\n Program Exiting... Goodbye!\n")
- line()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement