本文介紹代碼統計工具控制臺界面部分。
控制臺界面就是用命令行形式執行程序。主要內容是輸入參數和結果輸出。Python有一個命令行解析模塊getopt。它能解析兩種選項格式:短格式,長格式。
短格式:"-"號后面要緊跟一個選項字母。如果還有此選項的附加參數,可以用空格分開,也可以不分開。長度任意,可以用引號。
-v [正確]
-omyfile.py [正確]
-o myfile.py [正確]
-o "myfile.py" [正確]
長格式:"--"號后面要跟一個單詞。如果還有些選項的附加參數,后面要緊跟"=",再加上參數。"="號前后不能有空格。
--output=myfile.py [正確]
-- output=myfile.py [不正確]
--output= myfile.py [不正確]
--output = myfile.py [不正確]
getopt模塊中函數介紹
opts, args=getopt(args, shortopts, longopts=[])
參數args:需要解析的全部字符串
參數shortopt:短格式選項,如'hf:',h表示-h,f:表示-f string,冒號表示后面跟有參數。
參數longopt:長格式選項,如['help', 'output='],help表示--help,output=表示output=string,等號表示選項需要賦值。
返回值opts:選項和參數對。
返回值args:沒有匹配上的選項的參數。
注:-f filename.py 中‘-f’是選項,‘filename’是參數。
如果匹配不符就會拋出異常,如格式是'hf:',則(假設程序名為program)
program -s [不適合的選項]
program -f [此選項需要跟參數]
都會拋出異常。
此程序制裁采用了短格式,它需要調用counter.py的函數。
下面是CodeCounter.py中的代碼:
# -*- coding: cp936 -*-
'''
統計文件或目錄的代碼和注釋
usage: CodeCounter [-hfdlmto] [string|n]
-h 顯示幫助信息
-f string 統計string文件
-d string 統計string目錄
-l n 統計n層子目錄,-1表示所有子目錄
-m string 要統計文件的后綴名,格式如:.c,.h,.cpp
-t string 代碼類型,c表示C/C++語言,py表示Python
-o n 輸出格式,0表示簡易輸出,1表示全部輸出
'''

import sys
import getopt
# 統計工具的工作部分,見couter.py
from counter import CodeCounter

def usage():
print __doc__

def errmsg():
print "參數不對,請參考幫助信息. \nCodeCounter -h顯示幫助信息."

def print_result(result, out):
print "全部\t代碼\t注釋\t空行\t文件名"
total = [0,0,0,0]
for ele in result:
total[0] += ele[1][4]
total[1] += ele[1][1]+ele[1][3]
total[2] += ele[1][2]+ele[1][3]
total[3] += ele[1][0]

if out == 1:
for ele in result:
print "%d\t%d\t%d\t%d\t%s" %(ele[1][4], ele[1][1]+ele[1][3],
ele[1][2]+ele[1][3], ele[1][0], ele[0])
print "%d\t%d\t%d\t%d\t總計" % (total[0], total[1], total[2], total[3])
def main(argv):
# 解析參數
try:
opts, args = getopt.getopt(argv[1:], 'hf:d:m:l:t:o:')
except getopt.GetoptError:
errmsg()
return

(counter, out, result) = (CodeCounter(), 0, [])

# 設置參數
for opt, arg in opts:
if opt in ['-h']:
usage()
return
elif opt in ['-f']:
counter.AddCodeFiles('f', arg)
elif opt in ['-d']:
counter.AddCodeFiles('d', arg)
elif opt in ['-m']:
counter.SetModes(arg)
elif opt in ['-l']:
counter.SetLevel(int(arg))
elif opt in ['-t']:
counter.SetCodeType(arg)
elif opt in ['-o']:
out = int(arg)

# 統計和輸出結果
counter.Count(result)
print_result(result, out)
if __name__ == '__main__':
try:
main(sys.argv)
except:
errmsg()
運行如下:
D:\Work\stat>CodeCounter.py -h
統計文件或目錄的代碼和注釋
usage: CodeCounter [-hfdlmto] [string|n]
-h 顯示幫助信息
-f string 統計string文件
-d string 統計string目錄
-l n 統計n層子目錄,-1表示所有子目錄
-m string 要統計文件的后綴名,格式如:.c,.h,.cpp
-t string 代碼類型,c表示C/C++語言,py表示Python
-o n 輸出格式,0表示簡易輸出,1表示全部輸出
D:\Work\stat>CodeCounter.py -d . -o 1
全部 代碼 注釋 空行 文件名
46 40 15 3 .\stat.
46 40 15 3 總計
待續