我有一个项目,我想计算其代码行数。是否可以用Python统计项目所在文件目录下的所有代码行数?
原文由 Daniel 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有一个项目,我想计算其代码行数。是否可以用Python统计项目所在文件目录下的所有代码行数?
原文由 Daniel 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是我编写的一个函数,用于计算 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
原文由 Bryce93 发布,翻译遵循 CC BY-SA 3.0 许可协议
2 回答5.1k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
要计算目录中文件的所有代码行数,请调用“countIn”函数,将目录作为参数传递。