import time
import datetime
import openpyxl
import sys
import os
import shutil
import copy
import tkinter.filedialog
import re
import reading_writing_txt
import search_MS_Windows
import find_and_run_file


SEARCH_LOCALION=r'\\ZUMZ-DC2\UserData\Чертежи УСПК-Екб'
LIST_OF_SEARCH_TEMPLATES=['УС','ОР','МК','ПО','ПЛ','ЦС','ЭК','ЕР','СП','ФС','ФГ','ОС']
LIST_OF_OPERATIONS=['токарн.','сверл.','фрез.','гибка','расточн','ГРР','ГРМ']
SIZE_OF_DETAILS=['отв','и','из','None','заг.','с','отв.','заг','c' ]
FILTER_WIITHOUT_DRAWING_DETAILS=['L']
DICT_OF_PATHS={'УС-0617': r'\\ZUMZ-DC2\UserData\Чертежи УСПК-Екб\УС-0617.00.000 БУ 400',
               'УС-0718': r'\\ZUMZ-DC2\UserData\Чертежи УСПК-Екб\УС-0718.00.000 Модернизация 3Д',
               'УС-1219': r'\\ZUMZ-DC2\UserData\Чертежи УСПК-Екб\УС-1219.00.000 БУ320',
               'УС-0719': r'\\ZUMZ-DC2\UserData\Чертежи УСПК-Екб\УС-0719.00.000 БУ 3Д',
               }

NUMBER_OF_WINDOWS=int(10)
COLUMN_NUMBER = 0
COPY_DIR_FILE="D:\\Temp_Excel"

def clickEnter():
    print('Для открытия '+ str(NUMBER_OF_WINDOWS) +' окон поиска')
    wait = input("Нажми Enter")

def listA_in_listB(listA:list, listB:list)->bool:
    for elementlistA in listA:
        if elementlistA in listB:
                return True
        return False

def search_name(data:str)->str:
    for list_item in data.split():
        if list_item[0:2:1]in LIST_OF_SEARCH_TEMPLATES:
            return list_item

def search_in_a_Windows(search_list:list):
    repeat_count=0
    count=0
    for j in search_list:                
        if repeat_count==NUMBER_OF_WINDOWS:
            print('Открыто '+ str(NUMBER_OF_WINDOWS) +' окон поиска')
            print('Для открытия '+ str(NUMBER_OF_WINDOWS) +' следуюших окон поиска')
            clickEnter()
            repeat_count=0                    
        search_MS_Windows.searh_query(j+'*.cdw OR '+j+'*.pdf OR '+j+'*.frw',DICT_OF_PATHS.get(j[0:7] ,SEARCH_LOCALION))
        count=count+1
        print(str(count)+'>> '+j)
        time.sleep(1)
        repeat_count=repeat_count+1
    print('Итого '+str(len(list_Excel))+' запросов окон поиска')
    clickEnter()

def no_execution(value:str)->str:
    if value[len(value)-3:len(value)-2:1] in '-' :
        return value[0:len(value)-3:1]
    elif value[len(value)-2:len(value)-1:1] in '-' :
        return value[0:len(value)-2:1]
    else:
        return value        

def call_sheet_column(sheet, COLUMN_NUMBER):
    list_Excel=[]
    if COLUMN_NUMBER==1:
        for i in range(sheet.max_row):
            val1 = str(sheet.cell(row = i+1, column = COLUMN_NUMBER).value)#Обозначение
            val12 = str(sheet.cell(row = i+1, column = 12).value)#Наименование
            val24 = str(sheet.cell(row = i+1, column = 24).value)#Габариты длинна заготовки
            val44 = str(sheet.cell(row = i+1, column = 44).value)#Операции
            if val1:
                if val1[0:2:1]in LIST_OF_SEARCH_TEMPLATES:
                    if listA_in_listB(val44.split(sep='-'), LIST_OF_OPERATIONS) or listA_in_listB(val24.split(), SIZE_OF_DETAILS) or not listA_in_listB(val24.split(), val12.split()):
                        list_Excel.append(no_execution(val1))

    elif COLUMN_NUMBER==4: 
        for i in range(sheet.max_row):
            val4 = str(sheet.cell(row = i+1, column = COLUMN_NUMBER).value)#Обозначение
            val9 = str(sheet.cell(row = i+1, column = 9).value)#Операции
            val1 = val4 + ' ' + val9
            cell = val1.split()
            if 'L' not in val1:
                if not bool(re.search(r'\d+х\d+х\d+', val1)):
                    for word in cell:
                        if word[0:2:1]in LIST_OF_SEARCH_TEMPLATES:
                            list_Excel.append(word)  
                                         
                
    elif COLUMN_NUMBER==28: 
        for i in range(sheet.max_row):
            if sheet.cell(row = i+1, column = COLUMN_NUMBER).value:
                val1 = str(sheet.cell(row = i+1, column = COLUMN_NUMBER).value)#Обозначение
                val9 = str(sheet.cell(row = i+1, column = 9).value)#Операции
                cell=val1.split()
                cell.pop(0)
                count_boot=False
                for word in cell:
                    for fill in FILTER_WIITHOUT_DRAWING_DETAILS:
                        count_boot+=fill in word
                    if not bool(count_boot):    
                        if word[0:2:1]in LIST_OF_SEARCH_TEMPLATES:
                            list_Excel.append(word)
    return list_Excel


def open_save_load_Excel():
    
    global COLUMN_NUMBER
    number_list_sheetnames=0
    root = tkinter.Tk()
    root.wm_withdraw()
    
    filename = tkinter.filedialog.askopenfilename()
    basename=os.path.basename(filename)
    shutil.copy(filename, COPY_DIR_FILE)
    copy_filename=COPY_DIR_FILE+'\\'+basename
    time.sleep(5)
    os.startfile(copy_filename)
    data = datetime.datetime.today().strftime("%Y/%m/%d %H:%M:%S")
    reading_writing_txt.event_log_txt(data, basename)
    clickEnter()
    
    with open(copy_filename) as file:
        print('Идёт загрузка...')
        if basename[0:2]=='ве':
            COLUMN_NUMBER=1
        elif basename[0:2]=='пф':
            COLUMN_NUMBER=4
            print('Выбрана документ Лист полуфабрикатов')
        elif basename[0:2]=='чс':
            COLUMN_NUMBER=5
        elif basename[0:2]=='ме':
            COLUMN_NUMBER=12
        elif basename[0:2]=='тм':
            print('Выбрана документ Технологических Маршрутов')
            COLUMN_NUMBER=28   
        else:
            print('Выбран не стандартный документ для определения запросов')
            
        print('Выбрана столбец с №' + str(COLUMN_NUMBER))
        
    wb = openpyxl.load_workbook(copy_filename, read_only=False)
    root.destroy()
    print(wb.sheetnames)
    list_sheetnames=wb.sheetnames
    print('Загрузка завершена')
    print('Место поиска: '+ SEARCH_LOCALION)


    clickEnter()
    return wb[wb.sheetnames[number_list_sheetnames]]
            
if __name__ == '__main__':
    
    count = 0
    list_names = call_sheet_column(open_save_load_Excel(), COLUMN_NUMBER)
    print(list_names)

    for path_file in find_and_run_file.multiprocessing_find_path_file(list_names):
       
        print("File path:" + str(path_file))
        if NUMBER_OF_WINDOWS >= count:
            find_and_run_file.start_file_KOMPAS(path_file)
            count += 1
        else:
            clickEnter()
            find_and_run_file.start_file_KOMPAS(path_file)
            count = 0

 Public
Share a link to this review

4.57% issue ratio

R46 Not using pathlib

Python's built-in pathlib library is nice! It's less verbose than os.path and is easier to read, for example: root = Path('root'); subdir = root / 'subfolder1' / 'subfolder2'; subdir.mkdir(exist_ok=True). Use it!

L12 Redundant code / overengineering

This code is not really needed or may be simplified

Suggested change:
NUMBER_OF_WINDOWS = 10
L12 Redundant code / overengineering

This code is not really needed or may be simplified

Suggested change:
input(f'Для открытия {NUMBER_OF_WINDOWS} окон поиска\nНажми Enter')
L50 Reinventing a wheel

Whatever you want to code, usually someone has already done that. And usually there are some tools to cover your case. And usually you can find them using Google.

Use set(listA).issubset(listB) or so.

R61 Not using f-strings

F-strings are powerful and very easy to read. Compare: 'text ' + str(number) + ' text' vs f'text {number} text'

O23 Calculated multiple times

Calculating something multiple times is redundant - use variables to store result of some calculation.

You're calculating len(value) over and over again. Calculate it once and store result in a variable, then reuse it.

R6 Copy-paste

Copy-paste lead to errors very, very often because developers forget to change value on one of copy-pasted lines . You should avoid it as much as possible. Usually a good solution is to extract the things that differ into separate variables.

L17 Using global variable

Global variables have one drawback: they are global. Which means that any snippet of code which relies on such global variables also becomes global, i.e. you can't run two copies of that code simultaneously. Also, global variables prevent you from writing clean tests where you can change input parameters and verify that your program behaves correctly - because some input parameter is a global variable.


Create new review request