def loginView(self): try: connected_nordlocker.connect(title='NordLocker') except findwindows.WindowAmbiguousError: wins = findwindows.find_elements(active_only=True, title="NordLocker") connected_nordlocker.connect(handle=wins[0].handle) except findwindows.ElementNotFoundError: wait_until(30, 0.5, lambda: len(findwindows.find_elements(active_only=True, title="NordLocker")) > 0) wins = findwindows.find_elements(active_only=True, title="NordLocker") connected_nordlocker.connect(handle=wins[0].handle)
def _wait_minimized(dlg): """A helper function to verify that the specified dialog is minimized Basically, WaitNot('visible', timeout=30) would work too, just wanted to make sure the dlg is really got to the 'minimized' state because we test hiding the window to the tray. """ wait_until(timeout=_ready_timeout, retry_interval=_retry_interval, func=lambda: (dlg.GetShowState() == win32defines.SW_SHOWMINIMIZED)) return True
def _wait_minimized(dlg): """A helper function to verify that the specified dialog is minimized Basically, WaitNot('visible', timeout=30) would work too, just wanted to make sure the dlg is really got to the 'minimized' state because we test hiding the window to the tray. """ wait_until( timeout=_ready_timeout, retry_interval=_retry_interval, func=lambda: (dlg.get_show_state() == win32defines.SW_SHOWMINIMIZED) ) return True
def purchase_fund(self, fund_code, money): """ 申购场内基金 """ self.__select_menu(path="\场内基金\基金申购") for i in range(4): keyboard.send_keys("{TAB}") for i in range(self.main_win.window(control_id=0x3ec).item_count()): keyboard.send_keys(fund_code) self.__select_account(index=i) keyboard.send_keys("{TAB}") keyboard.send_keys(money) keyboard.send_keys("%s" "%y" "{UP}" "{SPACE}") wait_until(10, .5, self.__get_target_dialog, True, text_in_dialog="本人已经认真阅读并理解上述内容") # 等待对话框 keyboard.send_keys("{TAB}" "{SPACE}" "{TAB}" "{ENTER}") wait_until(10, .5, self.__get_target_dialog, True, text_in_dialog="提示信息") # 等待对话框 keyboard.send_keys("{ENTER}") wait_until(10, .5, self.__get_target_dialog, True, text_in_dialog="公募证券投资基金投资风险告知") # 等待对话框 keyboard.send_keys("{TAB}" "{SPACE}" "{TAB}" "{ENTER}") wait_until(10, .5, self.__get_target_dialog, True, text_in_dialog="适当性匹配结果确认书") # 等待对话框 keyboard.send_keys("{TAB}" "{ENTER}") wait_until(10, .5, self.__get_target_dialog, True, text_in_dialog="提示") # 等待对话框 keyboard.send_keys("{ENTER}")
def export_view(mod, pt_num, path_to_views, username=ACRONYM, password=ACRONYM): cmd_display(mod, 'downloading...') app = Application().start( cmd_line= u'"C:\\Program Files (x86)\\Solid Edge TC Manual View\\Solid Edge TC Manual View.exe"' ) app.LoginForm.wait('ready', timeout=30) app.LoginForm.Edit5.set_edit_text(username) app.LoginForm.Edit4.set_edit_text(password) app.LoginForm.Login.click_input() time.sleep(5) app.PrincipalForm.wait('ready') app.PrincipalForm.Edit2.set_edit_text(pt_num) app.PrincipalForm.Search.click_input() time.sleep(3) if findwindows.find_windows(title='Search error'): print('Search Error: PT number invalide ') window = app.Dialog window.wait('ready') window.close() app.PrincipalForm.type_keys('%{F4}') else: app.PrincipalForm[u'4'].type_keys( path_to_views) #loop through the modules files app.PrincipalForm[u'3'].type_keys("{DOWN}") app.PrincipalForm.Export.click_input() app.wait_cpu_usage_lower( threshold=5) # wait until CPU usage is lower than 5% def detecting_pdf(): return any(glob.glob(os.path.join(path_to_views, r'*\*.pdf'))) wait_until(1000, 5.00, detecting_pdf, True) cmd_display(mod, 'exported') #close the popup windows & app window = app.Dialog button = window.OK button.click_input() #close principal form app.PrincipalForm.type_keys('%{F4}') # close an active window with Alt+F4 time.sleep(3)
def testClickVisibleIcon(self): """ Test minimizing a sample app into the visible area of the tray and restoring the app back """ if is_x64_Python() != is_x64_OS(): # We don't run this test for mixed cases: # a 32-bit Python process can't interact with # a 64-bit explorer process (taskbar) and vice versa return # Make sure that the hidden icons area is disabled orig_hid_state = _toggle_notification_area_icons( show_all=True, debug_img="%s_01" % (self.id()) ) self.dlg.minimize() _wait_minimized(self.dlg) menu_window = [None] # Click in the visible area and wait for a popup menu def _show_popup_menu(): taskbar.explorer_app.wait_cpu_usage_lower(threshold=5, timeout=self.tm) taskbar.RightClickSystemTrayIcon('MFCTrayDemo') menu = self.app.top_window().children()[0] res = isinstance(menu, ToolbarWrapper) and menu.is_visible() menu_window[0] = menu return res wait_until(self.tm, _retry_interval, _show_popup_menu) menu_window[0].menu_bar_click_input("#2", self.app) popup_window = self.app.top_window() hdl = self.dlg.popup_window() self.assertEqual(popup_window.handle, hdl) taskbar.ClickSystemTrayIcon('MFCTrayDemo', double=True) self.dlg.wait('active', timeout=self.tm) # Restore Notification Area settings _toggle_notification_area_icons(show_all=orig_hid_state, debug_img="%s_02" % (self.id()))
def send_message(self): timings.always_wait_until(10, 0.5, self.dlg['Nowa wiadomość e-mail'].exists) self.dlg['Nowa wiadomość e-mail'].Button.click() timings.wait_until(10, 0.5, self.app['Bez tytułu - Wiadomość (HTML) '].exists) self.snd_dlg = self.app['Bez tytułu - Wiadomość (HTML) '] addressee_input = self.snd_dlg['Edit4'] addressee_input.set_focus() keyboard.send_keys(self.addressee, with_spaces=True) subject_input = self.snd_dlg['Edit6'] subject_input.set_focus() keyboard.send_keys(self.subject, with_spaces=True) message_input = self.snd_dlg['Edit7'] message_input.set_focus() keyboard.send_keys(self.message, with_spaces=True) send_button = self.snd_dlg['Wyślij'] send_button.click()
def _toggle_notification_area_icons(show_all=True, debug_img=None): """ A helper function to change 'Show All Icons' settings. On a succesful execution the function returns an original state of 'Show All Icons' checkbox. The helper works only for an "English" version of Windows, on non-english versions of Windows the 'Notification Area Icons' window should be accessed with a localized title" """ Application().start(r'explorer.exe') class_name = 'CabinetWClass' def _cabinetwclass_exist(): "Verify if at least one active 'CabinetWClass' window is created" l = findwindows.find_elements(active_only=True, class_name=class_name) return (len(l) > 0) wait_until(_ready_timeout, _retry_interval, _cabinetwclass_exist) handle = findwindows.find_elements(active_only=True, class_name=class_name)[-1].handle window = WindowSpecification({'handle': handle, 'backend': 'win32', }) explorer = Application().connect(process=window.process_id()) cur_state = None try: # Go to "Control Panel -> Notification Area Icons" cmd_str = r'control /name Microsoft.NotificationAreaIcons' for _ in range(3): window.wait("ready", timeout=_ready_timeout) window.AddressBandRoot.click_input() explorer.wait_cpu_usage_lower(threshold=2, timeout=_ready_timeout) window.type_keys(cmd_str, with_spaces=True, set_foreground=True) # verfiy the text in the address combobox after type_keys finished cmbx_spec = window.AddressBandRoot.ComboBoxEx if cmbx_spec.exists(timeout=_ready_timeout, retry_interval=_retry_interval): texts = cmbx_spec.texts() if texts and texts[0] == cmd_str: break # Send ESCs to remove the invalid text window.type_keys("{ESC}" * 3) # Send 'ENTER' separately, this is to make sure # the window focus hasn't accidentally been lost window.type_keys( '{ENTER}', with_spaces=True, set_foreground=True ) explorer.wait_cpu_usage_lower(threshold=5, timeout=_ready_timeout) # Get the new opened applet notif_area = Desktop().window(title="Notification Area Icons", class_name=class_name) notif_area.wait("ready", timeout=_ready_timeout) cur_state = notif_area.CheckBox.get_check_state() # toggle the checkbox if it differs and close the applet if bool(cur_state) != show_all: notif_area.CheckBox.click_input() notif_area.Ok.click_input() explorer.wait_cpu_usage_lower(threshold=5, timeout=_ready_timeout) except Exception as e: if debug_img: from PIL import ImageGrab ImageGrab.grab().save("%s.jpg" % (debug_img), "JPEG") l = pywinauto.actionlogger.ActionLogger() l.log("RuntimeError in _toggle_notification_area_icons") raise e finally: # close the explorer window window.close() return cur_state
def launch_outlook(self): self.app = Application(backend='uia').start( r"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE") timings.wait_until(10, 0.5, self.app[f'Inbox — {self.sender} - Outlook'].exists) self.dlg = self.app[f'Inbox — {self.sender} - Outlook']
def save_vrscene(scene_num, _tid=tid): save_dlg = su.child_window(title='Save VRScene') logger.debug(save_dlg.texts()) edit_box = save_dlg.descendants(title='File name:', control_type='Edit')[0] logger.debug(edit_box) edit_box.set_edit_text(f"{PREFIX}{_tid}\\{_tid}{scene_num}") save_dlg.descendants(title='Save')[0].click_input() text = [ "Upgrading V-Ray components.\nThis file will not work with previous versions of V-Ray for SketchUp.", ] error = alert_handler(app, f'SS{_tid}{scene_num}.png', text) logger.debug(error) try: app.wait_cpu_usage_lower(threshold=0.1, timeout=1200 if offset == 0 else 2400, usage_interval=3.0) # RuntimeError logger.info('CPU<0.1') if su_is_responding(app.process): tm.wait_until(35, 3, os.access, path=f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene", mode=os.F_OK) logger.info('Vrscene file found') else: app.wait_cpu_usage_lower(threshold=1.0, timeout=1200 if offset == 0 else 2400, usage_interval=25.0) # RuntimeError logger.info('CPU<1') if su_is_responding(app.process): tm.wait_until( 35, 3, os.access, path=f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene", mode=os.F_OK) else: try: tm.wait_until( 24, 3, os.access, path=f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene", mode=os.F_OK) except tm.TimeoutError: logger.error( f"{tid}{scene_num}.vrscene has not been found. Error:", exc_info=True) raise RuntimeError( f"{tid}{scene_num}.vrscene has not been found.") except tm.TimeoutError: # Проц освободился, процесс не завис, но файла нет. Значит еще раз меню try: print('Second attempt to select menu') my_menu_select(su, app_menu) save_dlg = su.child_window(title='Save VRScene') logger.debug(save_dlg.texts()) edit_box = save_dlg.descendants(title='File name:', control_type='Edit')[0] logger.debug(edit_box) edit_box.set_edit_text(f"{PREFIX}{_tid}\\{_tid}{scene_num}") save_dlg.descendants(title='Save')[0].click() text = [ "Upgrading V-Ray components.\nThis file will not work with previous versions of V-Ray for SketchUp.", ] error = alert_handler(app, f'SS{_tid}{scene_num}.png', text) logger.debug(error) raise tm.TimeoutError except (tm.TimeoutError, pui.NoPatternInterfaceError): print('in exc block') try: app.wait_cpu_usage_lower( threshold=0.1, timeout=1200 if offset == 0 else 2400, usage_interval=3.0) logger.info('2:CPU<0.1') if su_is_responding(app.process): tm.wait_until( 80, 3, os.access, path=f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene", mode=os.F_OK) logger.info('Vrscene file found') else: app.wait_cpu_usage_lower( threshold=1.0, timeout=1200 if offset == 0 else 2400, usage_interval=25.0) # RuntimeError logger.info('2:CPU<1') if su_is_responding(app.process): tm.wait_until( 54, 3, os.access, path=f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene", mode=os.F_OK) else: try: tm.wait_until( 6, 3, os.access, path= f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene", mode=os.F_OK) except tm.TimeoutError: logger.error( f"{tid}{scene_num}.vrscene has not been found. Error:", exc_info=True) raise RuntimeError( f"{tid}{scene_num}.vrscene has not been found." ) except tm.TimeoutError as t_e: logger.error( f"{tid}{scene_num}.vrscene has not been found. Error:", exc_info=True) raise t_e time_out = 250 while time_out > 0: try: os.rename(f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene", f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene") logger.debug( f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene is free") break except PermissionError: time.sleep(2) time_out -= 2 logger.debug( f"{PREFIX}{tid}\\{tid}{scene_num}.vrscene is busy") else: logger.critical( f'Script did not wait end of .vrscene file saving.') raise TimeoutError('Manual')
通过在对象timings.Timings 中设置全局静态变量(等待时间),它可以单独根据您的需要进行调整 全局计时变量值的设置方法: Timings.defaults():将全局计时设置为默认值 Timings.slow() :将所有时间加倍(使脚本执行速度降低约2倍) Timings.fast():将所有计时除以2(快2倍) """ from pywinauto.timings import wait_until, Timings i = 0 def work(): global i i += 1 print("当前i的值为:", i) return i # 等work返回的结果为5的时候,继续往下执行 wait_until(10, 1, work, 5) print("等待通过") # 将等待的计时器设为默认值 Timings.Defaults() # 将等待时间加倍 Timings.Slow() # 将等待时间减半 Timings.Fast()
from appium import webdriver desktop = Desktop(backend="uia") nordlocker_app = Application() nordlocker_app.start('C:\\Program Files\\NordLocker\\NordLauncher.exe', timeout=10) connected_nordlocker = Application(backend="uia") try: connected_nordlocker.connect(title='NordLocker') except findwindows.WindowAmbiguousError: wins = findwindows.find_elements(active_only=True, title="NordLocker") connected_nordlocker.connect(handle=wins[0].handle) except findwindows.ElementNotFoundError: wait_until( 30, 0.5, lambda: len( findwindows.find_elements(active_only=True, title="NordLocker")) > 0) wins = findwindows.find_elements(active_only=True, title="NordLocker") connected_nordlocker.connect(handle=wins[0].handle) main_screen = connected_nordlocker.window(title='NordLocker') def timeoutError(): main_screen = connected_nordlocker.window(title='NordLocker') try: actionable_window = main_screen.wait("exists enabled visible ready", timeout=20) except TimeoutError as e: print("Baigesi sesijos laikas")
import json from pywinauto.application import Application from pywinauto import timings import pywinauto.mouse as mouse import pywinauto.keyboard as keyboard import time # with open("movies.json", "r") as input_file: # file = json.load(input_file) # print(file) app = Application(backend='uia').start( r"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE") timings.wait_until(10, 0.5, app['Inbox — [email protected] - Outlook'].exists) dlg = app['Inbox — [email protected] - Outlook'] # dlg.print_control_identifiers() # timings.wait_until(10, 0.5, dlg['Nowa wiadomość e-mail'].exists) # dlg['Nowa wiadomość e-mail'].Button.click() timings.always_wait_until(10, 0.5, dlg['Nowa wiadomość e-mail'].exists) dlg['Nowa wiadomość e-mail'].Button.click() # time.sleep(2) # print(app.windows()) timings.wait_until(10, 0.5, app['Bez tytułu - Wiadomość (HTML) '].exists) snd_dlg = app['Bez tytułu - Wiadomość (HTML) '] # snd_dlg.print_control_identifiers()