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
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:
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)}")
var_name = var_value
). It then evaluates the value and stores it in a dictionary.def cmd_name(args): body
). It then dynamically creates these functions using exec
and stores them in a dictionary.globals().update(global_vars)
.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.