从知道其定义的行和列的文件中获取 function/class 代码

Get a function/class code from a file knowing the line and the column of it's definition

基本上我想使用 jedi 从函数定义的详细信息(路径、行、列)中检索函数或 class' 代码。更明确地说,我真正希望的是从一个文件中获取代码,该文件未执行,是静态的。

我使用此文件 https://github.com/Erotemic/utool/blob/next/utool/util_inspect.py 中定义的函数 find_pyfunc_above_row 来完成类似的任务。

看来你可以使用astcodegen来完成这个任务。

我将 post 一个代码示例来说明这一点:

import ast,codegen

def find_by_line(root, line):
    found = None
    if hasattr(root, "lineno"):
        if root.lineno == line:
            return root
    if hasattr(root, "body"):
        for node in root.body:
            found = find_by_line(node, line)
            if found:
                break
    return found

def get_func_code(path, line):
    with open(path) as file:
        code_tree = ast.parse(file.read())
        unit = find_by_line(code_tree, line)
        return codegen.to_source(unit)

Jedi 目前不支持此功能。您当然可以做到,但不能使用 public API。 Jedi 的 API 目前缺少两件事:

  1. 按位置获取class/function(你可以通过玩jedi's Parser来获取)。
  2. 获得代码后 class。这很简单:node.get_code()

试着玩 jedi.parser.Parser。这是一个非常强大的工具,但尚未 public 完整记录。