由于此处未讨论的原因,代码行数对任何事情都不好衡量。但是有没有一种巧妙的方法来计算 Python 源代码文件中的语句?
问问题
888 次
4 回答
3
pylint 直接在其输出报告中给出:
pylint main.py
...
Report
======
145 statements analysed.
于 2012-05-04T22:34:26.173 回答
1
为了计算物理代码行(而不是本地代码行),我发现SLOCCount给出了合理的数字。
于 2012-05-04T19:52:08.307 回答
1
使用ast
从 Python 代码解析和构造语法树的模块。您将能够根据该树和节点应用您想要的自定义计数算法。
于 2012-05-04T22:10:32.570 回答
0
虽然这是一个旧帖子。这是一段代码,它以与 PyLint 相同的方式计算 python 源文件中的语句。
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)
于 2019-09-14T22:25:36.237 回答