Advertisement
Python253

ini_parser_test

May 22nd, 2024
1,204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.98 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: ini_parser_test.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script is an INI parser that allows users to parse INI-like configuration data from a string.
  10.    - It provides a menu-based interface for selecting various test scenarios.
  11.    - These include parsing basic configuration settings, application settings, database credentials, and multi-section key-value pairs.
  12.  
  13. Requirements:
  14.    - Python 3.x
  15.    - io Module
  16.  
  17. Functions:
  18.    - parse_ini(input_string):
  19.        Parses INI-like configuration data from a string and returns the section name and a dictionary of key-value pairs.
  20.    - line():
  21.        Prints a line of dashes for visual separation.
  22.    - display_menu():
  23.        Displays menu options for selecting different test scenarios.
  24.    - run_test(test_num):
  25.        Runs the selected test scenario based on the user's choice.
  26.  
  27. Usage:
  28.    - Run the script.
  29.    - Select a test scenario from the menu by entering the corresponding number.
  30.    - View the parsed results and continue to the menu to select another test or exit the script.
  31.  
  32. Additional Notes:
  33.    - Ensure that the input strings for each test scenario are correctly formatted in the input_strings list.
  34.    - The script includes verbose output during the parsing process to display the sections and key-value pairs found.
  35. """
  36.  
  37. # Get Essential Imports
  38. import io
  39.  
  40. def line():
  41.     """
  42.    Prints a line of dashes for visual separation.
  43.    """
  44.     print("-" * 40)
  45.  
  46. def parse_ini(input_string):
  47.     """
  48.    Parse INI-like configuration data from a string.
  49.  
  50.    Args:
  51.        input_string (str): The input string containing INI-like configuration data.
  52.  
  53.    Returns:
  54.        tuple: A tuple containing the section name and a dictionary of key-value pairs.
  55.    """
  56.     key_values = {}  # Dictionary to store key-value pairs
  57.     section = None  # Current section name
  58.     for line_num, line in enumerate(input_string.split("\n"), start=1):
  59.         # Strip leading and trailing whitespace from each line
  60.         line = line.strip()
  61.         if not line:
  62.             continue  # Skip empty lines
  63.  
  64.         # Check if line represents a section header
  65.         if line.startswith("[") and line.endswith("]"):
  66.             section = line[1:-1]  # Extract section name
  67.             print(f"Found section: [{section}]")
  68.         else:
  69.             try:
  70.                 key, value = line.split("=", 1)  # Split line into key and value
  71.             except ValueError:
  72.                 raise ValueError(
  73.                     f"Error parsing line {line_num}: '{line}'"
  74.                 )  # Handle invalid format
  75.             # Store key-value pair in the dictionary
  76.             key = key.strip()
  77.             value = value.strip()
  78.             print(f"Found key-value pair: '{key}' = '{value}'")
  79.             key_values[key] = value
  80.  
  81.     return section, key_values
  82.  
  83. def display_menu():
  84.     """
  85.    Display menu options.
  86.    """
  87.     line()
  88.     print("\t    INI Parser Menu:")
  89.     line()
  90.     print("1: Test 1 - Basic Configuration")
  91.     print("2: Test 2 - Application Settings")
  92.     print("3: Test 3 - Database Credentials")
  93.     print("4: Test 4 - Multi-Sect & Key-Value Pairs")
  94.     print("0: Exit")
  95.  
  96. def run_test(test_num):
  97.     """
  98.    Run the selected test.
  99.  
  100.    Args:
  101.        test_num (int): The number of the test to run.
  102.    """
  103.     input_strings = [
  104.         "[config]\n" "host = example.com\n" "port = 8080\n\n",
  105.         "[settings]\n" "enabled = true\n" "debug_level = 2\n" "timeout = 30\n\n",
  106.         "[database]\n" "username = admin\n" "password = leet1337\n\n",
  107.         "[section1]\n"
  108.         "key1 = value1\n"
  109.         "key2 = value2\n\n"
  110.         "[section2]\n"
  111.         "key3 = value3\n"
  112.         "key4 = value4\n\n",
  113.     ]
  114.     if test_num == "0":
  115.         print("\n    Program Exiting...   Goodbye!\n")
  116.         return
  117.     try:
  118.         input_string = input_strings[int(test_num) - 1]
  119.     except IndexError:
  120.         print("\nInvalid selection!\nPlease choose a number between 0 and 4.\n")
  121.         return
  122.  
  123.     print(f"\nRunning Test {test_num} - {display_titles[int(test_num) - 1]}:\n")
  124.  
  125.     # Create a file-like object from the input string
  126.     file_obj = io.StringIO(input_string)
  127.  
  128.     # Parse the input string and get section name and key-value pairs
  129.     section, key_values = parse_ini(file_obj.read())
  130.  
  131.     line()
  132.     print("\n\t  Test completed!\n")
  133.     line()
  134.     input("\nPress Enter to continue to the menu...\n")
  135.  
  136. # Main Menu
  137. display_titles = [
  138.     "Basic Configuration",
  139.     "Application Settings",
  140.     "Database Credentials",
  141.     "Multi-Sect & Key-Value Pairs",
  142. ]
  143.  
  144. while True:
  145.     display_menu()
  146.     choice = input("\nSelect a test (0-4): ")
  147.     line()
  148.     if choice == "0":
  149.         break
  150.     elif choice in {"1", "2", "3", "4"}:
  151.         run_test(choice)
  152.     else:
  153.         print("\nInvalid selection!\nPlease choose a number between 0 and 4.\n")
  154.  
  155. print("\n    Program Exiting...   Goodbye!\n")
  156. line()
  157.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement