【问题标题】:How to prepend a line to functions in a Python file如何在 Python 文件中的函数前添加一行
【发布时间】:2018-12-26 17:35:47
【问题描述】:

我正在开发一种工具,该工具需要将内容写入 Python 文件中函数/方法的开头。我正在使用 Python 的 inspect 从文件中获取函数。鉴于这些对象,我使用inspect.getsourcelines(function_obj) 来获取函数的内容。从那里开始,我的解决方案是解析函数头,然后编写必要的内容。我的正则表达式是:

re.compile('def \w*\((\w|\s|,|=|\r|\*|\n|^\))*\):')

这感觉很脆弱,我敢肯定它缺少边缘情况。有没有更优雅/更强大的东西?这对于ast 模块来说是一个很好的用例吗

【问题讨论】:

  • 是的,这将是对 ast 模块的极好使用。
  • 好吧,太好了,我再试一次。感谢@MartijnPieters 的指导
  • @MartijnPieters 你说的非常对。比使用检查模块更容易。

标签: python abstract-syntax-tree inspect


【解决方案1】:

我不确定为什么我的答案被删除了,但是下面的两个函数是我在 Python 文件中将行语句添加到函数开头的问题的解决方案。

我使用术语“例程”来表示文件中的任何函数或方法。请注意,从 AST 节点获取文件似乎并不容易,因此我将其存储在 AST 节点中。

import ast

def get_routines_from_file(repo_file):
    '''
    Returns the methods and functions from the file
    '''
    routines = []

    with open(repo_file) as file:
        repo_file_content = file.read()
        repo_module = ast.parse(repo_file_content)
        for node in ast.walk(repo_module):
            if isinstance(node, ast.FunctionDef):
                routines.append((node, repo_file))

    return routines


def prepend_statement(self, file, node, statement):
    '''
    Writes a statement to the beginning of the routine
    '''
    first_node = node.body[0]
    first_line_in_routine = first_node.lineno

    # you unfortunately can't used first_node.col_offset because comments
    # return -1 as their col_offset.
    column_offset = node.col_offset + 4
    indentation = ' ' * column_offset
    statement = indentation + statement + '\n'

    with open(file, 'r') as f:
        contents = f.readlines()

    contents.insert(first_line_in_routine - 1, statement)

    with open(file, 'w') as f:
        f.writelines(contents)

【讨论】:

    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    相关资源
    最近更新 更多