def add_2(self, num1, num2): self.click_wyczysc() send_keys(num1) self.click_plus() send_keys(num2) self.click_rownasie() return self.get_result()
def open_chrome(): # path to chrome chrome_dir = r'"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"' # open chrome maximized and allow access to pywinauto chrome = Application(backend='uia') chrome.start(chrome_dir + ' --force-renderer-accessibility --start-maximized') # sleep for random time to allow page to load and go to zoominfo.com time.sleep(float(decimal.Decimal(random.randrange(50, 150)) / 100)) send_keys("zoominfo.com {ENTER 2}") # sleep for enough time for me to move mouse to the 'login' button to get coordinates time.sleep(float(decimal.Decimal(random.randrange(150, 300)) / 100)) time.sleep(7) # print coordinates of mouse over the login button position = pyautogui.position() print(position) # move mouse to and click on the login button pywinauto.mouse.click(button='left', coords=(1737, 104)) time.sleep(float(decimal.Decimal(random.randrange(150, 300)) / 100))
def _execute(self, filter_string: str = "", expected_count: int = None, expected_names: List[str] = None, allow_additional_tracks=False): """ See MatchTracks._execute() for documentation. """ toolbar = self.find_control("ToolBar", "CaptureToolBar") track_filter = self.find_control("Edit", "FilterTracks", parent=toolbar) logging.info("Setting track filter text: '%s'", filter_string) track_filter.set_focus() track_filter.set_edit_text('') # Using send_keys instead of set_edit_text directly because set_edit_text ignores the wait timings... keyboard.send_keys(filter_string) # Verify by re-using a MatchTracks Fragment match_tracks = MatchTracks( expected_count=expected_count, expected_names=expected_names, allow_additional_tracks=allow_additional_tracks) match_tracks.execute(self.suite)
def automation(self): driver = webdriver.Firefox() try: driver.get("https://www.seleniumhq.org/download/") driver.maximize_window() driver.find_element_by_xpath( "//td[text()='Java']/..//*[contains(text(),'Download')]" ).click() time.sleep(1) # Handling windows based pop using pywinauto package. keyboard.send_keys("{TAB}") keyboard.send_keys("{TAB}") time.sleep(1) keyboard.send_keys("{TAB}") keyboard.send_keys("{TAB}") keyboard.send_keys("{ENTER}") except Exception as e: print("Error occured:") print(str(e)) else: print( "Else block will work only when there is no exception. But Finally block will execute all the times." ) finally: driver.close()
def start_game(main_dlg): no_save_result = False save_result = False send_keys("{SPACE down}") # Keep pressing z until we get to the main menu while not no_save_result and not save_result: press_key('z') # Wait for next frame to load before processing image time.sleep(1) # Capture an image of the screen and convert it to cv2 img = screenshot(main_dlg.window_text()) numpy_img = np.array(img) parent_img = cv2.cvtColor(numpy_img, cv2.COLOR_RGB2BGR) # Read a template image of the main menu no_save_img = cv2.imread('img/menu_no_save.PNG') save_img = cv2.imread('img/menu_save.PNG') # Check if we are at the main menu no_save_result = img_contains(parent_img, no_save_img, .003) save_result = img_contains(parent_img, save_img, .003) send_keys("{SPACE up}") # If there is a saved game, press z to get into the game if save_result: print('Saved game found...') press_key('z') # If there wasn't a saved game, inform the user and have them retry elif no_save_result: print( 'No saved game found. Please ensure you have a .sav file in the same directory as your ROM' ) exit(1)
def show(self, *args): """ """ if args and len(args) == 1 and args[0] == 'local': self.show_spotify_window() while True: try: #time.sleep(5) send_keys('^p') self.spotify_window_button(title="Settings", control_type="Document") break except TimeoutError: pass while True: try: self.spotify_window_button(title="Show Local Files", control_type="CheckBox", timeout=1) #if show_local_files_checkbox.get_toggle_state() == 0: # show_local_files_checkbox.click_input() return except TimeoutError: send_keys('{DOWN 6}') self.cmd_set_focus() else: print("\nUsage:\tshow local") raise KeyError
def add(self, *args): """ """ if args and len(args) == 1: try: self.spotify_set_focus() self.spotify_window.maximize() self.spotify_window_button(title='Local Files', control_type='Hyperlink') time.sleep(0.5) self.spotify_direct_button('Custom2') send_keys('^a') self.spotify_direct_button('Custom2', 'right') self.spotify_window_button(title='Add to Playlist', control_type='Text') self.spotify_window_button(title=args[0], control_type='Text') time.sleep(1) send_keys('{ENTER}') except Exception: print( colored.stylize("""\n[*] """, colored.fg("light_red")) + "Timeout error, element not found!\n") raise KeyError else: print("\nUsage:\tadd PLAYLIST") raise KeyError
def __sell(self, code, price, quantity): keyboard.send_keys("{F2}") time.sleep(sleepTime) self.__init__() # self.__dialog_window.print_control_identifiers() self.__dialog_window.Edit0.set_focus() time.sleep(sleepTime) self.__dialog_window.Edit0.set_edit_text(code) time.sleep(sleepTime) self.__dialog_window.Edit2.set_focus() time.sleep(sleepTime) self.__dialog_window.Edit2.set_edit_text(price) time.sleep(sleepTime) self.__dialog_window.Edit3.set_focus() time.sleep(sleepTime) self.__dialog_window.Edit3.set_edit_text(quantity) time.sleep(sleepTime) self.__dialog_window[u'卖出Button'].click() # self.__dialog_window.child_window(title=u"卖出", class_name="Button").Click() time.sleep(sleepTime)
def _load_all_modules(self): logging.info("Loading all modules") self._modules_dataview.get_item_at(0, 0).click_input() # Select all send_keys("^a") self._modules_dataview.get_item_at(0, 0).click_input('right') self.find_context_menu_item('Load Symbols').click_input()
def cha_click(self, cha, keyvalue): for i in range(0, cha): send_keys(keyvalue) # 按向上键 self.time_delay(1) # 按enter键 send_keys("{VK_RETURN}") self.time_delay(1)
def on_event(self, event): if not isinstance( event, KeyboardEvent) or event.event_type != 'key down' or self.lock: return False if set(event.pressed_key) != self.HOTKEY: # log.info(event.__dict__) return False self.lock = True log.info("listening...") with speech_recognition.Microphone( device_index=self.DEVICE_INDEX) as source: audio = self.recognizer.listen(source) log.info("converting audio to text...") try: text = self.recognizer.recognize_google( audio_data=audio, # This uses Google Speech Engine's public API key. # If you exceed the quota, you need your own API key from https://console.developers.google.com/ key="AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw", language=self.LANGUAGE) log.info(f"typing '{text}'") keyboard.send_keys(text, with_spaces=True) except: log.exception("") finally: keyboard.send_keys("{VK_LWIN up}{Z up}") self.lock = False
def _execute(self, process_filter): # Finding FilterProcesses/ProcessList occationally throws from within pywinauto. This is not # understood. The while loop with the try/except block is a workaround for that. while True: try: filter_edit = self.find_control('Edit', 'FilterProcesses') break except KeyError: logging.info('Find FilterProcesses failed. Try again.') while True: try: process_list = self.find_control('Table', 'ProcessList') break except KeyError: logging.info('Find ProcessList failed. Try again.') logging.info('Waiting for process list to be populated') wait_for_condition(lambda: process_list.item_count() > 0, 30) logging.info('Setting filter text for process list') if process_filter: filter_edit.set_focus() filter_edit.set_edit_text('') send_keys(process_filter) # Wait for the process to show up - it may still be starting wait_for_condition(lambda: process_list.item_count() > 0, 30) logging.info('Process selected, continuing to main window...') process_list.children(control_type='DataItem')[0].double_click_input() _wait_for_main_window(self.suite.application) window = self.suite.top_window(True) self.expect_eq(window.class_name(), "OrbitMainWindow", 'Main window is visible') window.maximize()
def ascii_export(self, path, tsv_name): print("Doing ASCII export.") self.select_all() self.spec.menu_select("Process -> ASCII Export") export = self.app["ASCII Export"] export.ReflectanceRadioButton.check() export.AbsoluteCheckBox.check() export.OutputToASingleFileCheckBox.check() export.set_focus() time.sleep(2) export.Button2.click_input() save = self.app["Select Ascii File"] save.set_focus() save.ToolBar2.double_click() keyboard.send_keys(path) keyboard.send_keys("{ENTER}") save.edit.set_edit_text(tsv_name) save.set_focus() time.sleep(2) save.OKButton.click_input() while not self.app.Dialog.exists(): time.sleep(0.25) pass self.app["Dialog"].OKButton.set_focus() self.app["Dialog"].OKButton.click()
def _captureRepeatPart(sct, output, windows): sleep(0.4) sct_img = sct.grab(monitor) mss.tools.to_png(sct_img.rgb, sct_img.size, output=output) #windows['ab'].type_keys('{VK_SUBTRACT}') windows['ab'].set_focus() keyboard.send_keys('{VK_SUBTRACT}')
def restart(self): self.spec.set_focus() rect = self.spec.rectangle() print(rect) loc = find_image(IMG_LOC + "/exit.png", rect=rect) if loc is not None: x_left = self.spec.rectangle().left y_top = self.spec.rectangle().top while x_left < -10 or y_top < -10: x_left = self.spec.rectangle().left y_top = self.spec.rectangle().top time.sleep(0.25) x = loc[0] + x_left y = loc[1] + y_top mouse.click(coords=(x, y)) print("clicked x") time.sleep(0.5) keyboard.send_keys("{ENTER}") time.sleep(10) self.app = Application().start(self.RS3_loc) self.spec = None self.spec_connected = False self.spec = self.app.ThunderRT6Form self.spec.draw_outline() self.pid = self.app.process self.menu = RS3Menu(self.app) else: print("Error: Failed to restart RS3")
def _execute(self): # For some reason the line below does NOT work when Orbit is maximized - this is actually consistent with # the results of AccessibilityInsights as the close button seems to have no on-screen rect... # self.find_control("Button", "Close").click_input() # ... so just send Alt + F4 send_keys('%{F4}') logging.info('Closed Orbit.')
def runApp(index): global DULLRAZOR_ROOT, pathlist, total app = Application().start(DULLRAZOR_ROOT) window = app.window(title='DullRazor for Windows') window2 = app.window(title='dullrazor') # Every 80-85 runs, Dullrazor crashes for an unknown reason, so we have to restart it. try: currentIndex = index while currentIndex < total: print(currentIndex) path = pathlist[currentIndex] subprocess.run(['clip.exe'], input=str(path).strip().encode('utf-8'), check=True) send_keys( "{TAB}{TAB}{TAB}{TAB}{TAB}^v{TAB}{TAB}^v{TAB}{TAB}{TAB}{ENTER}" ) window2.wait('exists', timeout=20) send_keys("{ENTER}") currentIndex += 1 except TimeoutError: runApp(currentIndex)
def __get_grid_data(self, require_dates = False): """ 取得GRID窗口中的数据。 1. require_dates = True, 有些平台有两个子窗口。一个填日期,一个显示数据。 2. require_dates = False, 有些平台带日期,但只有一个GRID窗口。 """ if require_dates: self.main_wnd.child_window(title="Custom1", class_name='CVirtualGridCtrl', found_index=1).set_focus() # .right_click() # 模拟右键 else: self.main_wnd.child_window(title="Custom1", class_name='CVirtualGridCtrl', found_index=0).set_focus() # 复制 keyboard.send_keys('^c') # Ctrl+C # 跳出验证码窗口 self.app.top_window().wait('ready',timeout=2) # 验证码错误就重新输入 trial = 1 # 最多尝试5次识别,避免循环 while trial <=5: # 识别并输入验证码,确认关闭验证码窗口 print("最多识别5次,现在第%d次"%trial) self.app.top_window().child_window(class_name='Edit').set_text(self.__get_char()) self.app.top_window().child_window(class_name='Edit').type_keys("{ENTER}") trial += 1 try: "验证码错误" in self.app.top_window().window(class_name="Static",title="验证码错误!!").texts() except: break #验证码有错,则继续 data = clipboard.GetData() df = pd.read_csv(io.StringIO(data), delimiter='\t', na_filter=False) return df.to_dict('records')
def func2(): global runs lock.acquire() lock.release() while runs < 30: send_keys('{s down}' '{s up}') runs += 1
def test_invert(self): dlg = run_calculator() num = (generate_random_number(-10000, 1000) / 100) # num = generate_random_number(-1000, 1000) num_c = str(num).replace('.', ',') # divide to 0 # num_c = 0 dlg.type_keys(num_c) dlg.child_window(auto_id='negateButton').click() send_keys('{ENTER}') time.sleep(1) dlg.child_window(auto_id='invertButton').click() result = dlg.child_window(auto_id='CalculatorResults').window_text() if contain_digits(result): real_res = get_number(result) exp_res = trim_num(1 / (-num), get_numbers_of_symbols(real_res)) else: self.assertEqual('Display is Cannot divide by zero', result) time.sleep(1) dlg.close()
def _execute(self, process_filter): if flags.FLAGS.enable_ui_beta: filter_edit = self.find_control('Edit', 'FilterProcesses') process_list = self.find_control('Table', 'ProcessList') else: process_data_view = DataViewPanel(self.find_control('Group', 'ProcessesDataView')) filter_edit = process_data_view.filter process_list = process_data_view.table logging.info('Waiting for process list to be populated') wait_for_condition(lambda: process_list.item_count() > 0, 30) logging.info('Setting filter text for process list') if process_filter: filter_edit.set_focus() filter_edit.set_edit_text('') send_keys(process_filter) # Wait for the process to show up - it may still be starting wait_for_condition(lambda: process_list.item_count() > 0, 30) if flags.FLAGS.enable_ui_beta: logging.info('Process selected, continuing to main window...') process_list.children(control_type='DataItem')[0].double_click_input() wait_for_main_window(self.suite.application) window = self.suite.top_window(True) self.expect_eq(window.class_name(), "OrbitMainWindow", 'Main window is visible') else: process_list.children(control_type='TreeItem')[0].click_input()
def _execute(self, module_search_string: str): _show_symbols_and_functions_tabs(self.suite.top_window()) logging.info('Start loading symbols for module %s', module_search_string) modules_dataview = DataViewPanel( self.find_control("Group", "ModulesDataView")) logging.info('Waiting for module list to be populated...') wait_for_condition(lambda: modules_dataview.get_row_count() > 0, 100) logging.info('Filtering and loading') modules_dataview.filter.set_focus() modules_dataview.filter.set_edit_text('') send_keys(module_search_string) wait_for_condition(lambda: modules_dataview.get_row_count() == 1) modules_dataview.get_item_at(0, 0).click_input('right') self.find_context_menu_item('Load Symbols').click_input() logging.info('Waiting for * to indicate loaded modules') wait_for_condition( lambda: modules_dataview.get_item_at(0, 4).texts()[0] == "*", 100) functions_dataview = DataViewPanel( self.find_control("Group", "FunctionsDataView")) wait_for_condition(lambda: functions_dataview.get_row_count() > 0)
def test_subtraction(self): # run a program dlg = run_calculator() for i in range(4): # enter data num1 = generate_random_number(10, 29) num2 = generate_random_number(1, 9) dlg.type_keys(num1) dlg.type_keys('-') time.sleep(1) dlg.type_keys(num2) time.sleep(1) # get results dlg.type_keys('=') real_res = get_number( dlg.child_window(auto_id='CalculatorResults').window_text()) # compare results self.assertEqual(real_res, num1 - num2) send_keys('{ESC}') time.sleep(1) dlg.close()
def _delete_keys_from_terminal(keys): """Emulate BACK key press A helper to remove the keys that has been sent to the terminal during a test. We don't care if BACK is pressed more than required when special codes were used. """ if keys: send_keys('{BACK ' + str(len(keys)) + '}')
def testNewlinesWithNewlines(self): """Make sure that with_newlines option works""" send_keys("\t \t \t a~\tb\nc", pause=.5, with_newlines=True) received = self.receive_text() if sys.platform == 'win32': self.assertEqual("a\r\nb\r\nc", received) else: self.assertEqual("a\nb\nc", received)
def func4(): global runs global lock lock.acquire() lock.release() while runs < 30: send_keys('{LEFT down}' '{LEFT up}') runs += 1
def main_function(): start_time = time.time() mouse.click(Button.left, 2) pywinauto_keyboard.send_keys('^c') copy_text = pyperclip.paste() symbol.set_edit_text(copy_text) symbol.send_keystrokes("{ENTER}") print("--- %s seconds ---" % (time.time() - start_time))
def accept_then_back(self): ready = locateOnScreen(self.material['game_ready'], grayscale=True) \ or locateOnScreen(self.material['accept'], grayscale=True) \ or None if ready: print('NEW GAME') # click(ready) keyboard.send_keys('{ENTER}') hotkey('alt', 'tab')
def winAuto(self): gekodriverpath = os.getcwd() + "/Drivers/geckodriver.exe" driver = webdriver.Firefox(executable_path=gekodriverpath) driver.get("https://www.seleniumhq.org/download/") driver.find_element_by_xpath( "//a[contains(text(),'3.141.59')]").click() time.sleep(2) keyboard.send_keys("{ENTER}") driver.quit()
def Send_Keywords(self, user_input): """ **Send key presses** -------------- :Example: | Send_Keywords x """ logger.info('Send keywords %s.' % user_input) send_keys(user_input)
def __get_text(self): data = '' time.sleep(1) send_keys('^a^c', pause=0.2) if sys.platform == 'win32': win32clipboard.OpenClipboard() data = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() else: data = clipboard.get_data() return data
def _type_keys_and_unhook(self, key_strokes): """A timer callback to type key strokes and unhook""" send_keys(key_strokes) # Give a time to process the keys by the hook self._sleep_and_unhook()