您好,登錄后才能下訂單哦!
小編給大家分享一下怎樣使用python腳本統(tǒng)計(jì)當(dāng)前根目錄代碼行數(shù),希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
主要思路
1、首先判斷傳入?yún)?shù)是否為文件夾
2、遍歷文件
3、調(diào)用對(duì)應(yīng)的注釋監(jiān)測(cè)正則代碼段進(jìn)行抓取
關(guān)鍵內(nèi)容
函數(shù)內(nèi)部是可以訪問(wèn)全局變量的,問(wèn)題在于函數(shù)內(nèi)部修改了變量,導(dǎo)致python認(rèn)為它是一個(gè)局部變量。如果在函數(shù)內(nèi)部訪問(wèn)并修改全局變量,應(yīng)該使用關(guān)鍵字 global 來(lái)修飾變量。
實(shí)例代碼演示
import os import re #定義規(guī)則抓取文件中的python注釋 re_obj_py = re.compile('[(#)]') #定義規(guī)則抓取文件中的C語(yǔ)言注釋 re_obj_c = re.compile('[(//)(/*)(*)(*/)]') #判斷是否為python文件 def is_py_file(filename): if os.path.splitext(filename)[1] == '.py': return True else: return False #判斷是否為c文件 def is_c_file(filename): if os.path.splitext(filename)[1] in ['.c', '.cc', '.h']: return True else: return False #定義幾個(gè)全局變量用于計(jì)算所有文件總和(全部行數(shù)、代碼行數(shù)、空行數(shù)、注釋行數(shù)) all_lines, code_lines, space_lines, comments_lines = 0, 0, 0, 0 #判斷是否為文件夾,不是則輸出提示 def count_codelines(dirpath): if not os.path.isdir(dirpath): print('input dir: %s is not legal!' % dirpath) return # 定義幾個(gè)全局變量用于計(jì)算每個(gè)文件行數(shù)(全部行數(shù)、代碼行數(shù)、空行數(shù)、注釋行數(shù)) global all_lines, code_lines, space_lines, comments_lines #列出當(dāng)前文件夾下的文件(包含目錄) all_files = os.listdir(dirpath) for file in all_files: #將文件(目錄)名與路徑拼接 file_name = os.path.join(dirpath, file) if os.path.isdir(file_name): count_codelines(file_name) else: temp_all_lines, temp_code_lines, temp_space_lines, temp_comments_lines = 0, 0, 0, 0 f = open(file_name) for line in f: temp_all_lines += 1 if line.strip() == '': temp_space_lines += 1 continue if is_py_file(file_name) and re_obj_py.match(line.strip()): temp_comments_lines += 1 if is_c_file(file_name) and re_obj_c.match(line.strip()): temp_comments_lines += 1 temp_code_lines = temp_all_lines - temp_space_lines - temp_comments_lines print('%-15s : all_lines(%s)\t code_lines(%s)\t space_lines(%s)\t comments_lines(%s)' % (file, temp_all_lines, temp_code_lines, temp_space_lines, temp_comments_lines)) all_lines += temp_all_lines code_lines += temp_code_lines space_lines += temp_space_lines comments_lines += temp_comments_lines if __name__ == '__main__': count_codelines('test') print('\n**** TOTAL COUNT ****\nall_lines = %s\ncode_lines = %s\nspace_lines = %s\ncomments_lines = %s' % (all_lines, code_lines, space_lines, comments_lines))
看完了這篇文章,相信你對(duì)怎樣使用python腳本統(tǒng)計(jì)當(dāng)前根目錄代碼行數(shù)有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。