Skip to content

Instantly share code, notes, and snippets.

@guerbai
Last active June 2, 2019 04:04
Show Gist options
  • Save guerbai/b57b4a96a868ec12971104e1f8be1576 to your computer and use it in GitHub Desktop.
Save guerbai/b57b4a96a868ec12971104e1f8be1576 to your computer and use it in GitHub Desktop.
获取python项目有效行数
# -*- coding: utf-8 -*-
import sys
import os
import os.path as path
def get_project_row_info(project, suffix):
res = {
'all_line': 0,
'annotation': 0,
'blank': 0,
'file_num': 0,
}
def read_lines(count_file):
with open(count_file) as f:
for line in f:
res['all_line'] += 1
if line.startswith('#') or line.startswith('//'):
res['annotation'] += 1
if line.strip() == '':
res['blank'] += 1
res['file_num'] += 1
def walk_dir(cur_dir):
for content in os.listdir(cur_dir):
content = path.join(cur_dir, content)
if path.isdir(content):
walk_dir(content)
elif content.endswith(suffix):
read_lines(content)
walk_dir(project)
return res
if __name__ == '__main__':
if len(sys.argv) < 3:
print('please enter target project name and suffix like this: python total_row.py fulishe py.')
exit(1)
project = sys.argv[1]
if not path.isdir(project):
print('can not find your input project.')
exit(1)
suffix = sys.argv[2]
project_row_info = get_project_row_info(project, suffix)
print(project_row_info)
# -*- coding:utf-8 -*-
import os
import sys
#用字典结构表示,更为清晰。
codemap = {}
codemap['blank'] = 0
codemap['annotation'] = 0
codemap['all'] = 0
target_dir = sys.argv[1]
file_list = os.walk(target_dir)
def parsefile(filedir):
#可以此控制计算的文件类型,如加上'.sql'等,都很容易。
if filedir.endswith('.py'):
h = open(filedir,'r')
allLines = h.readlines()
for line in allLines:
line = line.strip()
if line == '':
codemap['blank'] += 1
elif line[0] == '#':
codemap['annotation'] += 1
codemap['all'] += len(allLines)
def main():
#这几行很重要。
for root, dirs, files in file_list:
for name in files:
#特别是这一行。
filedir = root+'/'+name
parsefile(filedir)
print codemap
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment