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

如何在非交互式Python脚本中输出最后一条语句的执行结果

实现非交互式Python脚本获取最后一条语句执行结果

要实现需求中的功能,我们可以通过**解析AST(抽象语法树)**修改用户脚本的代码逻辑,让最后一条表达式语句的执行结果被自动打印。以下是具体实现方案:

核心思路

  1. 读取用户传入的脚本文件内容
  2. 将代码解析为AST,定位最后一条语句
  3. 若最后一条语句是无赋值的表达式(对应交互式Shell中会输出结果的语句),则修改AST,添加打印该表达式结果的逻辑
  4. 编译并执行修改后的AST

实现代码(show_the_latest.py)

import ast
import sys

def adjust_ast(tree):
    if not tree.body:
        return
    last_statement = tree.body[-1]
    # 仅处理表达式语句(交互式Shell中会输出结果的类型)
    if isinstance(last_statement, ast.Expr):
        # 构建print函数调用节点,传入原表达式作为参数
        print_node = ast.Call(
            func=ast.Name(id='print', ctx=ast.Load()),
            args=[last_statement.value],
            keywords=[]
        )
        # 替换最后一条语句为print调用
        tree.body[-1] = ast.Expr(value=print_node)
        # 修复AST节点的位置信息,避免编译警告
        ast.fix_missing_locations(tree)

def main():
    if len(sys.argv) != 2:
        print("用法: python show_the_latest.py <目标脚本文件>")
        sys.exit(1)
    script_path = sys.argv[1]
    with open(script_path, 'r', encoding='utf-8') as f:
        script_content = f.read()
    # 解析生成AST
    ast_tree = ast.parse(script_content)
    # 修改AST
    adjust_ast(ast_tree)
    # 编译并执行修改后的代码
    compiled_code = compile(ast_tree, script_path, mode='exec')
    exec(compiled_code)

if __name__ == "__main__":
    main()

测试验证

假设用户脚本code.py内容如下:

x = 1
y = 2
x+y

运行命令:

python show_the_latest.py code.py

输出结果:

3

边界说明

  • 如果脚本最后一条是赋值语句(如z = x + y),交互式Shell不会输出结果,本脚本也不会产生输出,与交互行为一致
  • 脚本为空时无输出
  • 支持任意合法的Python表达式作为最后一条语句

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:42:52