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 53 54 55 56 57
| """
Parcourir récursivement les fichiers '.cpp', '.h' et '.hpp' du dossier courant
et afficher le nombre total de lignes lues.
Ce code fonctionne avec Python 3.6.4.
L'analyse statique du code a été validée par mypy 0.570.
"""
###########
# Imports #
###########
import os, re, traceback
from typing import Iterable, Pattern, Tuple
#################################
# Paths and regular expressions #
#################################
DIR_PATH: str = '.'
CPP_FILE_NAME_REGEX: Pattern[str] = re.compile(r'^.*\.(cpp|h|hpp)$')
#############
# Main code #
#############
def _mainImpl() -> None:
cppLineCount: int = 0
for cppFilePath in getRecursiveChildrenCppFilePaths(DIR_PATH):
cppLineCount += countLinesInFile(cppFilePath)
print('Number of lines of C++ code: ' + str(cppLineCount) + '.')
def getRecursiveChildrenCppFilePaths(dirPath: str) -> Iterable[str]:
for filePath, fileName in getRecursiveChildrenFilePathsAndNames(dirPath):
if isCppFileName(fileName):
yield filePath
def getRecursiveChildrenFilePathsAndNames(dirPath: str) -> Iterable[Tuple[str, str]]:
for dirPath2, _, fileNames in os.walk(dirPath):
for fileName in fileNames:
filePath: str = os.path.join(dirPath2, fileName)
yield (filePath, fileName)
def isCppFileName(name: str) -> bool:
return CPP_FILE_NAME_REGEX.match(name) is not None
def countLinesInFile(filePath: str) -> int:
with open(filePath) as file:
return sum(1 for line in file)
if __name__ == '__main__':
try:
_mainImpl()
except Exception as e:
print('Error: ' + str(e))
traceback.print_exc()
os.system('pause') |
Partager