Python Script to Dynamically Create Global Variables and Commands

Answered using ChatGPT 4o by ChatGPT4o

Question:

Python: write a demo that read an input text of a program script and automatically create and assign global variables as well as command appeared in the input text

Answer:

Creating a Python script that reads an input text, parses it to identify global variables and commands, and then dynamically creates and assigns these variables and commands can be quite complex. However, I can provide a simplified example to demonstrate the concept.

This example will:

  1. Read an input text.
  2. Identify lines that define global variables.
  3. Identify lines that define commands (functions).
  4. Dynamically create and assign these variables and commands.

Here's a basic implementation:

import re

def execute_script(script):
    global_vars = {}
    commands = {}

    lines = script.split('\n')
    for line in lines:
        line = line.strip()
        if not line:
            continue

        # Match global variable assignment
        var_match = re.match(r'(\w+)\s*=\s*(.+)', line)
        if var_match:
            var_name, var_value = var_match.groups()
            try:
                # Evaluate the value to handle different types (int, float, str, etc.)
                global_vars[var_name] = eval(var_value)
            except Exception as e:
                print(f"Error evaluating variable {var_name}: {e}")
            continue

        # Match command definition
        cmd_match = re.match(r'def\s+(\w+)\s*\((.*?)\)\s*:\s*(.+)', line)
        if cmd_match:
            cmd_name, cmd_args, cmd_body = cmd_match.groups()
            try:
                # Create a function dynamically
                exec(f"def {cmd_name}({cmd_args}): {cmd_body}", global_vars)
                commands[cmd_name] = global_vars[cmd_name]
            except Exception as e:
                print(f"Error defining command {cmd_name}: {e}")
            continue

    # Assign global variables to the global scope
    globals().update(global_vars)

    return global_vars, commands

# Example input script
input_script = """
x = 10
y = 20
z = x + y

def add(a, b): return a + b
def multiply(a, b): return a * b
"""

global_vars, commands = execute_script(input_script)

# Test the dynamically created variables and commands
print(f"x: {x}")
print(f"y: {y}")
print(f"z: {z}")
print(f"add(3, 4): {add(3, 4)}")
print(f"multiply(3, 4): {multiply(3, 4)}")

Explanation:

  1. Reading the Script: The script is read line by line.
  2. Global Variable Assignment: The script uses a regular expression to match lines that look like variable assignments (var_name = var_value). It then evaluates the value and stores it in a dictionary.
  3. Command Definition: The script uses a regular expression to match lines that define functions (def cmd_name(args): body). It then dynamically creates these functions using exec and stores them in a dictionary.
  4. Assigning to Global Scope: The global variables are updated in the global scope using globals().update(global_vars).

Note:

  • This is a simplified example and does not handle all edge cases or complex Python syntax.
  • Using eval and exec can be dangerous if the input script is not trusted, as it can execute arbitrary code. Always validate and sanitize input if it comes from an untrusted source.

This example should give you a good starting point for creating a more robust and secure implementation tailored to your specific needs.