虽然这是个老职位。 这里是一刀切的法典,用与PyLint相同的方式,用假冒的原始资料来计算这些陈述。
from astroid import MANAGER
# Tested with astroid 2.3.0.dev0
class ASTWalker:
"""
Class to walk over the Astroid nodes
"""
def __init__(self):
self.nbstatements = 0
def walk(self, astroid_node):
"""
Recurse in the astroid node children and count the statements.
"""
if astroid_node.is_statement:
self.nbstatements += 1
# recurse on children
for child in astroid_node.get_children():
self.walk(child)
walker = ASTWalker()
ast_node = MANAGER.ast_from_file("/my/file/name", source=True)
walker.walk(ast_node)
print(walker.nbstatements)