在Python中将节点添加到AST时,函数未添加到新行

马克·佛佛

在Python中,我尝试使用AST在源代码中的每个for循环之后添加一条print语句。但是问题是,print语句没有添加到新行,而是与for循环添加在同一行。添加的各种组合fix_missing_locations(),并increment_lineno()没有帮助。我究竟做错了什么?

import astor
import ast

class CodeInstrumentator(ast.NodeTransformer):
    def get_print_stmt(self, lineno):
        return ast.Call(
            func=ast.Name(id='print', ctx=ast.Load()),
            args=[ast.Num(n=lineno)],
            keywords=[]
            )

    def insert_print(self, node):
        node.body.insert(0, self.get_print_stmt(node.lineno))

    def visit_For(self, node):
        self.insert_print(node)
        self.generic_visit(node)
        return node

def main():
    input_file = 'source.py'
    try:
        myAST = astor.parsefile(input_file)
    except Exception as e:
        raise e

    CodeInstrumentator().visit(myAST)
    instru_source = astor.to_source(myAST)
    source_file = open('test.py', 'w')
    source_file.write(instru_source)

if __name__ == "__main__":
    main()
克里斯蒂安·拉蒙·科尔特斯(Cristian Ramon-Cortes)

这个问题似乎被我所面临的类似问题抛弃了,我终于找到了一个解决方案,所以我写下来,以防万一它对某人有用。

首先,通知,ASTOR不依靠也没有对lineno也没有col_offset这么使用ast.fix_missing_locations(node)increment_lineno(node, n=1)new_node = ast.copy_location(new_node, node)不会对输出代码有任何影响。

这就是说,问题在于该Call语句不是独立的操作,因此ASTOR会将其应用于前一个节点(因为它是同一操作的一部分,但是您写错了该节点的lineno)。

然后,解决方案是使用以下Call语句用void调用包装Expr语句:

def get_print_stmt(self, lineno):
    return ast.Expr(value=ast.Call(
        func=ast.Name(id='print', ctx=ast.Load()),
        args=[ast.Num(n=lineno)],
        keywords=[]
        ))

如果您编写的代码包含对函数的无效调用,则会注意到其AST表示形式已包含该Expr节点:

test_file.py

#!/usr/bin/python

# -*- coding: utf-8 -*-

#
# MAIN
#

my_func()

process_file.py

#!/usr/bin/python

# -*- coding: utf-8 -*-

from __future__ import print_function

def main():
    tree = astor.code_to_ast.parse_file("test_file.py")

    print("DUMP TREE")
    print(astor.dump_tree(tree))
    print("SOURCE")
    print(astor.to_source(tree))

#
# MAIN
#

if __name__ == '__main__':
    main()

输出值

$ python process_file.py

DUMP TREE
Module(
    body=[
        Expr(value=Call(func=Name(id='my_func'), args=[], keywords=[], starargs=None, kwargs=None))])
SOURCE
my_func()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章