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

如何用Python ast库提取指定节点的原生Python数据?

提取Python代码中entry_points的原生数据

问题背景

setup.py代码片段:

extras_require={"dev": dev_reqs}
x = 3
entry_points={
    "console_scripts": ["main=smamesdemo.run.main:main"]
}

需要提取entry_points对应的原生Python字典(即{"console_scripts": ["main=smamesdemo.run.main:main"]},要求是dict和list类型,而非AST节点)。

解决方案

通过AST遍历筛选目标赋值语句,再将AST节点转换为原生数据:

import ast

def get_entry_points(file_path):
    with open(file_path, 'r') as f:
        code = f.read()
    
    tree = ast.parse(code)
    for node in ast.walk(tree):
        if isinstance(node, ast.Assign):
            # 遍历赋值目标,匹配变量名
            for target in node.targets:
                if isinstance(target, ast.Name) and target.id == 'entry_points':
                    # 将AST字面量节点转为原生Python对象
                    return ast.literal_eval(node.value)

# 调用示例
entry_points = get_entry_points('./setup.py')
print(entry_points)
print(type(entry_points))  # 输出 <class 'dict'>

关键说明

  • 使用ast.walk()遍历整个语法树,定位所有赋值语句节点
  • 通过判断赋值目标的名称,精准筛选出entry_points的赋值
  • ast.literal_eval()是安全的AST节点转原生数据方法,仅支持字面量类型(字符串、数字、列表、字典等),刚好匹配目标entry_points的结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:10:35