Python 在C文件中查找除法运算符实例
我试图在一个大的c文件中找到所有的除法运算符。 我在Python代码中看到了这一点 我试着在我的c文件中使用它。因此,我使用pycparser将我的c文件解析为ast,如下所示:Python 在C文件中查找除法运算符实例,python,abstract-syntax-tree,pycparser,Python,Abstract Syntax Tree,Pycparser,我试图在一个大的c文件中找到所有的除法运算符。 我在Python代码中看到了这一点 我试着在我的c文件中使用它。因此,我使用pycparser将我的c文件解析为ast,如下所示: from pycparser import parse_file, c_parser, c_generator def translate_to_c(filename): ast = parse_file(filename, use_cpp=True) ast.show() translate_to_
from pycparser import parse_file, c_parser, c_generator
def translate_to_c(filename):
ast = parse_file(filename, use_cpp=True)
ast.show()
translate_to_c('source.c')
def translate_to_c(filename):
ast = parse_file(filename, use_cpp=True)
ast.show()
last_lineno = None
for node in ast.walk(ast):
# Not all nodes in the AST have line numbers, remember latest one
if hasattr(node, "lineno"):
last_lineno = node.lineno
# If this is a division expression, then show the latest line number
if isinstance(node, ast.Div):
print(last_lineno)
然后我尝试使用示例,将translate_修改为_c,如下所示:
from pycparser import parse_file, c_parser, c_generator
def translate_to_c(filename):
ast = parse_file(filename, use_cpp=True)
ast.show()
translate_to_c('source.c')
def translate_to_c(filename):
ast = parse_file(filename, use_cpp=True)
ast.show()
last_lineno = None
for node in ast.walk(ast):
# Not all nodes in the AST have line numbers, remember latest one
if hasattr(node, "lineno"):
last_lineno = node.lineno
# If this is a division expression, then show the latest line number
if isinstance(node, ast.Div):
print(last_lineno)
我得到以下错误:
line 25, in translate_to_c
for node in ast.walk(ast):
AttributeError: 'FileAST' object has no attribute 'walk'
那么,关于如何在我的代码中使用它,有什么想法吗?或者通常如何在ast文件上循环?使用Python内置的
ast
库和pycparser
非常不同。一个是Python AST,另一个将C解析为C AST。它们是来自不同库的不同类型-你不能指望一个人的方法(比如walk
)能神奇地为另一个人工作
我建议您从pycparser的示例开始:
例如,在C代码中查找所有函数调用。应易于调整以找到所有除法运算符。该示例向您展示了如何使用AST。使用Python内置的
AST
库和pycparser
是非常不同的。一个是Python AST,另一个将C解析为C AST。它们是来自不同库的不同类型-你不能指望一个人的方法(比如walk
)能神奇地为另一个人工作
我建议您从pycparser的示例开始:
例如,在C代码中查找所有函数调用。应易于调整以找到所有除法运算符。该示例向您展示了如何感受AST