Programming/Python

파이썬으로 소스코드(.h, .cpp) 줄(line) 수 세기

blueasa 2012. 5. 11. 16:47

파이썬 배우는 기념으로 만든 소스(.h, .cpp)의 줄 수 세는 프로그램.
현재 디렉토리를 포함한 모든 하위디렉토리에 속한 소스의 줄 수를 보여준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# -*-coding:utf-8-*-
import os
 
def count_line(filename):
    file    = open(filename)
    line_num    = 0
    while (file.readline()):
        line_num    += 1
    return line_num
 
def count_code_lines(dirname):
    file_line_list  = []
    filenames   = os.listdir(dirname)
    for filename in filenames:
        filename    = dirname + '\\' + filename
        if (os.path.isdir(filename)):
            file_line_list  += count_code_lines(filename)
        else:
            if ((len(filename) > len('.h') and filename[-2:] == '.h') or
                (len(filename) > len('.cpp') and filename[-4:] == '.cpp')):
                file_line_list.append((filename, count_line(filename)))
    return file_line_list
 
def get_dir_list(path):
    dir_list    = []
    if (os.path.isdir(path)):
        dir_list.append(path)
 
    header  = os.path.split(path)[0]
    if (header == ''):
        return dir_list
    else:
        dir_list    += get_dir_list(header)
 
    return dir_list
 
file_line_list  = count_code_lines('.')
 
dir_line_dict   = {}
 
for filename, line_num in file_line_list:
    dir_list    = get_dir_list(filename)
    for dir in dir_list:
        if (not dir in dir_line_dict):
            dir_line_dict[dir]  = 0
        dir_line_dict[dir]  = dir_line_dict[dir] + line_num
 
dirnames    = dir_line_dict.keys()
dirnames.sort()
 
for dirname in dirnames:
    print "%10d %s"%(dir_line_dict[dirname], dirname)

출력예 : 뭐, 대략 이런식

8388 .
 409 .\MemoryPool
 136 .\MemoryPool\profiler
 862 .\PicTest
 687 .\SimpleMFC
 403 .\SimpleMFC2
1627 .\SimpleTest
 142 .\SimpleTest2
  59 .\UDPClient
 155 .\UDPServer
 963 .\WebViewer
 112 .\cliWrap
  19 .\cppLib
2950 .\rvo_test
 136 .\rvo_test\profiler
 472 .\rvo_test\srv_cntr
2114 .\rvo_test\sti



반응형