You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中执行字符串语句并获取表达式返回值?

解决Python中执行字符串代码并捕获表达式返回值的问题

可以通过结合AST解析+动态编译的方式,区分传入的字符串是表达式还是语句,分别处理以获取返回值:

实现思路

  1. 先尝试将字符串按表达式模式编译,成功则直接用eval执行并返回结果;
  2. 如果编译失败(说明是语句),则用AST解析代码:
    • 若解析后是单条表达式语句(比如1+1这种直接书写的表达式),则修改AST将其转为赋值语句,把结果存入临时变量;
    • 若为普通语句(比如赋值、print调用等),直接执行即可,返回None。

代码实现

import ast

def execute_code(code_str):
    ns = {}
    # 尝试按表达式处理
    try:
        compiled_expr = compile(code_str, '<string>', 'eval')
        return eval(compiled_expr, ns)
    except SyntaxError:
        # 按单条语句解析
        tree = ast.parse(code_str, mode='single')
        # 判断是否是表达式语句
        if len(tree.body) == 1 and isinstance(tree.body[0], ast.Expr):
            # 将表达式转为赋值语句,捕获结果
            tree.body[0] = ast.Assign(
                targets=[ast.Name(id='__temp_result__', ctx=ast.Store())],
                value=tree.body[0].value
            )
            ast.fix_missing_locations(tree)
            exec(compile(tree, '<string>', 'exec'), ns)
            return ns['__temp_result__']
        else:
            # 执行普通语句,无返回值
            exec(code_str, ns)
            return None

测试示例

  • 处理表达式:
    print(execute_code('2 + 3 * 4'))  # 输出 14
    
  • 处理普通语句:
    result = execute_code('x = 100')
    print(result)  # 输出 None
    
  • 处理带输出的语句:
    result = execute_code('print("Hello World")')
    # 打印 Hello World,同时 result 为 None
    

这种方法既避免了eval无法处理语句的问题,也解决了exec无法捕获表达式返回值的痛点,同时不会像eval(compile(...,'single'))那样自动打印结果。

内容的提问来源于stack exchange,提问作者user1806566

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 07:12:31