我目前正在python中使用AST。我接收一个python文件,生成它的AST,修改它,然后重新编译回源代码。我正在使用一个转换器,它将一个 getter 添加到类中(我正在使用带有 ast 的访问者模式。节点转换器)。目前我的代码按预期工作,但不保留注释,这是我的问题。下面是我的代码:
#visits nodes and generates getters or setters
def genGet(file,type,func):
global things
things['func'] = func
things['type'] = type
with open(file) as f:
code = f.read() #get the code
tree = ast.parse(code) #make the AST from the code
genTransformer().visit(tree) #lets generate getters or setters depending on type argument given in our transformer so the genTransformer function
source = meta.asttools.dump_python_source(tree) #recompile the modified ast to source code
newfile = "{}{}".format(file[:-3],"_mod.py")
print "attempting to write source code new file: {}".format(newfile) #tell everyone we will write our new source code to a file
outputfile = open(newfile,'w+')
outputfile.write(source) #write our new source code to a file
outputfile.close()
class genTransformer(ast.NodeTransformer):
...
我已经对lib2to3进行了一些研究,它显然可以保留评论,但尚未找到任何有助于解决我的问题的内容。例如,我找到了下面的代码,但并不真正理解它。它似乎保留了注释,但不允许我的修改。运行时出现属性缺失错误。
import lib2to3
from lib2to3.pgen2 import driver
from lib2to3 import pygram, pytree
import ast
def main():
filename = "%s" % ("exfunctions.py")
with open(filename) as f:
code = f.read()
drv = driver.Driver(pygram.python_grammar, pytree.convert)
tree = drv.parse_string(code, True)
# ast transfomer breaks if it is placed here
print str(tree)
return
我找不到在转换 AST 时保留评论的软件包或策略。到目前为止,我的研究对我没有帮助。我可以使用什么来修改 AST,同时保留注释?
LibCST是一个Python Concrete Syntax树解析器和工具包,可用于解决您的问题。它提供了一个看起来像ast的语法树,但保留了格式信息。它还提供用于树修改的转换器模式。
https://github.com/Instagram/LibCST/
https://libcst.readthedocs.io/en/latest/index.html
import libcst as cst
class NameTransformer(cst.CSTTransformer):
def leave_Name(self, original_node, updated_node):
return cst.Name(updated_node.value.upper())
使用这样的 NameTransformer,我们可以将源代码中的所有名称转换为大写:
>>> m = cst.parse_module("def fn(): return (value)")
>>> m.visit(NameTransformer()).code
'def FN(): return VALUE'