Beispiel #1
0
    def restart_type_2(self):
        # Wait for session results screen shows up
        time.sleep(9)
        self.get_focus()
        # Move to bottom of the menu
        cmd = '{UP}'
        for i in range(1,6):
            SendKeys(cmd)

        # Restart Btn is located at second bottom of the menu
        cmd = '{DOWN}'
        SendKeys(cmd)

        # Hit Return
        cmd = '{ENTER}'
        SendKeys(cmd)

        # Wait for confirmation popup shows up
        time.sleep(0.2)
        cmd = '{DOWN}'
        SendKeys(cmd)

        cmd = '{ENTER}'
        SendKeys(cmd)

        self.trigger_virtual_enter()

        return True
Beispiel #2
0
def main():
    count = 0

    Application().Start(cmd_line=u'control intl.cpl')
    app = Application().connect(title_re="Region")
    dlg = app.Region
    dlg.SystemLink2.Click()
    time.sleep(0.4)

    app2 = Application().connect(title_re="Language")
    dlg2 = app2.Language

    dlg2.SysListView32.Click(double=True)

    while count < 4:
        SendKeys('{VK_TAB}')
        time.sleep(0.1)
        count += 1

    SendKeys('{VK_RETURN}')  #Hits remove for Dvorak here

    dlg2.SaveButton.click()  #saves settings here

    SendKeys('%{F4}')
    time.sleep(0.4)
    SendKeys('%{F4}')
Beispiel #3
0
 def PSP(self):
     # паспорт
     self.select_popupmenu_item(self.obj_tree_path, "#12")  # Паспорт
     time.sleep(self.delay_win_active)
     # изменение марки
     self.psp_change_marka()
     # подтверждение сохранения паспорта
     self.app.TMessageForm.capture_as_image().save("PSP_SaveConfirm.bmp")
     self.app.TMessageForm.Button3.click()  # Да
     time.sleep(self.delay_win_active)
     # подтверждение сохранения марки
     self.app.TMessageForm.capture_as_image().save(
         "PSP_MarkaSaveConfirm.bmp")
     # TODO: в окне выводится название марки
     self.app.TMessageForm.Button2.click()  # Да
     time.sleep(self.delay_win_active)
     # инфо о существовании похожей марки (opt)
     if self.app.TMessageForm.exists(
     ) and self.app.TMessageForm.control_count() == 1:
         SendKeys("{ESC}")  # закрываем сообщение
         time.sleep(self.delay_win_active)
     # подтверждение изменения марок в замерах (opt)
     if self.app.TMessageForm.exists():
         self.app.TMessageForm.capture_as_image().save(
             "PSP_MarkaSaveInZamersConfirm.bmp")
         SendKeys("{ESC}")  # закрываем сообщение
     else:
         print("skip PSP_MarkaSaveInZamersConfirm.bmp")
Beispiel #4
0
def hibernate():

    # Open windows menu with power options WIN+X
    SendKeys("$X")

    # Navigate to hibernate option and select
    SendKeys("{VK_UP 2}{VK_RIGHT}{VK_DOWN}{ENTER}")
Beispiel #5
0
    def restart_type_1(self):
        self.trigger_virtual_esc()

        time.sleep(0.5)
        self.get_focus()
        # Move to bottom of the menu
        cmd = '{DOWN}'
        for i in range(1,11):
            SendKeys(cmd)

        # Restart Btn is located at second bottom of the menu
        cmd = '{UP}'
        SendKeys(cmd)

        # Hit Return
        cmd = '{ENTER}'
        SendKeys(cmd)

        # Wait for confirmation popup shows up
        time.sleep(0.2)
        cmd = '{DOWN}'
        SendKeys(cmd)

        cmd = '{ENTER}'
        SendKeys(cmd)

        return True
Beispiel #6
0
def acro(path):
    os.system('start acrobat ' + path + '/' + path + '.pdf')
    sleep(1)
    #Change the path to point to your acrobat. If you dont know what this is,please refer to readme file
    app = Application(backend='uia').connect(
        path=r"C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat")
    sleep(1)
    dlg = app.top_window()
    SendKeys("{VK_MENU}")
    sleep(1)
    SendKeys("f")
    sleep(1)
    SendKeys("t")
    sleep(1)
    SendKeys("s")
    sleep(1)
    SendKeys("e")
    sleep(2)
    dlg.save.click()
    sleep(3)
    dlg.close()
    sleep(3)
    #Change the path to point to your excel. If you don't have excel installed just uncomment this part.
    app = Application(backend='uia').connect(
        path=r"C:\Program Files (x86)\Microsoft Office\root\Office16\excel.exe"
    )
    dlg = app.top_window()
    dlg.close()
Beispiel #7
0
 def testAltModifier(self):
     """Make sure that alt modifier works"""
     clipboard.set_data('abc')
     # check alt via opening edit menu and paste text from clipboard
     SendKeys('%(e)')
     SendKeys('{ENTER}')
     received = self.receive_text()
     self.assertEquals('abc', received)
Beispiel #8
0
 def SF(self):
     # TODO: спец. функции. Желательно, чтобы меню "уходило" вверх - м.б. сместить окно в низ экрана
     self.ids.TreeView.get_item(
         self.rbmsr_tree_path).click_input(button="right")
     # Подшипники качения->Фактический зазор
     if self.app.PopupMenu.menu().item_count() > 21:
         self.app.PopupMenu.wrapper_object().highlight_and_capture(
             "#21->#2", "_SF_RB_Call.bmp", self.screen_rect)
         SendKeys("{ESC}{ESC}")  # закрываем меню
     else:
         print("skip SF_RB_Call.bmp")
         SendKeys("{ESC}")  # закрываем меню
Beispiel #9
0
 def __get_text(self):
     data = ''
     time.sleep(1)
     SendKeys('^a')
     SendKeys('^c')
     if sys.platform == 'win32':
         win32clipboard.OpenClipboard()
         data = win32clipboard.GetClipboardData()
         win32clipboard.CloseClipboard()
     else:
         data = clipboard.get_data()
     return data
Beispiel #10
0
 def Params_Reporter(self):
     # TODO: дефолтные параметры
     self.ids.menu_select("#1->#{}->#2".format(
         self.params_index))  # Сервис->Параметры->Формирование отчёта
     self.app.TSetupReporterForm.capture_as_image().save(
         "Params_Reporter_p1.bmp")
     SendKeys("{TAB}{TAB}{RIGHT}")  # переключаемся на закладку Колонтитулы
     self.app.TSetupReporterForm.capture_as_image().save(
         "Params_Reporter_p2.bmp")
     SendKeys("{RIGHT}")  # переключаемся на закладку Шрифт, поля
     self.app.TSetupReporterForm.capture_as_image().save(
         "Params_Reporter_p3.bmp")
     self.app.TSetupReporterForm.close_alt_f4()
Beispiel #11
0
 def receive_text(self):
     """Receive data from text field"""
     received = ' '
     if sys.platform == 'win32':
         received = self.ctrl.TextBlock()
     else:
         time.sleep(0.2)
         SendKeys('^a')
         time.sleep(0.2)
         SendKeys('^c')
         SendKeys('{RIGHT}')
         received = clipboard.get_data()
     return received
Beispiel #12
0
        def testModifiersForFewChars(self):
            """Make sure that repeated action works"""
            SendKeys("%(SC)", pause=.3)
            dlg = self.app.Window_(title='Using C++ Derived Class')
            dlg.Wait('ready')
            dlg.Done.CloseClick()
            dlg.WaitNot('visible')

            SendKeys("%(H{LEFT}{UP}{ENTER})", pause=.3)
            dlg = self.app.Window_(title='Sample Dialog with spin controls')
            dlg.Wait('ready')
            dlg.Done.CloseClick()
            dlg.WaitNot('visible')
Beispiel #13
0
 def quit(self):
     # esc
     SendKeys('{ESC}')
     # leave
     self.window.ClickInput(coords=(600, 440))
     # confirm
     self.window.ClickInput(coords=(570, 420))
Beispiel #14
0
    def testIncorrectCases(self):
        """Make sure that incorrect key sequences raise an exception"""
        self.assertRaises(KeySequenceError, SendKeys, "{ENTER")
        self.assertRaises(KeySequenceError, SendKeys, "ENTER)")
        self.assertRaises(RuntimeError, SendKeys, "%{Enterius}")
        self.assertRaises(KeySequenceError, SendKeys, "{PAUSE small}")

        try:
            SendKeys("{ENTER five}")
        except KeySequenceError as exc:
            self.assertEquals("invalid repetition count five", str(exc))

        try:
            SendKeys("ENTER}")
        except KeySequenceError as exc:
            self.assertEquals("`}` should be preceeded by `{`", str(exc))
Beispiel #15
0
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:
        SendKeys('{BACK ' + str(len(keys)) + '}')
Beispiel #16
0
 def Import_Params_Extra(self):
     treeview_element_colapse(self.ids.TreeView.tree_root())
     self.ids.menu_select("#1->#5")  # Сервис->Импорт
     self.app.TImportInitForm.Button1.click()  # Настройки
     time.sleep(self.delay_win_active)
     self.app.TImportSettingsForm.capture_as_image().save(
         "Import_Params_Extra.bmp")
     SendKeys("{ESC}{ESC}")  # закрываем меню
Beispiel #17
0
 def testNewlinesWithNewlines(self):
     """Make sure that with_newlines option works"""
     SendKeys("\t \t \t a~\tb\nc", pause=.5, with_newlines=True)
     received = self.receive_text()
     if sys.platform == 'win32':
         self.assertEquals("a\r\nb\r\nc", received)
     else:
         self.assertEquals("a\nb\nc", received)
Beispiel #18
0
def choose_jijin_in_list(srclist,
                         selectlist,
                         jijinCurrent,
                         currentflag=False,
                         startflag=False):
    from pywinauto.keyboard import SendKeys
    from time import sleep
    try:
        dict = {}
        list = []
        number = 1
        current_number = 0
        for index in srclist:
            if jijinCurrent == index:
                current_number = number
            dict[index] = number
            number += 1
        if startflag is True:
            current_number = 1
        if currentflag is False:
            list.append(dict[jijinCurrent] - current_number)
        #匹配要选择的列表
        for index in selectlist:
            if dict.get(str(index)) is not None:
                list.append(dict[index] - current_number)
        current = 0
        for v in list:
            last_pose = v
            v -= current
            current = last_pose
            while v != 0:
                if v > 0:
                    SendKeys("{DOWN}")
                    v -= 1
                else:
                    SendKeys("{UP}")
                    v += 1
                sleep(0.5)
            SendKeys("{SPACE}")
            sleep(0.5)
            SendKeys("{ESC}")
            sleep(0.5)
    except Exception:
        None
Beispiel #19
0
 def Params(self, first: str, pages=None):
     # Params_Common{}.bmp
     # Params_Common2{}.bmp
     # Params_RB{}.bmp
     # Params_UserPointNames{}.bmp
     # TODO: дефолтные параметры
     # TODO: у TransVS, StatorTG, RF и FreeFormat параметр Использовать стандартные обозначения точек... выключен
     # по умолчанию
     self.ids.menu_select("#1->#{}->#0".format(
         self.params_index))  # Сервис->Параметры->Общие
     self.app.TParamsForm.capture_as_image().save("{}.bmp".format(first))
     if pages is not None and isinstance(pages, list) and len(pages) > 0:
         SendKeys("{TAB}{TAB}")  # подготавливаемся к переключению закладок
         for p in pages:
             SendKeys("{RIGHT}")  # переключаемся на следующую закладку
             time.sleep(self.delay_win_active)
             self.app.TParamsForm.capture_as_image().save(
                 "{}.bmp".format(p))
     self.app.TParamsForm.close_alt_f4()
Beispiel #20
0
 def Params_RB_ExtraVibroLevels(self):
     self.ids.menu_select("#1->#{}->#0".format(
         self.params_index))  # Сервис->Параметры->Общие
     SendKeys(
         "{TAB}{TAB}{RIGHT}{RIGHT}")  # переключаемся на закладку Подшипники
     self.app.TParamsForm["...TBitBtn"].click()
     time.sleep(self.delay_win_active)
     # TODO: дефолтные параметры
     self.app.TParams_RB_PowerInBandsForm.capture_as_image().save(
         "Params_RB_ExtraVibroLevels.bmp")
     self.app.TParams_RB_PowerInBandsForm.close_alt_f4()
     self.app.TParamsForm.close_alt_f4()
Beispiel #21
0
def main():
    count = 0

    Application().Start(cmd_line=u'control intl.cpl')
    app = Application().connect(title_re="Region")
    dlg = app.Region
    dlg.SystemLink2.Click()
    time.sleep(0.4)

    app2 = Application().connect(title_re="Language")
    dlg2 = app2.Language
    dlg2.SysListView32.Click(double=True)

    while count < 2:
        SendKeys('{VK_TAB}')
        time.sleep(0.1)
        count += 1
    SendKeys('{VK_RETURN}')  #add input method

    while count < 8:
        SendKeys('{VK_DOWN}')
        count += 1
        time.sleep(0.1)
    SendKeys('{VK_RETURN}')  #Selects Dvorak in layout choices

    dlg2.SaveButton.click()  #saves settings

    SendKeys('%{F4}')
    time.sleep(0.4)
    SendKeys('%{F4}')
Beispiel #22
0
 def Params_SignalsShow(self):
     self.ids.menu_select("#1->#{}->#1".format(
         self.params_index))  # Сервис->Параметры->Просмотр сигналов
     self.app.TGrafSetups_Params_Form.Button9.click(
     )  # По умолчанию (дефолтные параметры)
     self.app.TGrafSetups_Params_Form.capture_as_image().save(
         "Params_SignalsShow.bmp")
     SendKeys(
         "{TAB}{TAB}{RIGHT}"
     )  # переключаемся на закладку Параметры 2 с кнопки По умолчанию
     self.app.TGrafSetups_Params_Form.capture_as_image().save(
         "Params_SignalsShow_p2.bmp")
     self.app.TGrafSetups_Params_Form.close_alt_f4()
Beispiel #23
0
    def __run_NormalCharacters_with_options(self, **args):
        """Make sure that sending any character in range """
        #unused var: missed = []
        for i in range(32, 127):

            # skip characters that must be escaped
            if chr(i) in '~!@#$%^&*()_+{}|:"<>? ':
                continue

            SendKeys(chr(i), pause=.001, **args)
            received = self.receive_text()[-1]

            self.assertEquals(i, ord(received))
Beispiel #24
0
    def restart_type_3(self):
        time.sleep(7)

        self.get_focus()
        cmd = '{UP}'
        for i in range(0,3):
            SendKeys(cmd)

        cmd = '{DOWN}'
        SendKeys(cmd)

        # Hit Return
        cmd = '{ENTER}'
        SendKeys(cmd)

        time.sleep(0.2)
        cmd = '{DOWN}'
        SendKeys(cmd)

        cmd = '{ENTER}'
        SendKeys(cmd)

        return True
Beispiel #25
0
 def ZamerReg_SVK(self):
     self.select_popupmenu_item(self.rb_tree_path,
                                "#2")  # Добавить измерение
     time.sleep(7)  # идёт инициализация АЦП
     if self.app.TMessageForm.exists():
         # нет АЦП, условий в МВИ и т.п.
         print("skip ZamerReg_SVK.bmp")
         SendKeys("{ESC}")  # закрываем сообщение
     else:
         # ищем без best_match, на случай если юзер сам закрыл окно предупреждения
         self.app.window(class_name="TSVKSignalForm").capture_as_image(
         ).save("ZamerReg_SVK.bmp")
         self.app.TSVKSignalForm.close_alt_f4()
         self.app.wait_cpu_usage_lower()
Beispiel #26
0
 def Zamer_Cascade(self):
     self.select_popupmenu_item(self.rb_tree_path,
                                "#15")  # Просмотр каскада
     time.sleep(self.delay_win_active)
     self.app.TShowCascadeInitForm.capture_as_image().save(
         "_Zamer_Cascade_SelectFiles{}.bmp".format(self.suffix))
     # TODO: выбрать замеры
     self.app.TShowCascadeInitForm.Button2.click()  # Просмотр
     if self.app.TMessageForm.exists():
         print("skip Zamer_Cascade{}.bmp".format(self.suffix))
         SendKeys("{ESC}")  # закрываем сообщение
         self.app.TShowCascadeInitForm.close_alt_f4()
     else:
         self.app.TShowCascadeForm.capture_as_image().save(
             "Zamer_Cascade{}.bmp".format(self.suffix))
         self.app.TShowCascadeForm.close_alt_f4()
Beispiel #27
0
 def saveAs(self, param):
     if (param == "sublime"):
         self.menu_item = self.pxwindowclass.MenuItem(
             u'&File->Save &As\u2026\tCtrl+Shift+S')
         self.menu_item.ClickInput()
         SendKeys('{ENTER 2}')
     elif (param == "notepad"):
         self.app.notepad.menu_select("File->SaveAs")
         self.app.SaveAs.EncodingComboBox.select("UTF-8")
         self.app.SaveAs.edit1.set_edit_text("Example-utf8.txt")
         self.app.SaveAs.Save.close_click()
     elif (param == "paint"):
         pass
     elif (param == "notepad"):
         pass
     else:
         pass
Beispiel #28
0
def user_double_click(text):
    time.sleep(0.5)
    img = PIL.ImageGrab.grab()
    #imgplot = plt.imshow(img)
    data = pytesseract.image_to_data(img)

    data = data.split()
    #print(data)
    draw = ImageDraw.Draw(img)
    coords_list = []
    count = 1
    '''for i in range(len(data)):
        if ' '.join(text) in data[i].lower():
            print("Match Found")
            #coord_x = int(data[i-5]) + int(data[i-3]/2)
            #coord_y = int(data[i-4]) + int(data[i-2]/2)
            coord_x = int(data[i-5]) + int(int(data[i-3])/2)
            coord_y = int(data[i-4]) + int(int(data[i-2])/2)
            mouse.double_click(button="left",coords=(coord_x,coord_y))
            print("Double Clicked at: (" ,coord_x,",", coord_y,")")
            break'''
    for i in range(len(data)):
        if ' '.join(text) in data[i].lower():
            print("Match Found")
            coord_x = int(data[i - 5]) + int(int(data[i - 3]) / 2)
            coord_y = int(data[i - 4]) + int(int(data[i - 2]) / 2)
            draw.text((coord_x, coord_y),
                      str(count),
                      fill="rgb(240,0,0)",
                      font=font)
            coords_list.append((coord_x, coord_y))
            count += 1

    #if count>2:
    img.show()
    img.save("./images/image.png")
    winsound.Beep(frequency, duration)
    # if voice_cmd:
    im_no = str(speech.press_record())
    # else:
    #   im_no = int(input("Enter The number of image to select: "))
    #   time.sleep(2)
    #print(im_no)
    SendKeys("%{F4}")
    time.sleep(1)
    mouse.double_click(button='left', coords=(coords_list[int(im_no) - 1]))
Beispiel #29
0
 def Import_Manual(self):
     treeview_element_colapse(self.ids.TreeView.tree_root())
     self.ids.menu_select("#1->#5")  # Сервис->Импорт
     self.app.TImportInitForm["...Button"].click()  # выбор файла
     self.app.DialogEdit.Edit.set_edit_text(self.import_file)
     self.app.DialogEdit.Button1.click_input()  # Открыть
     if self.app.DialogEdit.exists() or self.app.Dialog.exists():
         # ошибка открытия файла (иногда окно предупреждения не появляется)
         print("skip Import_Manual{}.bmp".format(self.suffix))
         time.sleep(3)  # чтобы успеть увидеть сообщение ))
         SendKeys("{ESC}{ESC}{ESC}")  # закрываем все окна вплоть до IDS
     else:
         self.app.TImportInitForm.Button3.click()  # Ok
         self.app.wait_cpu_usage_lower()
         self.app.TImportTreeForm.move_window(450, 270, 330,
                                              300)  # в границах IDS, справа
         self.ids.capture_as_image().save("Import_Manual{}.bmp".format(
             self.suffix))
         self.app.TImportTreeForm.close_alt_f4()
Beispiel #30
0
 def Diagnoz_RB(self):
     self.select_popupmenu_item(self.rbmsr_tree_path, "#17")  # Диагностика
     time.sleep(self.delay_win_active)
     if self.app.TMessageForm.exists():
         if self.app.TMessageForm.control_count() == 2:
             # предупреждение о нормах и т.п.
             self.app.TMessageForm.Button2.click()  # Да
             time.sleep(self.delay_win_active)
         else:
             # ошибка диагностики
             SendKeys("{ESC}")  # закрываем сообщение
     if self.app.TRollingBearing_DiagnosForm.exists():
         self.app.TRollingBearing_DiagnosForm.capture_as_image().save(
             "Diagnoz_RB.bmp")
         # TODO: картинки примеров отчётов (из браузера)
         # self.app.TRollingBearing_DiagnosForm.TBitBtn1.click()  # Отчёт
         self.app.TRollingBearing_DiagnosForm.close_alt_f4()
     else:
         print("skip Diagnoz_RB.bmp")