""" wbbit = self.openfile(self.paths[1]) wbweb = self.openfile(self.paths[0]) wsweb =…
- User
""" wb_bit = self.open_file(self.paths[1]) wb_web = self.open_file(self.paths[0])
ws_web = wb_web.active ws_bit = wb_bit.active for i in range(1, ws_bit.max_row): task = ws_bit.cell(column=2, row=i).value if task[:2] == 'ПЭ' and ws_bit.cell(column=10, row=i).value != 'Завершена': try: tags = ws_bit.cell(column=21, row=i).value.split(', ') for each in tags: each = each[5:].capitalize() if each in wb_web.sheetnames: continue else: wb_web.create_sheet(each) except: pass wb_web.create_sheet('Конфликты') wb_web.save(self.pathDone) wb_web.close() wb_bit.close() def __count_tasks_in_departments(self)->dict: """Создает словарь с названиями всех бюро и количество программ ПЭ в каждом из них return: Словарь с названиями всех бюро и количество программ ПЭ в каждом из них rtype: dict """ wb = oxl.load_workbook(self.paths[1]) sheet = wb.active amount = {} for i in range(1, sheet.max_row): task_name = sheet.cell(column=2, row=i).value first_two = task_name[:2] if (first_two == 'ПЭ'): if (sheet.cell(column=10, row=i).value != 'Завершена'): tag = sheet.cell(column=21, row=i).value try: tags = tag.split(', ') except: pass for each in tags: if (each in amount): amount[each] += 1 else: amount[each] = 1 return amount def __spread_on_sheets(self, links: dict) -> None: """Переносит информацию из веб-системы на лист соответсвующего бюро в итоговом файле :param links: словарь ключей-названий бюро :type links: dict """ wb_web = self.open_file(self.paths[0]) wb_done = self.open_file(self.pathDone) ws_web = wb_web.active first = True for i, el in enumerate(ws_web["F"]): if first: first = False continue knots = el.value.split('; ') for each in knots: if each in links.keys(): for byros in links[each]: our_row = [] for j, cell in enumerate(ws_web[i+1]): if j == 5: our_row.append(each) elif j == ws_web.max_column-1: continue else: our_row.append(cell.value) wb_done[byros[5:].capitalize()].append(our_row) else: our_row = [] for j, cell in enumerate(ws_web[i+1]): if j == 5: our_row.append(each) elif j == ws_web.max_column: continue else: our_row.append(cell.value) wb_done['Конфликты'].append(our_row) wb_done.save(self.pathDone) wb_done.close() wb_web.close() def __count_number_of_machines(self, path)->int: """Возвращает количество уникальных машин в ПЭ, взяв их из файла выгруженного из веб-системы :param path: Путь к файлу веб-системы :type path: str :rtype: int """ wb = self.open_file(path) sheet = wb.active unique_machines = []for i in range(2, sheet.max_row): if (sheet.cell(column=2, row=i).value not in unique_machines): unique_machines.append(sheet.cell(column=2, row=i).value)
wb.save(path) wb.close() return (len(unique_machines)) def __stat(self)->None: """Создает в итоговом файле лист со статистикой На этом листе выводит общее количество тракторов, которое находит через функцию __count_number_of_machines, список всех бюро с количеством проектов ПЭ в каждом из них на основе словаря, полученного из функции __count_tasks_in_departments и создает круговую диграмму распределения проектов ПЭ по бюро :rtype: None """ num_of_machines = self.__count_number_of_machines(self.paths[0]) path = self.pathDone data = self.__count_tasks_in_departments() wb = oxl.load_workbook(filename=path) wb.create_sheet('Статистика') wb.active=wb['Статистика'] sheet = wb.active """Выведение числа тракторов""" sheet.cell(column=1, row=1).value = 'Количество тракторов' sheet.cell(column=1, row=1).font = Font(name='Times New Roman', bold=True, size=12) sheet.cell(column=2, row=1).font = Font(name='Times New Roman', bold=False, size=12) sheet.column_dimensions['A'].width = 30 sheet.cell(column=2, row=1).value = num_of_machines """Таблица с числом проектов у каждого бюро""" for row_index, (key, value) in enumerate(data.items(), start=3): sheet[f'A{row_index}'] = key sheet[f'B{row_index}'] = value thin = Side(border_style="thin", color="000000") """Создание диаграммы""" chart = PieChart() labels = Reference(sheet, min_col=1, min_row=3, max_row=sheet.max_row, max_col=1) info = Reference(sheet, min_col=2, min_row=2, max_row=sheet.max_row, max_col=2) chart.add_data(info, titles_from_data=True) chart.set_categories(labels) chart.dataLabels = DataLabelList() chart.dataLabels.showVal = True chart.width = 20 chart.height = 10 chart.dataLabels = DataLabelList() chart.dataLabels.showVal = True chart.dataLabels.showCatName = True chart.dataLabels.showPercentage = False data_label_font = Font(size=14) chart.dataLabels.font = data_label_font chart.legend = None sheet.add_chart(chart, 'D5') wb.save(self.pathDone) wb.close() def open_file(self, path): """Открывает файл как work_book в openpyxl :param path: путь к файлу, который необходимо открыть :type path: str """ try: x2x = XLS2XLSX(path) wb = x2x.to_xlsx() except Exception as e: print(e) wb = oxl.load_workbook(filename=path) return wb def start(self) -> None: """ Запускает весь процесс совмещения двух файлов, перед этим выполняя проверку на ошибки при добавлении исходных файлов в итогоговом файле распределяяет информацию по листам с бюро и создает лист статистики :rtype: None """ # if self.__correct_file_B() == False: # logging.critical('Unexpected Bitrix file structure',exc_info=True) # elif self.__correct_file_W() == False: # logging.critical('Unexpected Web-sys file structure',exc_info=True) # else: self.__delete_unwanted_rows() self.__create_sheets() self.__spread_on_sheets(self.__make_link_files()) self.__stat() logging.info('Program completed successfully',exc_info=True)print(Xl_work(web_src=r"C:\Users\Aleksandr\Documents\Work\Excel\w.xlsx", bit_src=r"C:\Users\Aleksandr\Documents\Work\Excel\B.xlsx", done_src=r"C:\Users\Aleksandr\Documents\Work\Excel\Report.xlsx"))
Выводит ошибку: TypeError: time_of_function..wrapped() got an unexpected keyword argument 'web_src'
- Assistant
The error message you're encountering indicates that there is a problem with how the
Xl_workclass is being instantiated in your code, specifically regarding keyword arguments.Let's break down the error:
- The function
time_of_function.<locals>.wrapped()seems to be a decorator that is wrapping yourXl_workclass or a method within it. - When you create an instance of
Xl_work, you are passing keyword arguments (web_src,bit_src, anddone_src), but thewrapped()function (likely produced by the decorator) does not recognize these keyword arguments.
Possible Solutions
- Check the Decorator: If you're using a decorator (like one that times the function's execution), ensure that the decorator is set up to accept and forward keyword arguments to the wrapped function or class initializer.
Here’s an example adjustment for a decorator to support arguments:
def time_of_function(func): def wrapped(*args, **kwargs): # Accept any positional and keyword arguments import time start_time = time.time() result = func(*args, **kwargs) # Pass arguments to the decorated function end_time = time.time() print(f"Function {func.__name__} executed in {end_time - start_time} seconds.") return result return wrapped- Class Definition: Ensure the
Xl_workclass is defined correctly to accept the parameters. It should contain an__init__method that looks something like this:
class Xl_work: def __init__(self, web_src: str, bit_src: str, done_src: str): self.paths = [web_src, bit_src] # Example assignment self.pathDone = done_src- Instantiate Correctly: Ensure the instantiation matches how the class is defined. If
Xl_workindeed acceptsweb_src,bit_src, anddone_srcas arguments, ensure they are set up correctly in its constructor (__init__).
Additional Debugging Steps
- Print the signature of the
wrapped()function to confirm what parameters it can accept. This can help diagnose if the parameters are being handled properly. - Check if any other decorators are applied to the
Xl_workclass or its methods that could also be interfering with argument passing. - Ensure that your Python version supports the features being used, in case there are version complications.
Example Initialization
Here’s how you might typically want to initialize your
Xl_workinstance:xl_work_instance = Xl_work(web_src=r"C:\Users\Aleksandr\Documents\Work\Excel\w.xlsx", bit_src=r"C:\Users\Aleksandr\Documents\Work\Excel\B.xlsx", done_src=r"C:\Users\Aleksandr\Documents\Work\Excel\Report.xlsx")By ensuring the decorator properly handles the parameters and that the class is constructed to accept them, you should be able to resolve the
TypeError. - The function