Best Python code snippet using AutoItDriverServer_python
rde.py
Source:rde.py
1# simple role diagram editor2# 14h233import pygame4import random5class Selectable:6 def __init__(self):7 self.selected = False8 9 def select(self):10 self.selected = True11 12 def unselect(self):13 self.selected = False14class Button(Selectable):15 16 def __init__(self, name, x, y, size_x, size_y, border_size):17 Selectable.__init__(self)18 self.name = name19 self.x = x20 self.y = y21 self.size_x = size_x22 self.size_y = size_y23 self.border_size = border_size24 25 def draw(self, surf):26 mx, my = pygame.mouse.get_pos()27 if self.selected:28 pygame.draw.rect(surf, (0,0,255), (self.x, self.y, self.size_x, self.size_y), self.border_size)29 elif self.collision(mx, my):30 pygame.draw.rect(surf, (0,255,0), (self.x, self.y, self.size_x, self.size_y), self.border_size)31 else:32 pygame.draw.rect(surf, (0,0,0), (self.x, self.y, self.size_x, self.size_y), self.border_size)33 34 def collision(self, x, y):35 if x >= self.x and x <= self.x+self.size_x and y >= self.y and y <= self.y+self.size_y:36 return True37 else:38 return False39class Role(Selectable):40 41 def __init__(self, name, x, y, size_x, size_y):42 Selectable.__init__(self)43 self.name = name44 self.x = x45 self.y = y46 self.size_x = size_x47 self.size_y = size_y48 self.border_size = 249 50 def collision(self, x, y):51 if x >= self.x and x <= self.x+self.size_x and y >= self.y and y <= self.y+self.size_y:52 return True53 else:54 return False55 56 def draw(self, surf):57 mx, my = pygame.mouse.get_pos()58 if self.selected:59 pygame.draw.rect(surf, (0,0,255), (self.x, self.y, self.size_x, self.size_y), self.border_size)60 elif self.collision(mx, my):61 pygame.draw.rect(surf, (0,255,0), (self.x, self.y, self.size_x, self.size_y), self.border_size)62 else:63 pygame.draw.rect(surf, (0,0,0), (self.x, self.y, self.size_x, self.size_y), self.border_size)64class Link(Selectable):65 66 def __init__(self, name, x1, y1, x2, y2):67 Selectable.__init__(self)68 self.name = name69 self.x1 = x170 self.y1 = y171 self.x2 = x272 self.y2 = y273 self.color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))74 75 def draw(self, surf):76 if self.selected:77 pygame.draw.line(surf, (0,255,0), (self.x1, self.y1), (self.x2, self.y2), 2)78 else:79 pygame.draw.line(surf, self.color, (self.x1, self.y1), (self.x2, self.y2), 2)80class Editor:81 82 def __init__(self):83 self.clock = pygame.time.Clock()84 self.fps = 6085 self.title = "Role Diagram Editor"86 self.size = (800, 600)87 self.esc = False88 89 self.build()90 91 pygame.init()92 self.screen = pygame.display.set_mode(self.size)93 pygame.display.set_caption(self.title)94 while not self.esc:95 self.update()96 self.draw()97 pygame.display.flip()98 99 def build(self):100 self.buttons = []101 self.selection = Button("Selection", 3, 100, 64, 64, 2)102 self.buttons.append(self.selection)103 self.buttons.append(Button("Role", 3, 170, 64, 64, 2))104 self.buttons.append(Button("Lien", 3, 240, 64, 64, 2))105 self.buttons.append(Button("Commentaire", 3, 310, 64, 64, 2))106 self.buttons.append(Button("Lien Commentaire", 3, 380, 64, 64, 2))107 108 self.mode = None109 self.element_selected = None110 self.ecart_mx = -1111 self.ecart_my = -1112 113 self.m_down = False114 115 self.lien_start = None116 117 self.roles = []118 self.links = []119 120 def select(self):121 mx, my = pygame.mouse.get_pos()122 self.element_selected = None123 for r in self.roles:124 if r.collision(mx, my) and self.element_selected is None:125 r.select()126 self.element_selected = r127 self.ecart_mx = mx - r.x128 self.ecart_my = my - r.y129 else:130 r.unselect()131 found_link = None132 for i in range(mx-5, mx+5):133 for j in range(my-5, my+5):134 c = self.screen.get_at((i, j))135 for l in self.links:136 if l.color == c:137 found_link = l138 break139 if found_link is not None:140 print "we've got a line! " + str(found_link)141 found_link.select()142 143 def select_button_x(self, button):144 for b in self.buttons:145 if b == button:146 b.select()147 self.mode = b.name148 else:149 b.unselect()150 151 def select_button(self):152 mx, my = pygame.mouse.get_pos()153 self.mode = None154 for b in self.buttons:155 if b.collision(mx, my):156 b.select()157 self.mode = b.name158 else:159 b.unselect()160 def update(self):161 mx, my = pygame.mouse.get_pos()162 for event in pygame.event.get():163 if event.type == pygame.QUIT:164 self.esc = True165 if event.type == pygame.VIDEORESIZE: #on peut pas agrandir sous Linux!166 print event.size, event.w, event.h167 if self.mode == 'Role':168 if event.type == pygame.MOUSEBUTTONUP:169 self.m_down = False170 if mx > 70:171 self.select()172 if self.element_selected is None:173 self.roles.append(Role('ano', mx, my, 128, 64))174 else:175 self.select_button_x(self.selection)176 elif mx <= 70:177 self.select_button()178 elif self.mode == 'Lien':179 if event.type == pygame.MOUSEBUTTONUP:180 self.m_down = False181 if mx <= 70:182 self.select_button()183 elif mx > 70:184 self.links.append(Link('ano', self.lien_start[0], self.lien_start[1], mx, my))185 self.lien_start = None186 elif event.type == pygame.MOUSEBUTTONDOWN:187 self.m_down = True188 if mx > 70:189 self.lien_start = (mx, my)190 elif self.mode == 'Selection' or self.mode is None:191 if event.type == pygame.MOUSEBUTTONDOWN:192 if mx > 70:193 self.select()194 self.m_down = True195 elif event.type == pygame.MOUSEBUTTONUP:196 self.m_down = False197 if mx <= 70:198 self.select_button()199 if self.m_down and self.element_selected is not None and mx > 70:200 self.element_selected.x = mx - self.ecart_mx201 self.element_selected.y = my - self.ecart_my202 if self.element_selected.x <= 70: self.element_selected.x = 70203 204 def update2(self):205 mx, my = pygame.mouse.get_pos()206 for event in pygame.event.get():207 if event.type == pygame.QUIT:208 self.esc = True209 elif event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:210 # ai-je clique sur quelque chose ?211 self.element_selected = None212 for r in self.roles:213 if r.collision(mx, my) and self.element_selected is None:214 r.select()215 self.element_selected = r216 self.ecart_mx = mx - r.x217 self.ecart_my = my - r.y218 else:219 r.unselect()220 if event.type == pygame.MOUSEBUTTONDOWN:221 self.m_down = True222 if mx > 70 and self.mode == 'Lien':223 self.lien_start = (mx, my)224 elif event.type == pygame.MOUSEBUTTONUP:225 self.m_down = False226 if event.button == 1:227 if mx <= 70:228 self.mode = None229 for b in self.buttons:230 if b.collision(mx, my):231 b.select()232 self.mode = b.name233 else:234 b.unselect()235 elif mx > 70:236 # action des modes237 if self.mode == 'Role':238 if self.element_selected is None:239 self.roles.append(Role('ano', mx, my, 128, 64))240 elif self.mode == 'Lien':241 self.links.append(Link('ano', self.lien_start[0], self.lien_start[1], mx, my))242 elif self.mode == 'Commentaire':243 print 'C'244 elif self.mode == 'Lien Commentaire':245 print 'D'246 if self.m_down:247 if mx > 70:248 if self.element_selected is not None:249 self.element_selected.x = mx - self.ecart_mx250 self.element_selected.y = my - self.ecart_my251 elif self.lien_start is not None:252 pass 253 254 def draw(self):255 self.screen.fill((255,255,255))256 # menu left257 pygame.draw.rect(self.screen, (200,200,200), (0, 0, 70, 600), 0)258 # icons259 for b in self.buttons:260 b.draw(self.screen)261 for r in self.roles:262 r.draw(self.screen)263 if pygame.mouse.get_pos()[0] > 70 and self.m_down and self.lien_start is not None and self.mode == 'Lien':264 pygame.draw.line(self.screen, (0,0,0), self.lien_start, pygame.mouse.get_pos(), 2)265 for l in self.links:266 l.draw(self.screen)...
display_imaging_resonance_sample_definition.py
Source:display_imaging_resonance_sample_definition.py
1import numpy as np2import os3import numbers4try:5 from PyQt4.QtGui import QFileDialog6 from PyQt4 import QtCore, QtGui7 from PyQt4.QtGui import QMainWindow8except ImportError:9 from PyQt5.QtWidgets import QFileDialog10 from PyQt5 import QtCore, QtGui11 from PyQt5.QtWidgets import QApplication, QMainWindow12from __code.ui_resonance_imaging_layers_input import Ui_MainWindow as UiSampleMainWindow13from ImagingReso.resonance import Resonance14class SampleWindow(QMainWindow):15 16 debugging = False17 stack = {} # used to initialize ImagingReso18 19 def __init__(self, parent=None, debugging=False):20 QMainWindow.__init__(self, parent=parent)21 self.ui = UiSampleMainWindow()22 self.ui.setupUi(self)23 self.setWindowTitle("Define Sample Layers")24 25 self.debugging = debugging26 27 self.initialize_ui()28 self.__debugging()29 30 def __debugging(self):31 '''Fill the table for debugging only!'''32 if not self.debugging:33 return34 35 _debug_table = [['Gadnium','Gd','1','0.075','']]36 for _row_index,_row in enumerate(_debug_table):37 for _col_index, _entry in enumerate(_row):38 _item = QtGui.QTableWidgetItem(_entry)39 self.ui.layer_table.setItem(_row_index, _col_index, _item)40 41 def initialize_ui(self):42 self.ui.check_groupBox.setVisible(False)43 44 _column_width = [300, 100, 100, 100, 100]45 for _index, _width in enumerate(_column_width):46 self.ui.layer_table.setColumnWidth(_index, _width)47 self.ui.example_table.setColumnWidth(_index, _width)48 49 _column_width = [80, 90, 90, 100]50 for _index, _width in enumerate(_column_width):51 self.ui.element_table.setColumnWidth(_index, _width)52 53 def validate_table_input_clicked(self):54 # block element table signal55 self.ui.element_table.blockSignals(True)56 # disable top part (no more changes allowed)57 self.ui.layer_groupBox.setEnabled(False)58 59 # collect table input60 nbr_row = self.ui.layer_table.rowCount()61 _table_dictionary = {}62 for _row_index in range(nbr_row):63 _dict = {}64 _layer_name = self.get_table_item(_row_index, 0)65 if _layer_name == '':66 break67 _dict['elements'] = self.format_string_to_array(string=self.get_table_item(_row_index, 1), data_type='str')68 _dict['stoichiometric_ratio'] = self.format_string_to_array(string=self.get_table_item(_row_index, 2), data_type='float')69 _dict['thickness'] = {'value': float(self.get_table_item(_row_index, 3)),70 'units': 'mm'}71 if self.get_table_item(_row_index, 4):72 _dict['density'] = {'value': float(self.get_table_item(_row_index, 4)),73 'units': 'g/cm3'}74 _table_dictionary[_layer_name] = _dict75 self.stack = _table_dictionary76 E_min = float(str(self.ui.Emin_lineEdit.text()))77 E_max = float(str(self.ui.Emax_lineEdit.text()))78 delta_E = float(str(self.ui.deltaE_lineEdit.text()))79 o_reso = Resonance(stack=self.stack, energy_min=E_min, energy_max=E_max, energy_step=delta_E)80 self.o_reso = o_reso81 82 self.fill_check_groupBox()83 self.ui.check_groupBox.setVisible(True) 84 self.ui.element_table.blockSignals(False)85 self.ui.ok_button.setEnabled(True)86 87 def format_string_to_array(self, string='', data_type='str'):88 _parsed_string = string.split(',')89 result = []90 for _entry in _parsed_string:91 if data_type == 'str':92 result.append(str(_entry))93 elif data_type == 'float':94 result.append(float(_entry))95 else:96 raise ValueError("data_type not supported!")97 return result98 99 def get_table_item(self, row, col):100 _item = self.ui.layer_table.item(row, col)101 if _item is None:102 return ''103 _text = _item.text().strip()104 return _text105 def fill_check_groupBox(self):106 # fill layer's name107 _stack = self.o_reso.stack108 layers_name = list(_stack.keys())109 self.ui.layer_name_combobox.clear()110 self.ui.layer_name_combobox.addItems(layers_name)111 112 def element_combobox_clicked(self, element_selected):113 if element_selected == '':114 return115 116 self.ui.element_table.blockSignals(True)117 layer_selected = self.ui.layer_name_combobox.currentText()118 if layer_selected == '':119 return120 if element_selected == '':121 return122 123 _entry = self.stack[layer_selected][element_selected]124 number_of_atoms = float(self.stack[layer_selected]['atoms_per_cm3'][element_selected])125 self.ui.element_number_of_atoms.setText("{:6.3e}".format(number_of_atoms))126 density = str(self.stack[layer_selected][element_selected]['density']['value'])127 self.ui.element_density.setText("{:6.3e}".format(float(density)))128 molar_mass = str(self.stack[layer_selected][element_selected]['molar_mass']['value'])129 self.ui.element_molar_mass.setText("{:6.3e}".format(float(molar_mass)))130 131 self.fill_isotopes_table(element_selected)132 self.ui.element_table.blockSignals(False)133 134 def fill_isotopes_table(self, element_selected=''):135 self.clear_isotopes_table()136 layer_selected = self.ui.layer_name_combobox.currentText()137 element_selected = self.ui.element_name_combobox.currentText()138 _entry = self.stack[layer_selected][element_selected]['isotopes']139 list_iso = _entry['list']140 list_density = _entry['density']['value']141 list_iso_ratio = _entry['isotopic_ratio']142 list_mass = _entry['mass']['value']143 144 nbr_iso = len(list_iso)145 for _row in range(nbr_iso):146 self.ui.element_table.insertRow(_row)147 # iso name148 _item = QtGui.QTableWidgetItem(list_iso[_row])149 _item.setFlags(QtCore.Qt.NoItemFlags)150 _color = QtGui.QColor(200,200,200)151 _item.setBackgroundColor(_color)152 self.ui.element_table.setItem(_row, 0, _item)153 # density154 _item = QtGui.QTableWidgetItem("{:6.3e}".format(list_density[_row]))155 _item.setBackgroundColor(_color)156 _item.setFlags(QtCore.Qt.NoItemFlags)157 self.ui.element_table.setItem(_row, 1, _item)158 159 # iso. ratio160 _item = QtGui.QTableWidgetItem("{:6.3e}".format(list_iso_ratio[_row]))161 self.ui.element_table.setItem(_row, 2, _item)162 163 # molar mass164 _item = QtGui.QTableWidgetItem("{:6.3e}".format(list_mass[_row]))165 _item.setBackgroundColor(_color)166 _item.setFlags(QtCore.Qt.NoItemFlags)167 self.ui.element_table.setItem(_row, 3, _item)168 self.calculate_sum_iso_ratio()169 170 def clear_isotopes_table(self):171 nbr_row = self.ui.element_table.rowCount()172 for _row in range(nbr_row):173 self.ui.element_table.removeRow(0)174 def calculate_sum_iso_ratio(self):175 nbr_row = self.ui.element_table.rowCount()176 total_iso_ratio = 0177 for _row in range(nbr_row):178 _item = self.ui.element_table.item(_row, 2)179 try:180 _iso_ratio = float(self.ui.element_table.item(_row, 2).text())181 except:182 _iso_ratio = np.NaN183 _item = QtGui.QTableWidgetItem("NaN")184 self.ui.element_table.setItem(_row, 2, _item)185 total_iso_ratio += _iso_ratio186 self.ui.total_iso_ratio.setText("{:.2f}".format(total_iso_ratio))187 # will use this flag to allow new isotopic ratio entries188 if np.isnan(total_iso_ratio):189 return False190 return True191 192 def layer_combobox_clicked(self, layer_selected):193 if layer_selected == '':194 return195 list_elements = self.stack[layer_selected]['elements']196 # block element table signal197 self.ui.element_table.blockSignals(True)198 199 # fill list of elements for this layer200 self.ui.element_name_combobox.clear()201 self.ui.element_name_combobox.addItems(list_elements)202 203 # fill info for this layer204 _layer = self.stack[layer_selected]205 thickness = str(_layer['thickness']['value'])206 self.ui.layer_thickness.setText(thickness)207 density = str(_layer['density']['value'])208 self.ui.layer_density.setText(density)209 210 self.ui.element_table.blockSignals(False)211 def element_table_edited(self, row, col):212 if col == 2:213 calculation_status = self.calculate_sum_iso_ratio()214 if calculation_status:215 self.define_new_isotopic_ratio()216 217 def define_new_isotopic_ratio(self):218 layer_selected = self.ui.layer_name_combobox.currentText()219 element_selected = self.ui.element_name_combobox.currentText()220 _entry = self.stack[layer_selected][element_selected]['isotopes']221 list_isotopes = _entry['list']222 223 nbr_row = self.ui.element_table.rowCount()224 list_isotopic_ratio = []225 for _row in range(nbr_row):226 _iso_ratio = float(self.ui.element_table.item(_row, 2).text())227 list_isotopic_ratio.append(_iso_ratio)228 229 self.o_reso.set_isotopic_ratio(compound=layer_selected, 230 element=element_selected, 231 list_ratio=list_isotopic_ratio)232 233 self.layer_combobox_clicked(layer_selected)234 self.element_combobox_clicked(element_selected)235 236 def ok_button_clicked(self):237# global global_o_reso238# global_o_reso = self.o_reso239 self.close()...
Rpa.py
Source:Rpa.py
1from operator import imod2from selenium import webdriver3from core.Storage import Storage4from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException5from selenium.webdriver.support.ui import WebDriverWait6from selenium.webdriver.support import expected_conditions as EC7from selenium.webdriver.common.by import By8import time9from selenium.webdriver.common.keys import Keys10from core import Log11from pathlib import Path12import os13import shutil14class Rpa():15 16 def __init__(self, config = {"showBrowser":False, "namelog":"rpa"}) -> None:17 18 """Instancia o RPA""" 19 20 self._config = config 21 self.Log = Log() 22 23 self.element_selected = None24 self.fileToDownload = None25 26 try: 27 options = webdriver.ChromeOptions()28 options.add_experimental_option(29 "prefs", 30 {31 "download.default_directory": Storage().basePath('core\\chromedriver\\downloads'),32 "download.prompt_for_download": False,33 "download.directory_upgrade": True,34 "safebrowsing.enabled": True35 }36 )37 options.add_experimental_option('excludeSwitches', ['enable-logging']) 38 39 if(self._config['showBrowser'] == False): 40 options.add_argument("--headless") 41 self.driver = webdriver.Chrome(executable_path = 'core\\chromedriver\\chromedriver.exe', chrome_options=options) 42 self.windowSize()43 44 except Exception as err: 45 Log(self._config['namelog'],rf"Erro: {err}")46 return None47 48 def click(self, type, value): 49 """50 Retorna o click em um elemento da pagina que pode ser do tipo [XPATH | NAME | ID | CLASS_NAME | TAG_NAME]51 52 :DRIVER: WebDriver53 :ELEMT: array54 55 RETURN bool|element56 """ 57 ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,) 58 self.Log.log(self._config['namelog'],rf"Clicando em elemento {type}:{value}") 59 60 type = type.lower() 61 try:62 63 if(type == 'xpath'): 64 WebDriverWait(self.driver, 60,ignored_exceptions=ignored_exceptions).until(EC.element_to_be_clickable((By.XPATH, value ))).click()65 66 elif(type == 'name'):67 WebDriverWait(self.driver, 60,ignored_exceptions=ignored_exceptions).until(EC.element_to_be_clickable((By.NAME, value ))).click()68 69 elif(type == 'id'):70 WebDriverWait(self.driver, 60,ignored_exceptions=ignored_exceptions).until(EC.element_to_be_clickable((By.ID, value ))).click()71 72 elif(type == 'clas_name'):73 WebDriverWait(self.driver, 60,ignored_exceptions=ignored_exceptions).until(EC.element_to_be_clickable((By.CLASS_NAME, value ))).click()74 75 elif(type == 'tag_name'):76 WebDriverWait(self.driver, 60,ignored_exceptions=ignored_exceptions).until(EC.element_to_be_clickable((By.TAG_NAME, value ))).click()77 78 else: 79 Log(self._config['namelog'],rf"Erro: Elemento Não encontrado: {type}:{value}") 80 81 except Exception as err: 82 Log(self._config['namelog'],rf"Erro: Elemento Não encontrado: {type}:{value}") 83 84 85 return self 86 87 def url(self, url): 88 """Acessa uma url"""89 self.Log.log(self._config['namelog'],rf"Acessando url: {url}")90 self.driver.get(url)91 return self92 93 94 def findElement(self, by, value): 95 """Procura um elemento na página""" 96 97 try:98 self.Log.log(self._config['namelog'],rf"Procurando elemento: {by}:{value}")99 if by == 'id':100 self.element_selected = self.driver.find_element_by_id(value)101 elif by == 'name':102 self.element_selected = self.driver.find_element_by_name(value)103 elif by == 'xpath':104 self.element_selected = self.driver.find_element_by_xpath(value)105 elif by == 'css':106 self.element_selected = self.driver.find_element_by_css_selector(value) 107 108 except Exception as err: 109 self.Log.log(self._config['namelog'], rf"Erro: Elemento Não encontrado: {by}:{value}") 110 111 return self112 113 114 def key(self, value):115 """Insere um texto no elemento selecionado""" 116 117 if(self.element_selected != None):118 self.Log.log(self._config['namelog'],rf"Inserindo o texto: '{value}'")119 self.element_selected.send_keys(value) 120 else:121 self.Log.log(self._config['namelog'], rf"Erro: Não há elemento selecionado para inserir texto") 122 self.element_selected = None 123 124 return self125 126 127 def delay(self, timer):128 """Adiciona um delay em segundos"""129 self.Log.log(self._config['namelog'],rf"Aguardando {timer} segundos")130 time.sleep(timer)131 return self132 133 134 def enter(self):135 """Aciona o botão enter do teclado"""136 if(self.element_selected != None):137 self.Log.log(self._config['namelog'],rf"Acionando o ENTER")138 self.element_selected.send_keys(Keys.ENTER)139 else:140 self.Log.log(self._config['namelog'], rf"Erro: Não há elemento selecionado para pressionar enter") 141 self.element_selected = None 142 143 return self144 145 146 def toIframe(self):147 """Pula para um frame""" 148 if(self.element_selected != None):149 self.Log.log(self._config['namelog'],rf"Alterando para iframe selecionado")150 self.driver.switch_to.frame(self.element_selected)151 else:152 self.Log.log(self._config['namelog'], rf"Erro: Não há iframe selecionado") 153 self.element_selected = None 154 155 return self156 157 158 def backoDocument(self):159 """Retorna ao documento base"""160 self.Log.log(self._config['namelog'],rf"Retornando para documento base")161 self.driver.switch_to.default_content() 162 return self163 164 165 def getAttribute(self, name):166 """Recupera um atributo de um elemento selecionado"""167 if(self.element_selected != None):168 self.Log.log(self._config['namelog'],rf"Pegando atributo {name} de {self.element_selected}")169 self.element_selected.get_attribute(name)170 else:171 self.Log.log(self._config['namelog'], rf"Erro: Não há elemento selecionado para pegar o atributo") 172 self.element_selected = None 173 174 return self175 176 177 def formSubmit(self):178 """Aciona o submit de um formulario selecionado"""179 if(self.element_selected != None):180 self.Log.log(self._config['namelog'],rf"Submit de formulário")181 self.element_selected.submit()182 else:183 self.Log.log(self._config['namelog'], rf"Erro: Não há formulario selecionado para dar o submit") 184 self.element_selected = None 185 186 return self187 188 189 def windowSize(self, size = 'maximize', x=None, y=None):190 """Ajusta a tela do navegador"""191 if size == 'maximize':192 self.driver.maximize_window()193 elif size == 'minimize':194 self.driver.minimize_window()195 elif size == 'set':196 self.driver.set_window_size(x,y)197 198 def waitDownload(self, file, timeOut=300):199 """Aguarda o download de um arquivo"""200 dirdown = Path(Storage().pathRpaDownloads()) 201 202 timer = 0 203 stop = False204 while stop == False:205 filesInDown = dirdown.glob('*') 206 filesInDown = sorted(filesInDown) 207 208 for dnfile in filesInDown: 209 if file in os.path.basename(dnfile):210 self.Log.log(self._config['namelog'], rf"Arquivo '{os.path.basename(dnfile)}' encontrado") 211 self.fileToDownload = dnfile212 stop = True213 214 if(stop == False): 215 timer = timer+1216 time.sleep(1) 217 if(timer<=1): 218 self.Log.log(self._config['namelog'], rf"Aguardando download do arquivo {file}") 219 220 221 if(timer >= timeOut and stop == False):222 self.Log.log(self._config['namelog'], rf"Erro: Arquivo '{file}' demorou muito para baixar") 223 stop = True 224 225 return self226 227 228 def moveDownFileTo(self, toDir):229 """Move um arquivo baixado para outro diretorio, utilizado apos waitDownload()"""230 if os.path.isdir(toDir) == False:231 os.makedirs(toDir)232 self.Log.log(self._config['namelog'],rf'Movendo arquivo para {toDir}') 233 shutil.move(self.fileToDownload, toDir)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!