# -*- coding: utf-8 -*-
from pylint.lint import Run
from pylint.reporters.text import TextReporter
import os
import fnmatch
from collections import Counter
import re
import pandas as pd
import openpyxl
class WritableObject(object):
def __init__(self):
self.content = []
def write(self, line):
#
self.content.append(line)
def read(self):
#
return self.content
#
class CheckerPylint(object):
SCORING_VALUES = {
'E':5,
'W':4,
'R':3,
'C':2,
'I':0.1,
}
dirname = os.path.dirname(os.path.realpath('__file__'))
#
def __init__(self, path_py, file_rep_excel):
self.contetn_py = [path_py]
self.total_counter = Counter()
self.full_sintax = []
self.name_file = file_rep_excel
self.df_sintax_stra = pd.DataFrame()
#
def find_files(self, directory, pattern):
"""
Find files from pattern
"""
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
#
def run_pylint(self, filename):
"""
Run pylint for py file
"""
#args = ['-r', 'n', '--rcfile=pylintuva.pylintrc', '--disable=W0311,C0301',]
args = ['-r', 'n', '--rcfile=.pylintrc', '--disable=C0301',]
pylint_output = WritableObject()
Run([filename] + args, reporter = TextReporter(pylint_output), exit=False)
lines = []
for line in pylint_output.read():
if not line.startswith('*') and line != '\n':
lines.append(line)
return lines
#
def parse_pylint_outpyt(self, pil_output):
"""
Parse report pylint
"""
lookup_key = '-{10,}|Your code'
cyr_arr = []
for text in pil_output:
if(len(re.findall(r''+ lookup_key, str(text))) <= 0):
stripped_out = [x for x in text.split() if x != '']
if stripped_out:
cyr_arr.append(stripped_out[1])
stripped = [x[0] for x in cyr_arr]
counter = Counter(stripped)
return counter
#
def parse_pylint_rep(self, pil_output):
"""
Parse report pylint
"""
lookup_key = '-{10,}'
cyr_arr = []
for text in pil_output:
if(len(re.findall(r''+ lookup_key, str(text))) <= 0):
text = re.sub(r'^[A-Za-z]:', '..', text)
#stripped_out = [x for x in re.split(r':|: ', text)]
stripped_out = list(re.split(r':|: ', text))
if stripped_out:
cyr_arr.append(stripped_out)
return cyr_arr
def print_scoring(self):
"""
Scoring error pylint
"""
score_val = 0
statement = 0.01
print(self.total_counter)
for count, stat in enumerate(self.total_counter):
koef = self.SCORING_VALUES[stat]
statement += self.total_counter[stat]
score_val += self.total_counter[stat]*koef
print('' + str(score_val) + ' / ' + str(statement))
#evaluation=10.0 - ((float(score_val) / statement) * 10)
evaluation=10.0 - (float(score_val) / statement)
print('========Scoring :=' + str(evaluation))
def run_checker_pyfiles(self):
"""
Run py files to pylint
"""
self.full_sintax = []
self.total_counter = Counter()
for path_tx in self.contetn_py:
python_files = self.find_files(path_tx, '*.py')
for python_file in python_files:
print("=====file " + python_file)
pil_output = self.run_pylint(python_file)
#
rep_pylint = self.parse_pylint_rep(pil_output)
if(len(rep_pylint) > 0):
for curr_rep in rep_pylint:
print(curr_rep)
if(len(re.findall(r'Your code', str(curr_rep))) != 0):
print(curr_rep)
continue
self.full_sintax.append(curr_rep)
# print error
self.print_rep_error(pil_output)
# scoring my
counter = self.parse_pylint_outpyt(pil_output)
self.total_counter += counter
#
def print_rep_error(self, pil_output):
"""
Print report error
"""
lookup_key = 'E0001:|E0102:|E1120:|E0401:|E1101'
for text in pil_output:
if(len(re.findall(r''+ lookup_key, str(text))) != 0):
print(text)
#
def get_max_len(self, a_list=[]):
"""
Max len fields list
"""
max_lm = 0
for fgg in a_list:
if(max_lm < len(fgg)):
max_lm = len(fgg)
return max_lm
def export_to_excel(self):
"""
Export to excel
"""
try:
if(self.get_max_len(self.full_sintax) > 5):
self.df_sintax_stra = pd.DataFrame(self.full_sintax, columns=['file_py', 'str_err', 'pozi_err', 'code_err', 'text', 'Unkn',])
else:
self.df_sintax_stra = pd.DataFrame(self.full_sintax, columns=['file_py', 'str_err', 'pozi_err', 'code_err', 'text',])
self.df_sintax_stra.to_excel(self.name_file, index=False)
except Exception as ex:
print(ex)
Есть хорошие сервисы для анализа код, типа AppRefactoring Sourcery AI.
А AppRefactoring, помогает еще создать уникальный код.
Спасибо за информацию