我目前正在使用Python中的AST。我输入一个Python文件,生成它的AST,进行修改,然后重新编译回源代码。我正在使用一个转换器将getter添加到类中(我正在使用ast.NodeTransformer的访问者模式)。目前我的代码按预期工作,但不保留注释,这是我的问题。以下是我的代码:
#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同时又保留注释?
lib2to3.pgen2.tokenize
源代码包含注释:它旨在完全匹配Python标记器的工作方式,除了它为注释生成COMMENT标记并为所有运算符提供OP类型。 - Martijn Pieterslib2to3
解析器生成自己的树(不兼容ast
模块)。它保留注释;在lib2to3.pytree
中的注释说明:这是一个非常具体的解析树;我们需要保留每个标记,甚至是标记之间的注释和空格。 - Martijn Pieters