python - 使用 Python 计算目录中的代码行数

标签 python lines-of-code

我有一个项目,我想计算其代码行数。是否可以用Python统计项目所在文件目录下的所有代码行数?

最佳答案

这是我编写的一个函数,用于计算 python 包中的所有代码行并打印信息输出。它将计算所有 .py 中的所有行

import os

def countlines(start, lines=0, header=True, begin_start=None):
    if header:
        print('{:>10} |{:>10} | {:<20}'.format('ADDED', 'TOTAL', 'FILE'))
        print('{:->11}|{:->11}|{:->20}'.format('', '', ''))

    for thing in os.listdir(start):
        thing = os.path.join(start, thing)
        if os.path.isfile(thing):
            if thing.endswith('.py'):
                with open(thing, 'r') as f:
                    newlines = f.readlines()
                    newlines = len(newlines)
                    lines += newlines

                    if begin_start is not None:
                        reldir_of_thing = '.' + thing.replace(begin_start, '')
                    else:
                        reldir_of_thing = '.' + thing.replace(start, '')

                    print('{:>10} |{:>10} | {:<20}'.format(
                            newlines, lines, reldir_of_thing))


    for thing in os.listdir(start):
        thing = os.path.join(start, thing)
        if os.path.isdir(thing):
            lines = countlines(thing, lines, header=False, begin_start=start)

    return lines

要使用它,只需传递您想要开始的目录。例如,要计算某些包 foo 中的代码行数:

countlines(r'...\foo')

这会输出类似的东西:

     ADDED |     TOTAL | FILE               
-----------|-----------|--------------------
        5  |        5  | .\__init__.py       
       539 |       578 | .\bar.py          
       558 |      1136 | .\baz\qux.py         

关于python - 使用 Python 计算目录中的代码行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38543709/

相关文章:

python - 按列轴移动时,Pandas DataFrame.Shift 返回错误结果

python - 如何基于有效的 Python 代码在 iPhone 应用程序的 opencvWrapper 文件中创建 OpenCV 函数 findcontour

php - 好的 PHP 度量工具

ide - IntelliJ Idea 11 - 如何计算代码行数(LOC)?

notepad++ - 在多行复制和粘贴时保留相对于第一行的缩进

python - 确定 MIME 电子邮件部分是文件还是消息文本

python - 抑制 python 中的弃用

python - 比较两个表中的两个值并追加

javascript - 使用 JQuery 而不是直接使用 JavaScript 将节省多少行代码?