小智 13
pygount 将显示文件夹中的所有文件,每个文件都有一个代码行数(不包括文档)
https://pypi.org/project/pygount/
pip install pygount
Run Code Online (Sandbox Code Playgroud)
要列出当前目录的结果,请运行:
pygount ~/path_to_directory
Run Code Online (Sandbox Code Playgroud)
小智 11
这是我编写的一个函数,用于计算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
Run Code Online (Sandbox Code Playgroud)
要使用它,只需传递您想要开始的目录.例如,要计算某个包中的代码行foo:
countlines(r'...\foo')
Run Code Online (Sandbox Code Playgroud)
哪个输出会像:
ADDED | TOTAL | FILE
-----------|-----------|--------------------
5 | 5 | .\__init__.py
539 | 578 | .\bar.py
558 | 1136 | .\baz\qux.py
Run Code Online (Sandbox Code Playgroud)
小智 7
作为pygount答案的补充,他们只是添加了--format=summary获取目录中不同文件类型的总行数的选项。
pygount --format=summary ./your-directory
Run Code Online (Sandbox Code Playgroud)
可以输出类似的东西
Language Code % Comment %
------------- ---- ------ ------- ------
XML 1668 48.56 10 0.99
Python 746 21.72 150 14.90
TeX 725 21.11 57 5.66
HTML 191 5.56 0 0.00
markdown 58 1.69 0 0.00
JSON 37 1.08 0 0.00
INI 10 0.29 0 0.00
Text 0 0.00 790 78.45
__duplicate__ 0 0.00 0 0.00
------------- ---- ------ ------- ------
Sum total 3435 1007
Run Code Online (Sandbox Code Playgroud)
这有点像家庭作业:-)——尽管如此,这是一个值得的练习,而且 Bryce93 的格式很好。我认为很多人不太可能为此使用 Python,因为它可以通过几个 shell 命令快速完成,例如:
cat $(find . -name "*.py") | grep -E -v '^\s*$|^\s*#' | wc -l
Run Code Online (Sandbox Code Playgroud)
请注意,这些解决方案都没有考虑多行 ( ''') 注释。
from os import listdir
from os.path import isfile, join
def countLinesInPath(path,directory):
count=0
for line in open(join(directory,path), encoding="utf8"):
count+=1
return count
def countLines(paths,directory):
count=0
for path in paths:
count=count+countLinesInPath(path,directory)
return count
def getPaths(directory):
return [f for f in listdir(directory) if isfile(join(directory, f))]
def countIn(directory):
return countLines(getPaths(directory),directory)
Run Code Online (Sandbox Code Playgroud)
要计算目录中文件中的所有代码行,请调用“countIn”函数,并将目录作为参数传递。
| 归档时间: |
|
| 查看次数: |
7358 次 |
| 最近记录: |