Python中使用eval执行字符串代码及语法树结构解析技术问询
Alright, let's break down both of these topics clearly for you:
eval() The eval() function lets you run Python code that's stored as a string. It's straightforward for simple expressions, like this:
# Basic arithmetic operation calc_result = eval("3 + 5 * 2") print(calc_result) # Outputs 13 # Evaluate with existing variables user_age = 22 is_adult = eval("user_age > 18") print(is_adult) # Outputs True
But a critical warning: eval() is a major security risk if you're running strings from untrusted sources. Malicious code could delete files, steal sensitive data, or cause other harm. If you only need to parse literal values (like numbers, lists, or dictionaries), use ast.literal_eval() instead—it's safer and only handles valid Python literals. Avoid eval() entirely when dealing with input you can't fully trust.
First, let's clean up the syntax tree structure you provided to make it easier to follow:
Tree(if, [ Tree(condition, [Token(VARIABLE, 'age'), Token(ACTION_OPERATOR, '>'), Token(SIGNED_NUMBER, '18')]), Tree(result, [ Tree(if, [ Tree(condition, [Token(VARIABLE, 'salary'), Token(ACTION_OPERATOR, '>'), Token(SIGNED_NUMBER, '100000')]), Tree(result, [Token(STRING, 'success')]), Tree(condition, [Token(VARIABLE, 'salary'), Token(ACTION_OPERATOR, '<'), Token(SIGNED_NUMBER, '50000')]), Tree(result, [Token(STRING, 'fail')]), Tree(else, [Token(STRING, 'get_more_info')]) ]) ]) ])
This maps directly to nested if-elif-else logic in Python:
age = 25 # Replace with your actual variable value salary = 75000 # Replace with your actual variable value if age > 18: if salary > 100000: print("success") elif salary < 50000: print("fail") else: print("get_more_info")
If you need to evaluate this tree programmatically (without manually translating it), you can write a recursive function to traverse the nodes:
def evaluate_syntax_tree(tree, variables): if tree.label == 'if': # Parse the first condition cond_node = tree.children[0] var = cond_node.children[0].value op = cond_node.children[1].value val = cond_node.children[2].value condition = f"{var} {op} {val}" # Check if the condition holds true if eval(condition, variables): # Recursively evaluate the result branch return evaluate_syntax_tree(tree.children[1], variables) else: # Handle subsequent elif conditions or else branch for i in range(2, len(tree.children), 2): child = tree.children[i] if child.label == 'condition': var = child.children[0].value op = child.children[1].value val = child.children[2].value condition = f"{var} {op} {val}" if eval(condition, variables): return evaluate_syntax_tree(tree.children[i+1], variables) elif child.label == 'else': return child.children[0].value elif tree.label == 'result': # If the result is another tree, recurse; else return the raw value child = tree.children[0] if hasattr(child, 'label'): return evaluate_syntax_tree(child, variables) else: return child.value # Example usage user_vars = {'age': 20, 'salary': 60000} # Assume your syntax tree is stored in a variable called `my_tree` # output = evaluate_syntax_tree(my_tree, user_vars) # print(output) # Would output "get_more_info"
Again, keep security in mind with eval() here. If your variables or conditions come from untrusted sources, use Python's ast module to parse expressions safely instead of relying on eval().
内容的提问来源于stack exchange,提问作者Petr Petrov

