以使用Python编写一个脚本来统计代码行数,具体步骤如下:
安装Python的os模块和sys模块。
编写一个函数来统计指定目录下的代码行数。该函数需要遍历指定目录下的所有文件,如果是代码文件,则统计该文件中的代码行数。
在该函数中,可以使用Python的正则表达式来判断一个文件是否是代码文件。比如,可以判断文件的扩展名是否是.py、.cpp、.java等常见的代码文件扩展名。
在该函数中,可以使用Python的文件操作函数来读取文件中的内容,并统计其中的代码行数。需要注意的是,代码行数应该排除注释行和空行。
编写主函数来调用该统计函数,并输出统计结果。
示例代码:
import os
import sys
import re
def count_code_lines(dir_path):
total_lines = 0
file_count = 0
for root, dirs, files in os.walk(dir_path):
for file in files:
if re.match('.*\.(py|cpp|java)$', file):
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and not line.startswith('//'):
total_lines += 1
file_count += 1
return total_lines, file_count
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: python count_code_lines.py <directory>")
sys.exit(1)
dir_path = sys.argv[1]
if not os.path.isdir(dir_path):
print("Error: %s is not a directory" % dir_path)
sys.exit(1)
total_lines, file_count = count_code_lines(dir_path)
print("Total lines of code: %d" % total_lines)
print("Total files: %d" % file_count)
这个示例代码中,count_code_lines()函数用于统计指定目录下的代码行数。在该函数中,使用os.walk()函数遍历指定目录下的所有文件,使用正则表达式判断一个文件是否是代码文件,然后使用open()函数打开文件,读取文件中的内容,并统计其中的代码行数。最后,函数返回总的代码行数和代码文件的数量。
在主函数中,首先检查命令行参数是否正确,然后调用count_code_lines()函数,输出统计结果。
要使用该脚本,只需要在命令行中输入以下命令:
python count_code_lines.py <directory>
其中,是指定的目录路径。执行该命令后,脚本会统计指定目录下的代码行数,并输出统计结果。