我使用PycParser为C函数生成一个抽象语法树,但我仍然试图弄清楚如何将解析树转换为字符串:
from pycparser import c_parser
src = '''
int hello(a, b){
return a + b;
}
'''
ast = c_parser.CParser().parse(src)
aString = ast.show()
print(aString) #This prints "None" instead of printing the parse tree
是否可以从已生成的解析树生成字符串(或字符串数组)?
这是打印的抽象语法树,但我无法弄清楚如何将其转换为字符串:
FileAST:
FuncDef:
Decl: hello, [], [], []
FuncDecl:
ParamList:
ID: a
ID: b
TypeDecl: hello, []
IdentifierType: ['int']
Compound:
Return:
BinaryOp: +
ID: a
ID: b
答案 0 :(得分:1)
show
方法接受buf
关键字参数 - 您可以在那里传递StringIO
。 sys.stdout
是默认值。见https://github.com/eliben/pycparser/blob/master/pycparser/c_ast.py#L30
答案 1 :(得分:0)
from pycparser import c_parser
src = '''
int hello(a, b){
return a + b;
}
'''
ast = c_parser.CParser().parse(src)
ast_buffer_write=open("buffer.txt","w") # here will be your AST source
ast.show(ast_buffer_write)
ast_buffer_write.close()
ast_buffer_read=open("buffer.txt","r")
astString=ast_buffer_read.read()
print(astString)