def kill_program(title: str or list, backend: str = "win32", time: int = 10) -> None: """ 链接自启动的程序并关闭 :param time: 链接程序等待时间 :param backend: win32 or uia :param title: 自启动程序的窗口标题名 :return: None """ if type(title) is str: # 结束的进程只有单个标题 while time: try: temp = Application(backend=backend).connect(title=title) except: sleep(1) time -= 1 else: # 未抛出异常时说明程序成功启动 temp.kill() break else: # 结束的进程有多个标题 while time: for each in title: try: temp = Application().connect(title=each) except: if time <= 0: break else: sleep(1) time -= 1 else: temp.kill() time = 0 break
def pr_crack(): step = { 0: ["Adobe Acrobat DC", "TsEdit", "Adobe Prelude CC 2015", 'edit', 10], 1: [ "V7{}AcrobatCont-12-Win-GM", "TsEdit", "V7{}Prelude-4-Win-GM", 'edit', 10 ], 2: ["15.7.0", "TsEdit", "4.0.0", 'edit', 10], 3: ["Install", "TButton", 'click', 10], 4: [ "", "Edit", r"C:\Program Files\Adobe\Adobe Premiere Pro CC 2018\amtlib.dll", 'edit', 10 ], 5: ["打开(&O)", "Button", 'click', 10] } pr_cra = Application().start(join(getcwd(), "app_pkg", 'PRCC2018', 'crack')) for i in range(len(step)): next_step = pr_cra.top_window().child_window( title=step[i][0], class_name=step[i][1]).wait('ready', timeout=step[i][-1]) if step[i][-2] == 'click': next_step.click_input() if i in [3, 5]: sleep(1) elif step[i][-2] == 'edit': next_step.set_text(step[i][2]) pr_cra.kill()
def notepad(): notepad = Application().start('notepad.exe') yield notepad # Clear Notepad's contents to prevent any save prompts. notepad.UntitledNotepad.Edit.type_keys('^A{DEL}') notepad.kill()
def word_automate(list_file): #Запуск приложения MS Word count = 1 for item in list_file: app = Application(backend="uia").start( r"C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE") #Получение UI и взаимодейсвие # Открытие документа app.Dialog.ListItem3.click_input() app.Dialog.BrowseButton.click_input() app.Dialog.Open.Edit49.type_keys(item) app.Dialog.Open.OpenSplitButton.click_input() # Новый документ ## app.Dialog.ListItem7.click_input() #Переход на новый интерфейс app = Application(backend="uia").connect(path="WINWORD.exe", title="Document1 - Word") app.Dialog.set_focus() #Нажимаем на клавишу "File" app.Dialog.FileTab.click() #Нажимаем на клавишу "Save As" app.Dialog.SaveAsListItem.click_input() #Нажимаем на клавишу "Browse" app.Dialog.BrowseButton.click_input() #Проверяем на существование файла, если True, то его удаляем if os.path.isfile(path + 'file{i}'.format(i=str(count)) + '.docx'): os.remove(path + 'file{i}'.format(i=str(count)) + '.docx') #Сохранениие докуента Sub = app.Dialog.child_window(title_re="Save As", class_name="#32770") Sub.FileNameCombo.type_keys(path + 'file{i}'.format( i=str(count)).replace('.docx', '')) Sub.Save.click() try: app.Dialog.MicrosoftWord.OK.click() except: print('Word cохранил проект в более нововой версии!!!') while 1 == 1: if os.path.isfile(path + 'file{i}'.format(i=str(count)) + '.docx'): #Закрытие приложенния MS Word app.kill() break else: time.sleep(1) count += 1
def VPNConnect(): try: con_orig = Application().connect(title=u'VPN Connect - 119.147.211.38', timeout=1) con_orig.kill() except: pass conf = configparser.ConfigParser() conf.read("./conf.ini") App_dir = conf.get('config', 'dir') un = conf.get('config', 'username') pw = conf.get('config', 'password') app = Application().start(cmd_line=App_dir) shrewsoftacc = app.SHREWSOFT_ACC shrewsoftacc.wait('ready') syslistview = shrewsoftacc[u'ListView119.147.211.38'] listview_item = syslistview.get_item(u'119.147.211.38') listview_item.click() toolbarwindow = shrewsoftacc[u'Toolbar'] toolbar_button = toolbarwindow.button(u'Connect') toolbar_button.click() con = Application().connect(title=u'VPN Connect - 119.147.211.38', timeout=2) shrewsoftcon = con.SHREWSOFT_CON User = shrewsoftcon.Edit User.type_keys(un) Password = shrewsoftcon.Edit2 Password.type_keys(pw) Connect = shrewsoftcon.Button Connect.click() app.kill()
def ps_crack(): step = { 0: ["Adobe Acrobat DC", "TsEdit", "Adobe Photoshop CC 2017", 'edit', 10], 1: [ "V7{}AcrobatCont-12-Win-GM", "TsEdit", "V7{}Photoshop-18-Win-GM", 'edit', 10 ], 2: ["15.7.0", "TsEdit", "18.0.0", 'edit', 10], 3: ["Music", "TsCheckBox", 'click', 10], 4: ["Install", "TButton", 'click', 10], 5: [ "", "Edit", r"C:\Program Files\Adobe\Adobe Photoshop CC 2018\amtlib.dll", 'edit', 10 ], 6: ["打开(&O)", "Button", 'click', 10] } ps_cra = Application().start(join(getcwd(), "app_pkg", 'PSCC2018', 'crack')) for i in range(len(step)): try: next_step = ps_cra.top_window().child_window( title=step[i][0], class_name=step[i][1]).wait('ready', timeout=step[i][-1]) except RuntimeError: break else: if step[i][-2] == 'click': next_step.click_input() if i in [4, 6]: sleep(1) elif step[i][-2] == 'edit': next_step.set_text(step[i][2]) ps_cra.kill()
def auto_install(self): choose = self.choose start_time = (strftime("%H:%M", localtime())) # 获取运行程序时的开始时间 failure = [] # 保存安装失败的软件名称 menu = load_menu() # 读取安装目录下的menu.txt获取需要安装的文件 menu_change = menu.copy() for each in menu: labelframe1 = tk.LabelFrame(self.root, text=f'安装进度(第{menu.index(each) + 1}个,共{len(menu)}个)', height=80, width=300) # 信息区 labelframe1.grid(row=1, column=0, columnspan=10, padx=10, pady=10) labelframe1.propagate(0) # 使组件大小不变,此时width才起作用 tk.Label(labelframe1, text=f"正在安装{format_menu(each.split())[0]}...", font=(', 11')).pack(fill="both", expand="yes") if each == 'QQ': main_window = ["腾讯QQ安装向导", "win32", "QQ"] step = {0: ["自定义选项", 'click', 15], 1: ["添加到快速启动栏", 'click', 6], 2: ["开机自动启动", 'click', 6], 3: ['', 'edit', 6], 4: ["立即安装", 'click', 6], 5: ["完成安装", 'click', 40]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'QQ', 'QQ.exe')) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=3): kill_program(main_window[2]) # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'Wechat': main_window = ["微信安装向导", "uia", "微信"] step = {0: ["更多选项", 'click', 40], 1: ["程序安装目录", 'edit', 6], 2: ["安装微信", 'click', 6], 3: ['开始使用', 'click', 40]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'wechat', 'wechat.exe')) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each)): kill_program(main_window[2]) # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'Dtalk': main_window = ["钉钉 安装", "win32"] step = {0: ["下一步(&N) >", 'click', 50], 1: ["", 'edit', 6], 2: ["下一步(&N) >", 'click', 6], 3: ["运行 钉钉(&R)", 'click', 40], 4: ["完成(&F)", 'click', 6]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'Dtalk', 'Dtalk.exe')) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=1): # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'Winrar': main_window = ["WinRAR 5.91", "win32", 10] step = {0: ["", "Edit", 'edit', 6], 1: ["安装", "Button", 'click', 6]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'Winrar', 'Winrar.exe')) sleep(2) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=0, special=True): time = 6 while time >= 0: try: temp = Application().connect(title="WinRAR 简体中文版安装") except: sleep(1) time -= 1 else: # 未抛出异常时说明程序成功链接 for button in ["确定", "完成"]: temp2 = temp.window(title='WinRAR 简体中文版安装').child_window(title=button).wait('ready', timeout=30) temp2.click() break # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'LMsoft': main_window = 'uia' step = {0: ["原创工具", 'click', 10], 1: ["流氓软件免疫", 'click', 5], 2: ["一键免疫", 'click', 8], 3: ["确定", 'click', 3], 4: ["确定", 'click', 10] } sleep_time = [1, 5, 2, 5, 2] program = Application(backend=main_window).start( join(getcwd(), 'app_pkg', each, each)) if install_from_topwindow(window_backend=main_window, step=step, program=program, install_path=join(choose, each), sleep_time=sleep_time): program.kill() txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) if each in ['VCRedist', 'DX', 'NF3']: main_window = "win32" step = {0: ["确定", 'click', 10], 1: ["是(&Y)", 'click', 10]} sleep_time = [1, 0] program = Application(backend=main_window).start( join(getcwd(), 'app_pkg', each, each)) if install_from_topwindow(window_backend=main_window, step=step, program=program, install_path=join(choose, each), sleep_time=sleep_time): ok_dict = {'DX': 'DirectX 9.0c 安装完成!程序即将退出', 'VCRedist': 'Visual C++ 运行库 安装完成!程序即将退出', 'NF3': '.Net Framework 安装完成!程序即将退出'} # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) time = 60 while time >= 0: try: if program.window(title_re='信息').child_window(title=ok_dict[each]).exists(): break except: sleep(1) time -= 1 program.window(title_re='信息').child_window( title=ok_dict[each]).wait('ready', timeout=80) program.window(title_re='信息').child_window( title="确定").click_input() else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == 'OFFICE2013': main_window = [ "Microsoft Office Professional Plus 2013", "uia"] step = {0: ["我接受此协议的条款", "CheckBox", 'click', 20], 1: ["继续", "Button", 'click', 6], 2: ["自定义", "Button", 'click', 6], 3: ["Microsoft Access", "MenuItem", 'click', 6], 4: ["不可用", "Button", 'click', 6], 5: ["Microsoft InfoPath", "MenuItem", 'click', 6], 6: ["不可用", "Button", 'click', 6], 7: ["Microsoft Lync", "MenuItem", 'click', 6], 8: ["不可用", "Button", 'click', 6], 9: ["Microsoft OneNote", "MenuItem", 'click', 6], 10: ["不可用", "Button", 'click', 6], 11: ["Microsoft Outlook", "MenuItem", 'click', 6], 12: ["不可用", "Button", 'click', 6], 13: ["Microsoft Publisher", "MenuItem", 'click', 6], 14: ["不可用", "Button", 'click', 6], 15: ["Microsoft SkyDrive Pro", "MenuItem", 'click', 6], 16: ["不可用", "Button", 'click', 6], 17: ["Microsoft Visio Viewer", "MenuItem", 'click', 6], 18: ["不可用", "Button", 'click', 6], 19: ["文件位置", "TabItem", 'click', 6], 20: ["", "Edit", 'edit', 10], 21: ["立即安装", "Button", 'click', 6]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', 'OFFICE2013', 'setup.exe')) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=20, special=True): program.window(title_re='Microsoft Office Professional Plus 2013').child_window(title="继续联机", control_type="Button" ).wait('ready', timeout=600) program.window(title_re='Microsoft Office Professional Plus 2013')[ '关闭Button'].click_input() # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) office_crack(choose) # 激活office else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == "WPS": sleep_time = [5, 1, 1, 1] # 各图片的等待时间 grayscale = [True, True, True, False] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [-200, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", 'WPS', 'wpssetup_k56008174_281235.exe')) # 打开指定的安装程序 png_file_name = "_shot" if system_info() == "10" else "_shot_win7" result = install_from_png(app_name=each, edit_index=2, png_file_name=png_file_name, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) if each == '360drv': main_window = ["欢迎使用 360驱动大师", "uia"] step = {0: ["已经阅读并同意", 'CheckBox', 'click', 10], 1: ["", 'Edit', 'edit', 6], 2: ["安装完成后打开360驱动大师", 'CheckBox', 'click', 6], 3: ["立即安装", 'Button', 'click', 6]} sleep_time = [3] # 各图片的等待时间 grayscale = [True] # 各图片是否使用灰度搜索 skewing = [[0, 0]] # x、y坐标偏移 program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', each, each)) result = install_from_png(app_name=each, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing) # 第一个按钮获取不到用png图片匹配 if result: if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=1, special=True): # 图片匹配成功后再用pywinauto控制 txt_change(prom_name=each, menu_change=menu_change) else: # 安装失败记录安装失败程序 failure.extend(format_menu(each.split())) else: failure.extend(format_menu(each.split())) if each == "Chrome": program = Application(backend='win32').start( join(getcwd(), 'app_pkg', each, each)) txt_change(prom_name=each, menu_change=menu_change) while True: if not program.is_process_running(): break kill_program("欢迎使用 Chrome - Google Chrome") if each == "2345explorer": sleep_time = [5, 1] # 各图片的等待时间 grayscale = [False, False] # 各图片是否使用灰度搜索 skewing = [[300, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, '2345explorer_k56008174.exe')) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=0, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) kill_program(title=['2345网址导航-开创中国百年品牌(已创建11年整) - 2345加速浏览器 10.14', '网络不稳定或断网 - 2345加速浏览器 10.14'], time=30) else: failure.extend(format_menu(each.split())) if each == "TXvideo": main_window = ["腾讯视频 2020 安装程序 ", "win32"] step = {0: ["自定义安装", 'click', 30], 1: ["开机自动启动", 'click', 6], 2: ["", 'edit', 6], 3: ["立即安装", 'click', 8], 4: ["立即体验", 'click', 90]} program = Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', each, each)) if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=2): # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) kill_program(title='腾讯视频') else: failure.extend(format_menu(each.split())) # 安装失败记录安装失败程序 if each == "IQIYI": main_window = ["爱奇艺 安装向导", "win32"] step = {0: ["阅读并同意", 'click', 30], 1: ["", 'edit', 6], 2: ["立即安装", 'click', 6], 3: ["完成", 'click', 90]} Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', each, 'iqiyi_k56008174_107328.exe')) time = 5 while time >= 0: try: program = Application(backend=main_window[1]).connect( title_re=main_window[0]) # 直接打开的程序对象不能直接使用需要重新链接 except: sleep(1) time -= 1 else: if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=1): # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: # 安装失败记录安装失败程序 failure.extend(format_menu(each.split())) break if each == "PSCS3": main_window = ["安装 - Adobe Photoshop CS3 Extended", "win32"] step = {0: ["下一步(&N) >", "TButton", 'click', 10], 1: [r"C:\Program Files (x86)\Adobe\Adobe Photoshop CS3", "TEdit", 'edit', 6], 2: ["下一步(&N) >", "TButton", 'click', 6], 3: ["下一步(&N) >", "TButton", 'click', 6], 4: ["安装(&I)", "TButton", 'click', 6], 5: ["完成(&F)", "TButton", 'click', 60]} Application(backend=main_window[1]).start( join(getcwd(), 'app_pkg', each, each)) time = 5 while time >= 0: try: program = Application(backend=main_window[1]).connect( title='安装') # 直接打开的程序对象不能直接使用需要重新链接 except: sleep(1) time -= 1 else: if install(main_window=main_window[0], window_backend=main_window[1], step=step, program=program, install_path=join(choose, each), edit_value=100, special=True): # 安装成功修改menu文件 txt_change(prom_name=each, menu_change=menu_change) else: # 安装失败记录安装失败程序 failure.extend(format_menu(each.split())) break if each == "PSCC2018": # PSCC2018打开自动安装不需要任何按钮 if "PSCS3" in menu: # 防止装完PSCS3马上打开程序报错 sleep(5) ps_path = join(getcwd(), "app_pkg", each, 'Set-up') copy(ps_path) hotkey('win', 'r') hotkey('ctrl', 'v') hotkey('enter') time = 10 while time >= 0: try: ps_cc = Application().connect(path=paste()) except: sleep(1) time -= 1 else: break while True: if not ps_cc.is_process_running(): break else: sleep(2) txt_change(prom_name=each, menu_change=menu_change) kill_program(title='Adobe Photoshop CC 2018') ps_crack() if each == "PRCC2018": # PRCC2018打开自动安装不需要任何按钮 pr_path = join(getcwd(), "app_pkg", each, 'Set-up') copy(pr_path) hotkey('win', 'r') hotkey('ctrl', 'v') hotkey('enter') time = 10 while time >= 0: try: pr_cc = Application().connect(path=paste()) except: sleep(1) time -= 1 else: break while True: if not pr_cc.is_process_running(): break else: sleep(2) txt_change(prom_name=each, menu_change=menu_change) kill_program(title='Adobe Premiere Pro CC 2018') pr_crack() if each == "163music": sleep_time = [5, 1, 1, 1, 1, 5] # 各图片的等待时间 grayscale = [True, True, True, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [0, 0], [-230, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, each)) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=3, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) time = 5 while time >= 0: try: Application(backend='uia').connect(title='网易云音乐') except: sleep(1) time -= 1 else: system('taskkill /IM cloudmusic.exe /F') sleep(3) break else: failure.extend(format_menu(each.split())) if each == "QQmusic": sleep_time = [5, 1, 1, 1, 5] # 各图片的等待时间 grayscale = [True, True, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [-230, 0], [0, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, 'QQMusic_YQQFullStack')) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=2, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) kill_program(title='QQ音乐', backend='uia') else: failure.extend(format_menu(each.split())) if each == "Kugou": sleep_time = [5, 1, 1, 1, 1, 1, 10] # 各图片的等待时间 grayscale = [True, True, True, True, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [-250, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, 'kugou_k56008174_306395')) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=1, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) kill_program(title='酷狗音乐', backend='uia') else: failure.extend(format_menu(each.split())) if each == "Xunlei": sleep_time = [3, 3] # 各图片的等待时间 grayscale = [True, True] # 各图片是否使用灰度搜索 skewing = [[-50, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, each)) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=0, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) kill_program(title='迅雷', backend='uia') else: failure.extend(format_menu(each.split())) if each == "SougouPY": sleep_time = [5, 1, 1, 1, 1, 8] # 各图片的等待时间 grayscale = [True, True, True, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [0, 0], [ 70, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, each)) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=3, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) if each == "2345pinyin": sleep_time = [5, 1, 1, 10] # 各图片的等待时间 grayscale = [False, True, True, True] # 各图片是否使用灰度搜索 skewing = [[50, 0], [0, 0], [0, 0], [0, 0]] # x、y坐标偏移 Application().start(join(getcwd(), "app_pkg", each, '2345pinyin_k56008174.exe')) # 打开指定的安装程序 result = install_from_png(app_name=each, edit_index=0, confidence=0.8, install_path=choose, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, paste_identi=True) # 采用全图片匹配 if result: txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) if each == "3DMAX2014": step = {0: ["ListBox3", 'click', 30], 1: ["我接受Button", 'click', 6], 2: ["下一步Button", 'click', 6], 3: ["序列号:Edit", '666', 'edit', 6], 4: ["Edit2", '69696969', 'edit', 6], 5: ["产品密钥:Edit5", '128F1', 'edit', 6], 6: ["下一步Button", 'click', 6], 7: ["安装路径:Edit", join(choose, each), 'edit', 6], 8: ["安装Button", 'click', 6]} setup_path = join(getcwd(), "app_pkg", each, "Setup.exe") copy(setup_path) hotkey('win', 'r') hotkey('ctrl', 'v') hotkey('enter') time = 20 while time >= 0: try: program = Application().connect(title="Autodesk 3ds Max 2014") except: sleep(1) time -= 1 else: break if simple_install(window_backend='win32', step=step, program=program): while True: try: temp = Application().connect(title_re='文件正在使用') if temp.top_window().window(title='忽略(&I)').exists(): temp.top_window()['忽略(&I)'].click_input() except: pass if program.top_window().child_window(title="完成").exists(): program.top_window().child_window(title="完成").wait("ready", timeout=10) program.top_window()['完成'].click_input() txt_change(prom_name=each, menu_change=menu_change) break else: sleep(3) cra_3dmax(choose, each) else: failure.extend(format_menu(each.split())) if each == "CAD2014": step = {0: ["ListBox3", 'click', 30], 1: ["我接受Button", 'click', 6], 2: ["下一步Button", 'click', 6], 3: ["序列号:Edit", '666', 'edit', 6], 4: ["Edit2", '69696969', 'edit', 6], 5: ["产品密钥:Edit5", '001F1', 'edit', 6], 6: ["下一步Button", 'click', 6], 7: ["安装路径:Edit", join(choose, each), 'edit', 6], 8: ["安装Button", 'click', 6]} setup_path = join(getcwd(), "app_pkg", each, "Setup.exe") copy(setup_path) hotkey('win', 'r') hotkey('ctrl', 'v') hotkey('enter') time = 20 while time >= 0: try: program = Application().connect(title="Autodesk® AutoCAD® 2014") except: sleep(1) time -= 1 else: break if simple_install(window_backend='win32', step=step, program=program): while True: try: temp = Application().connect(title_re='文件正在使用') if temp.top_window().window(title='忽略(&I)').exists(): temp.top_window()['忽略(&I)'].click_input() except: pass if program.top_window().child_window(title="完成").exists(): program.top_window().child_window(title="完成").wait("ready", timeout=10) program.top_window()['完成'].click_input() txt_change(prom_name=each, menu_change=menu_change) break else: sleep(3) cra_3dmax(choose, each) else: failure.extend(format_menu(each.split())) if each == "CAD2007": program = Application().start(join(getcwd(), "app_pkg", each, 'setup')) if program.top_window()['确定Button'].wait("ready", timeout=10) and program.top_window()[ '确定Button'].exists(): sleep(1) program.top_window()['确定Button'].click_input() time = 10 while time >= 0: try: program = Application().connect(title="AutoCAD 2007 安装") except: sleep(1) time -= 1 else: break step = {0: ["Button2", 'click', 10], 1: ["RadioButton2", 'click', 6], 2: ["Button0", 'click', 6], 3: ["Edit1", '000', 'edit', 6], 4: ["Edit2", '00000000', 'edit', 6], 5: ["Button1", 'click', 6], 6: ["Edit1", "admin", 'edit', 6], 7: ["Edit2", "admin", 'edit', 6], 8: ["Edit3", "admin", 'edit', 6], 9: ["Edit4", "admin", 'edit', 6], 10: ["Edit5", "admin", 'edit', 6], 11: ["Button1", "click", 6], 12: ["Button1", "click", 6], 13: ["Button1", "click", 6], 14: ["Edit", join(choose, each), 'edit', 6], 15: ["Button1", "click", 6], 16: ["Button1", "click", 6], 17: ["Button1", "click", 6]} sleep_time = [1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 3, 3, 0, 3, 3, 3] if simple_install(window_backend="win32", step=step, program=program, sleep_time=sleep_time): sleep(5) try: Application().connect(title="AutoCAD 2007 安装程序") except: failure.extend(format_menu(each.split())) break sleep(2) time = 300 while time >= 0: try: program = Application().connect(title="AutoCAD 2007 安装程序") if program.top_window()['完成(&F)'].exists(): break except: sleep(1) time -= 1 step = {0: ["CheckBox", 'click', 8], 1: ["Button1", 'click', 6]} simple_install(window_backend="win32", step=step, program=program) txt_change(prom_name=each, menu_change=menu_change) cad2007_cra(choose) else: failure.extend(format_menu(each.split())) if each == "T20": program = Application().start(join(getcwd(), "app_pkg", each, 'setup')) time = 20 while time >= 0: if program.top_window()["我接受许可证协议中的条款((&A)RadioButton"].exists(): break sleep(1) time -= 1 step = {0: ["我接受许可证协议中的条款((&A)RadioButton", 'click', 10], 1: ["下一步(&N) >Button", 'click', 6], 2: ["浏览(&R)...Button", 'click', 6], 3: ["路径(&P):Edit", join(choose, each), 'edit', 6], 4: ["确定Button", 'click', 6], 5: ["下一步(&N) >Button", 'click', 6], 6: ["下一步(&N) >Button", 'click', 6]} sleep_time = [0, 2, 1, 0, 0.5, 0.5, 0] if simple_install(window_backend="win32", step=step, program=program, sleep_time=sleep_time): time = 60 while time >= 0: try: if program.top_window()['InstallShield Wizard 完成'].exists(): break except: sleep(1) time -= 1 step = {0: ["完成Button", 'click', 10]} if simple_install(window_backend="win32", step=step, program=program): t20_cra(choose) txt_change(prom_name=each, menu_change=menu_change) else: failure.extend(format_menu(each.split())) end_time = strftime("%H:%M", localtime()) # 获取程序安装结束时的时间 menu = format_menu(menu) labelframe1 = tk.LabelFrame( self.root, text="", height=80, width=300) # 信息区 labelframe1.grid(row=1, column=0, columnspan=10, padx=10, pady=10) labelframe1.propagate(0) # 使组件大小不变,此时width才起作用 if len(failure) != 0: tk.Label(labelframe1, text=f"程序安装完毕,用时{running_time(start_time, end_time)}分钟,共选择了{len(menu)}个软件,\n安装失败的软件为:{','.join(failure)}", font=(', 8')).pack(fill="both", expand="yes") else: tk.Label(labelframe1, text=f"程序安装完毕,用时{running_time(start_time, end_time)}分钟,共选择了{len(menu)}个软件", font=(', 10')).pack(fill="both", expand="yes")
class GonioToolWrapper: """Interfaces with Goniotool to automate setting the rotation speed on a JEOL microscope by adjusting the stepping frequency of the motor. The values can be set from 1 to 12, where 12 is maximum speed and 1 is the slowest. The speed is linear up the maximum speed, where 1 is approximately 50 degrees/minute. barrier: threading.Barrier Synchronization primitive to synch with parent process """ def __init__(self, barrier=None): super().__init__() self.app = Application().start(GONIOTOOL_EXE) input('Enter password and press <ENTER> to continue...' ) # delay for password, TODO: automate self.startup() if barrier: barrier.wait() def startup(self): """Initialize and start up the GonioTool interface.""" self.f1rate = self.app.TMainForm['f1/rate'] self.f1 = self.app.TMainForm.f1 self.rb_cmd = self.f1.CMDRadioButton self.rb_tkb = self.f1.TKBRadioButton self.set_button = self.f1.SetButton self.get_button = self.f1.GetButton self.click_get_button() self.click_cmd() self.edit = self.app.TMainForm.f1.Edit7 def closedown(self): """Set default speed and close the program.""" self.set_rate(DEFAULT_SPEED) self.click_tkb() time.sleep(1) self.app.kill() def list_f1rate(self): """List GUI control identifiers for `f1/rate` tab.""" self.f1rate.print_control_identifiers() def list_f1(self): """List GUI control identifiers for `f1` box.""" self.f1.print_control_identifiers() def click_get_button(self): """Click GET button.""" self.get_button.click() def click_set_button(self): """Click SET button.""" self.set_button.click() def click_tkb(self): """Select TKB radio button.""" self.rb_tkb.click() def click_cmd(self): """Select CMD radio button.""" self.rb_cmd.click() def set_rate(self, speed: int): """Set rate value for TX.""" assert isinstance( speed, int), f'Variable `speed` must be of type `int`, is `{type(speed)}`' assert 0 < speed <= 12, f'Variable `speed` must have a value of 1 to 12.' s = self.edit.select() s.set_text(speed) self.click_set_button() def get_rate(self) -> int: """Get current rate value for TX.""" s = self.edit.select() val = s.text_block() return int(val)
def run_declaration_app(path:str, data_json: str): print("Read input params") print('First arg - path to Declaration 2018') print('Second arg - data json for Declaration 2018') ## todo проверка входных параметров data = json.loads(data_json) number_i= data['declaration']['block1']['number_i'] # 0101 number_k= int(data['declaration']['block1']['number_k']) # 0 oktmo = data['declaration']['block1']['oktmo'] # '04701000' radio_btn1 = data['declaration']['block1']['radio_btn1'] # 'Иное физическое лицо' radio_btn2 = data['declaration']['block1']['radio_btn2'] # 'Лично' last_name = data['declaration']['block2']['lastname'] # 'ИВАНОВА' first_name = data['declaration']['block2']['firstname'] # 'ЮЛИЯ' sir_name = data['declaration']['block2']['sirname'] # ВАЛЕРЬЕВНА inn = data['declaration']['block2']['inn'] # '780204893183' birth_place = data['declaration']['block2']['birth_place'] # 'Г.РОСТОВ-НА-ДОНУ' birth_date = data['declaration']['block2']['birth_date'] # '02.06.1982' phone = data['declaration']['block2']['phone'] # '89135555555' type_doc = data['declaration']['block2']['type_doc'] # '21' doc_number = data['declaration']['block2']['doc_number'] # '04 09 934566' doc_from = data['declaration']['block2']['doc_from'] # 'ТП №75 ОТДЕЛА УФМС РОССИИ ПО САНКТ-ПЕТЕРБУРГУ И ЛЕНИНГРАДСКОЙ ОБЛ. В ФРУНЗЕНСКОМ Р-НЕ ГОР.САНКТ-ПЕТЕРБУРГА КОД ПОДРАЗДЕЛЕНИЯ 780-075' doc_date = data['declaration']['block2']['doc_date'] # '02.03.2002' money_source_company = data['declaration']['block3']['money_source_company'] # '04701000' # '2464001001' # '2464231675' # PRAVOCARD money_dec = data['declaration']['block3']['money_dec'] # '14316' money_source = data['declaration']['block3']['money_source'] money_source_bottom_table = data['declaration']['block3']['money_source_bottom_table'] code_number_object = data['declaration']['block5']['code_number_object'] # 1 sign_taxplayer = data['declaration']['block5']['sign_taxplayer'] # 1 object_name = data['declaration']['block5']['object_name'] # 2 object_data = data['declaration']['block5']['object_data'] app = Application(backend='uia').start(path) main_window = app.window(title='Без имени - Декларация 2018') main_window.set_focus() def _select_tab(num: int): step = int(main_window.rectangle().height() / 9) offset = step * num navigation_panel.click_input(coords=(0, offset)) def _select_tab_toolpanel(num: int): step = int(main_window.rectangle().height() / 9) offset = step * num tool_panel.click_input(coords=(0, offset)) def _select_radio(group: str, v: str): group = main_window.window(title=' ' + group) c = group.window(title=v) c.click_input() def _type_to_onlyone_input_by_index(group: str, text: str, class_name: str): parent = main_window.window(title=group) child = parent.child_window() child.set_text(text) def _type_to_input_by_index(group: str, ind: int, text: str, class_name: str): inpts = main_window.window(title=' ' + group).descendants(class_name=class_name) inpts[ind].set_text(text) def _type_to_input_by_index_mask(group: str, ind: int, text: str, class_name: str): inpts = main_window.window(title=' ' + group).descendants(class_name=class_name) inpts[0].set_text(text) def _set_spinner(group: str, ind: int, v: int): group = main_window.window(title=' ' + group) bs = group.descendants() b = bs[ind] b.set_text(v) def _select_from_dict(group: str, win_title: int, v: str): group = main_window.window(title=' ' + group) b = group.window(title='...') b.click_input() dw = app.window(title=win_title) l = dw.window(class_name="TListView") l.set_focus() vl = l.window(title=v) for _ in range(1000): try: #if vl.is_visible(timeout=0.5): vl.click_input() break except ElementNotFoundError: send_keys('{PGDN}') ok_b = dw.window(title='Да') ok_b.click_input() def _check_checkbox(group: str, name: str): cb = main_window.window(title=name) cb.click_input() labels2indTab1 = { 'Номер инспекции': ('Общая информация', 'Справочник инспекций', 0), 'Номер корректировки': ('Общая информация', 4, 0), 'ОКТМО': ('Общая информация', 0, 0), 'Индивидуальный предприниматель': ('Признак налогоплательщика', None, 0), 'Глава фермерского хозяйства': ('Признак налогоплательщика', None, 0), 'Частный нотариус': ('Признак налогоплательщика', None, 0), 'Адвокат': ('Признак налогоплательщика', None, 0), 'Иное физическое лицо': ('Признак налогоплательщика', None, 0), 'Арбитражный управляющий': ('Признак налогоплательщика', None, 0), 'Учитываемые "справками о доходах физического лица", доходы по договорам': ('Имеются доходы', None, 0), 'В иностранной валюте': ('Имеются доходы', None, 0), 'От предпринимательской деятельности': ('Имеются доходы', None, 0), 'Лично': ('Достоверность подтверждается', None, 0), 'Представителем - ФЛ': ('Достоверность подтверждается', None, 0), 'ФИО': ('Достоверность подтверждается', 1, 0), 'Документ': ('Достоверность подтверждается', 0, 0), 'Фамилия': ('Ф.И.О.', 4, 1), 'Имя': ('Ф.И.О.', 3, 1), 'Отчество': ('Ф.И.О.', 2, 1), 'ИНН': ('Ф.И.О.', 1, 1), 'Дата рождения': ('Ф.И.О.', 0, 1), 'Место рождения': ('Ф.И.О.', 0, 1), 'Вид документа': ('Сведения о документе, удостоверяющем личность', 'Справочник видов документов', 1), 'Серия и номер': ('Сведения о документе, удостоверяющем личность', 0, 1), 'Дата выдачи': ('Сведения о документе, удостоверяющем личность', 0, 1), 'Кем выдан': ('Сведения о документе, удостоверяющем личность', 1, 1), 'Контактный телефон': ('Контактный телефон', 0, 1), 'Наименование источника выплаты': ('Наименование источника выплаты', 0, 0), 'ИНН Источника выплаты': ('ИНН', 1, 0), 'КПП Источника выплаты': ('КПП', 2, 0), 'ОКТМО Источника выплаты': ('ОКТМО', 3, 0), 'Чекбокс Источник выплаты1': ('Расчет стандартных вычетов вести по этому источнику', None, 0), 'Чекбокс Источника выплаты2': ('Источник является инвестиционным товариществом', None, 0), 'Код дохода': ('Сведения о полученном доходе', 'Справочник видов доходов', 2) } def select_from_dict(name: str, v: str): group, ind, tb = labels2indTab1[name] _select_tab(tb) _select_from_dict(group, ind, v) def select_from_dict_from_modal_window(name: str, v: str): group, ind, tb = labels2indTab1[name] _select_from_dict_from_modal_window(group, ind, v) def set_spinner(name: str, v: int): group, ind, tb = labels2indTab1[name] _select_tab(tb) _set_spinner(group, ind, v) def fill_only_one_input(name: str, v: str, class_name: str): group, ind, tb = labels2indTab1[name] _select_tab(tb) _type_to_onlyone_input_by_index(group, v, class_name) def fill_input(name: str, v: str, class_name: str): group, ind, tb = labels2indTab1[name] _select_tab(tb) _type_to_input_by_index(group, ind, v, class_name) def select_radio(name: str): group, _, tb = labels2indTab1[name] _select_tab(tb) _select_radio(group, name) def select_checkbox(name: str): group, _, tb = labels2indTab1[name] _select_tab(tb) _check_checkbox(group, name) def fill_input_mask(name: str, v: str, class_name: str): group, ind, tb = labels2indTab1[name] _select_tab(tb) _type_to_input_by_index_mask(group, ind, v, class_name) print('Start new decl filling....') print('Block №1 - Задание условий') navigation_panel = main_window.descendants(class_name="TPanel")[1] select_from_dict('Номер инспекции', number_i) set_spinner('Номер корректировки', number_k) fill_input('ОКТМО', oktmo, 'TMaskedEdit') select_radio(radio_btn1) ## todo проверка - добавляется количество заполняемых данных ## первое устанавливается по-умолчанию ## select_checkbox('Учитываемые "справками о доходах физического лица", доходы по договорам') select_radio(radio_btn2) print('Block №1 - Сведения о декларанте') _select_tab(1) fill_input('Фамилия', last_name, 'TMaskedEdit') fill_input('Имя', first_name,'TMaskedEdit') fill_input('Отчество', sir_name, 'TMaskedEdit') fill_input('ИНН', inn , 'TMaskedEdit') fill_input('Место рождения', birth_place, 'TMaskedEdit') fill_input('Дата рождения', birth_date, 'TTestMaskD') fill_only_one_input('Контактный телефон', phone, 'TMaskedEdit') select_from_dict('Вид документа', type_doc) fill_input_mask('Серия и номер', doc_number , 'TMaskedDocEdit') fill_input_mask('Кем выдан', doc_from , 'TMaskedEdit') fill_input('Дата выдачи', doc_date, 'TTestMaskD') print('Block №1 - Доходы, полученные в РФ') _select_tab(2) ## todo пока клик настроен только на кнопку 13 в панели ## она устанавливается по-умолчанию print('Add money source') add_money_source_allpanel = main_window.descendants(class_name='TPanel')[0] add_source_panel = add_money_source_allpanel.descendants(class_name='TPanel') add_source_panel[8].click_input(coords=(10, 55)) print('Source money Modal window filling') dw = app.window(title='Источник выплаты') inner_edit = dw.window(class_name="TPanel").descendants(); inner_edit[1].type_keys(money_source_company[0]) inner_edit[3].type_keys(money_source_company[1]) inner_edit[4].type_keys(money_source_company[2]) ## todo проверить варианты ввода на русском языке ## пока проблема inner_edit[5].type_keys(money_source_company[3]) inner_checkbox = dw.window(class_name="TPanel").descendants(class_name="TCheckBox") inner_checkbox[1].click_input() ok_b = dw.window(title='Да') ok_b.click_input() edit_form = add_money_source_allpanel.descendants(class_name='TMaskedEdit') edit_form[1].set_text(money_dec) print('Info money source Modal Window filling') for money_source_item in money_source: add_money_source_allpanel = main_window.descendants(class_name='TPanel')[0] add_source_panel = add_money_source_allpanel.descendants(class_name='TPanel') add_source_panel[8].click_input(coords=(10, 155)) finance_buttons = app.window(title='Сведения о доходе').descendants(class_name="TButton") finance_buttons[3].click_input(); print('Open dictionary of the type of money') dw = app.window(title='Справочник видов доходов') l = dw.window(class_name="TListView") l.set_focus() vl = l.window(title= money_source_item['code']) for _ in range(1000): try: #if vl.is_visible(timeout=0.5): vl.click_input() break except ElementNotFoundError: send_keys('{PGDN}') ok_b = dw.window(title='Да') ok_b.click_input() print('Dictionary of the type of money source') edit_buttons = app.window(title='Сведения о доходе').descendants(class_name="TMaskedEdit") edit_buttons[2].set_text( money_source_item['money_sum']) edit_buttons[1].set_text( money_source_item['month']) app.window(title='Сведения о доходе').window(title='Да').click_input() print('Bottom table filling') add_money_source_allpanel = main_window.descendants(class_name='TPanel')[0] add_source_panel = add_money_source_allpanel.descendants(class_name='TPanel') add_source_panel[8].click_input(coords=(10, 455)) finance_buttons = app.window(title='Вычеты, указанные в разделе 3 справки 2-ндфл').descendants(class_name="TButton") finance_buttons[2].click_input() dw = app.window(title='Справочник видов вычетов') l = dw.window(class_name="TListView") l.set_focus() vl = l.window(title= money_source_bottom_table['code']) for _ in range(1000): try: #if vl.is_visible(timeout=0.5): vl.click_input() break except ElementNotFoundError: send_keys('{PGDN}') ok_b = dw.window(title='Да') ok_b.click_input() print('Get dictionary another money source') edit_buttons = app.window(title='Вычеты, указанные в разделе 3 справки 2-ндфл').descendants(class_name='TMaskedEdit') edit_buttons[0].set_text(money_source_bottom_table['money']) # 16800 app.window(title='Вычеты, указанные в разделе 3 справки 2-ндфл').window(title='Да').click_input() print("Block 3") _select_tab(5) check_boxes = main_window.descendants(class_name='TCheckBox') check_boxes[0].click_input() add_money_source_allpanel = main_window.descendants(class_name='TPanel')[0] add_source_panel = add_money_source_allpanel.descendants(class_name='TPanel') add_source_panel[0].click_input(coords=(10, 55)) print('Objects Data Modal Window filling') combo_boxes = app.window(title='Данные объекта').descendants(class_name='TComboBox') # Код номера объекта Кадастровый номер combo_boxes[0].click_input() cmb1 = combo_boxes[0].descendants() cmb1[int(code_number_object)].click_input() # 1 - Кадастровый номер # Признак налогоплательщика Собственник объекта combo_boxes[1].click_input() cmb1 = combo_boxes[1].descendants() cmb1[int(sign_taxplayer)].click_input() # 0 - Родитель несовершеннолетнего собственника объекта # 1 - Собственник объекта # Наименование объекта combo_boxes[2].click_input() cmb1 = combo_boxes[2].descendants() cmb1[int(object_name)].click_input() # 0 - Земельный участок для индивидуального жилищного строительства # 1 - Жилой дом # 2 - Квартира masked_edits = app.window(title='Данные объекта').descendants(class_name='TMaskedEdit') masked_edits[5].set_text(object_data['object_number']) masked_edits[4].set_text(object_data['object_address']) masked_edits[1].set_text(object_data['object_sum']) masked_edits[0].set_text(object_data['object_del']) masked_date_edits = app.window(title='Данные объекта').descendants(class_name='TTestMaskD') masked_date_edits[1].set_text(object_data['object_date']) app.window(title='Данные объекта').window(title='Да').click_input() ### Сохранить декларацию manage_btns = main_window.descendants(class_name='TToolBar') manage_btns[1].click_input() print('Choose folder to save...') dw = app.window(title='Обзор папок') l = dw.descendants()[1] #todo перенести в параметры item = l.get_item([r'\Рабочий стол\dec']) item.select() dw.descendants(class_name='Button')[0].click_input() ### Last Step app.window(title='Декларация 2018').descendants(class_name='Button')[0].click_input() ## todo проверка на ошибку - куча всплывающих окон может быть #app.window(title='Декларация 2018').descendants(class_name='Button')[0].click_input() print('Declaration is Ready!') app.kill()
class RealBandController: """An object for controlling RealBand.""" _TARGET_VERSION = '2018.0.2.5' def __init__(self, binary_path=r'C:\RealBand\RealBand.exe', try_connect=True): self.realband_version = _get_exe_version(binary_path) if self.realband_version != self._TARGET_VERSION: print('This code was written for RealBand {}, your version is {}. ' 'Proceed with caution.' .format(self._TARGET_VERSION, self.realband_version), file=sys.stderr) self._app = Application(backend='win32') if try_connect: try: self._app.connect(path=binary_path) except ProcessNotFoundError: try_connect = False if not try_connect: self._app.start(binary_path) self._app.wait_cpu_usage_lower(threshold=5) def get_ready(): rb_window = self._app.window(class_name='RealBand') if rb_window.exists() and rb_window.is_visible() and rb_window.is_enabled(): return # Reject attempts to recover from a crash dialog = self._app.window(class_name='#32770') dialog_text = dialog.StaticWrapper2.element_info.name if ('Okay to restore all the default settings' in dialog_text or 'Recover data from last session' in dialog_text): dialog.Button2.click() raise TimeoutError() wait_until_passes(func=get_ready, exceptions=(ElementNotFoundError, TimeoutError), timeout=15, retry_interval=1) self._song_pane = self._app.RealBand.children( class_name='TPanelWithCanvas')[10] @property def app(self): return self._app def kill(self): self._app.kill() for proc in psutil.process_iter(): if proc.name() in ['bbw2.exe', 'RealBand.exe']: print('Killing', proc, file=sys.stderr) try: proc.kill() except psutil.NoSuchProcess: traceback.print_exc(file=sys.stderr) def load_song(self, path): """Load a song from the given file.""" self._menu_select('File->Open') self._open_file(path) try: # Get the annoying Comments window out of the way self._app.Comments.minimize() except MatchError: pass def load_style(self, path): """Load a style from the given file.""" self.wait_ready() def open_dialog(): # Bring up the style popup menu and choose to open a style file self._song_pane.click_input(coords=(44, 73), absolute=False) menu = self._app.window(class_name='#32768') menu.menu_item('File Open Style').click_input() wait_until_passes(func=open_dialog, exceptions=ElementNotFoundError, timeout=120, retry_interval=0.4) self._open_file(path) def _open_file(self, path): """Input a path in the file open dialog.""" path = os.path.normpath(os.path.abspath(path)) while True: dialog = self._app.window(class_name='#32770') dialog.wait('ready') # If asked whether to save changes, say no try: dialog_text = dialog.StaticWrapper2.element_info.name if 'Save it?' in dialog_text: dialog.Button2.click() continue except MatchError: pass break dialog.Edit1.set_edit_text(path) dialog.Edit1.send_keystrokes('{ENTER}') self.wait_ready(timeout=60) def save_song(self, path, filetype='MIDI File (.MID) (*.MID)'): """Save the current song under the given filename.""" path = os.path.normpath(os.path.abspath(path)) self._menu_select('File->Save As') file_dialog = self._app.window(class_name='#32770') file_dialog.wait('ready') file_dialog.ComboBox2.select(filetype) file_dialog.Edit1.set_edit_text(path) file_dialog.Edit1.send_keystrokes('{ENTER}') self.wait_ready() def generate_all(self): """Generate all Band-in-a-Box tracks.""" self._menu_select('Generate->Generate All BB Tracks') self.wait_ready() def set_key(self, key, transpose=False): """Set the key of the song.""" if transpose: raise NotImplementedError('transpose not implemented') self._menu_select('Edit->Key Signature') key_dialog = self._app.window(class_name='TKEY') key_dialog.wait('ready') key_dialog.TComboBox1.select(key) key_dialog.TRadioButton4.click() # No Transpose key_dialog.TButton3.click() # OK self.wait_ready() @property def key_signature(self): """The key signature of the song.""" text = self._get_menu_item_text('Edit->Key Signature') return re.search(r'\[([A-G].?)\]$', text).group(1) @property def time_signature(self): """The time signature (meter) of the song.""" text = self._get_menu_item_text('Edit->Meter (Time Signature)') return re.search(r'\[([0-9]+/[0-9]+)\]$', text).group(1) @property def tempo(self): """The tempo of the song.""" text = self._get_menu_item_text('Edit->Tempo') return float(re.search(r'\[([0-9.,]+)\]$', text).group(1)) def _get_menu_item_text(self, path, timeout=10, retry_interval=0.5): def get_text(): return self._app.RealBand.menu_item(path).text() return wait_until_passes(func=get_text, exceptions=(ElementNotEnabled, RuntimeError), timeout=timeout, retry_interval=retry_interval) def _menu_select(self, path, timeout=10, retry_interval=0.5): self.wait_ready() def select_option(): self._app.RealBand.menu_select(path) wait_until_passes(func=select_option, exceptions=(ElementNotEnabled, RuntimeError), timeout=timeout, retry_interval=retry_interval) def wait_ready(self, timeout=30): self._app.RealBand.wait('ready', timeout=timeout)
def build(self, project): HAULBuilder.build(self, project=project) name = self.project.name libs_path = os.path.join(self.data_path, 'platforms', 'palmos', 'libs') pose_path = self.get_path('POSE_PATH', os.path.abspath(os.path.join(self.tools_path, 'platforms', 'palmos', 'pose'))) put('Copying libraries...') pas_filename = name + '.pas' exe_filename = name + '.exe' pas_filename_full = os.path.join(self.staging_path, pas_filename) put('Preparing path names...') for s in self.project.sources: s.dest_filename = self.staging_path + '/' + self.name_to_8(s.name) + '.pas' put('Translating source to PP...') self.translate_project(output_path=self.staging_path) if not os.path.isfile(pas_filename_full): raise HAULBuildError('Main Pascal file "{}" was not created!'.format(pas_filename_full)) return False sources = [] put('Copying libraries...') for s in self.project.libs: self.copy(os.path.join(libs_path, s.name + '.pas'), os.path.join(self.staging_path, s.name + '.pas')) sources.append(s.name) for s in self.project.sources: sources.append(self.name_to_8(s.name)) #@TODO: Convert file to PDB put('Converting pas files to PDBs...') for s in sources: pas_filename = self.staging_path + '/' + s + '.pas' vfsFilename = s + '.pas' pdbFilename = self.staging_path + '/' + vfsFilename + '.pdb' put('Converting "%s" to "%s"...' % (pas_filename, pdbFilename)) data = self.type(pas_filename) pdb = PDBFile() pdb.set_vfs(name=vfsFilename, data=data) self.touch(pdbFilename, pdb.to_file()) # Compile it using PP on POSE Emulator pose_cmd = os.path.join(pose_path, 'Emulator_Bound.exe') put('Starting emulator "%s"...' % (pose_cmd)) app = Application().start(pose_cmd) win = app.top_window() win.DrawOutline() #@TODO: Check if the emulator started up in good state #time.sleep(10) ### Clean emulator put('Cleaning source...') for s in sources: pas_filename = s + '.pas' win.TypeKeys('del{SPACE}%s{ENTER}' % (pas_filename)) put('Cleaning binary...') win.TypeKeys('del{SPACE}%s{ENTER}' % (exe_filename)) win.TypeKeys('{ENTER}') ### Install local files put('Importing into emulator...') for s in sources: time.sleep(0.2) pas_filename = s + '.pas' pas_pdb_filename = pas_filename + '.pdb' pas_pdb_filename_full = os.path.abspath(os.path.join(self.staging_path, pas_pdb_filename)) put('Importing "%s" ("%s") into Emulator...' % (pas_filename, pas_pdb_filename_full)) win.RightClickInput() app.PopupMenu.MenuItem('Install Application/Database -> Other').ClickInput() time.sleep(0.2) winOpen = app.top_window() winOpen.TypeKeys('%s{ENTER}' % (pas_pdb_filename_full)) time.sleep(0.2) ### Invoke compiler pas_filename = name + '.pas' exe_filename = name + '.exe' put('Compiling "%s" to "%s"...' % (pas_filename, exe_filename)) time.sleep(0.5) win.TypeKeys('pp.exe{SPACE}%s{ENTER}' % (pas_filename)) # Compiling... time.sleep(2) # OK win.TypeKeys('{ENTER}') put('Compilation done.') ### Exfiltrate put('Cleaning host...') exe_prc_filename = exe_filename + '.prc' exe_prc_filename_full = os.path.abspath(os.path.join(self.staging_path, exe_prc_filename)) if os.path.isfile(exe_prc_filename_full): os.remove(exe_prc_filename_full) put('Exporting "%s" back to host...' % (exe_filename)) win.RightClickInput() app.PopupMenu.MenuItem('Export Database').ClickInput() winList = app.top_window() #put(winList) #winList.print_control_identifiers() list = winList.ListBox #put(list.ItemTexts()) try: list.Select(exe_filename, True) winList.OK.ClickInput() except Exception as e: raise HULBuildError('Output file "{}" was not created on emulator!'.format(exe_filename)) return False time.sleep(0.1) winOpen = app.top_window() winOpen.TypeKeys('%s{ENTER}' % (exe_prc_filename_full)) time.sleep(1) put('Copying "%s" to output directory...' % (exe_prc_filename)) self.copy(exe_prc_filename_full, self.output_path + '/' + exe_prc_filename) if (self.project.run_test == True): ### Test put('Testing binary "%s" on emulator...' % (exe_filename)) time.sleep(0.1) win.TypeKeys('%s{ENTER}' % (exe_filename)) # Running put('Running... Close emulator manually when you are done.') # RightC win.RightClickInput() app.PopupMenu.MenuItem('Exit').ClickInput() # Type No ("Save changes?") #win.TypeKeys('n') else: ### Exit put('Quitting emulator...') win.RightClickInput() app.PopupMenu.MenuItem('Exit').ClickInput() # Do not save winPrompt = app.top_window() winPrompt.TypeKeys('n') ### put('Killing emulator...') app.kill() put('Done.') return True
class Browser(WEBDRIVER): def __init__(self, profile=True): super().__init__(headless=False, profile=profile, wait=15) self.obs = Application(backend='uia').start( work_dir=r'C:\Program Files\obs-studio\bin\64bit', cmd_line=r'C:\Program Files\obs-studio\bin\64bit\obs64.exe' ) self.auto_find('Launch Anyway', click=True, type_='Button') self.get('https://sketch.pixiv.net/followings') self.driver.set_window_position(-1000, 0) self.driver.fullscreen_window() self.run() def run(self, start=1): while True: try: if re.match('.+lives/\d+$', self.current_url()): if start: self.set_source(); start=0 self.auto_find( 'Start Recording', click=True ) self.live_stream() self.auto_find( 'Stop.* Recording', click=True ) except exceptions.WebDriverException: break except Exception as error: print(f'{error}\n') Timer(5, function=None) self.obs.kill() self.close() def live_stream(self): while 'lives' in self.current_url(): try: self.find(CHAT, click=True) self.find(PLAY, click=True, fetch=1) target = self.find(CONTROL).find_elements_by_class_name( 'StreamBodyCtrlButton' ) self.driver.execute_script( 'arguments[0].style.visibility="visible"', self.find(CONTROL, fetch=1) ) target[0].click() target[-1].click() self.find(HIGH, click=True) self.find(ACCEPT, click=True) except exceptions.ElementClickInterceptedException: self.refresh() except: pass if self.find(FINISHED): self.driver.back() self.refresh() def set_source(self): title = f'[firefox.exe]: {self.driver.title} — Mozilla Firefox' self.auto_find('Livestreams', select=True, type_='ListItem') self.auto_find('Window Capture.+', select=True, type_='ListItem') self.auto_find('Window', select=title, type_='ComboBox') def auto_find(self, title, keys=None, click=0, select=None, type_='CheckBox', fetch=0): try: element = self.obs.top_window().child_window( title_re=title, control_type=type_ ) if keys: element.type_keys(keys) if click: element.click() if select: if isinstance(bool, select): element.select() else: element.select(select) return element except Exception as error: if fetch: raise error
class BandInABoxController: """An object for controlling Band-in-a-Box.""" _TARGET_VERSION = '2018.0.0.520' def __init__(self, binary_path=r'C:\bb\bbw.exe', try_connect=True): self.biab_version = _get_exe_version(binary_path) if self.biab_version != self._TARGET_VERSION: print('This code was written for Band-in-a-Box {}, your version is {}. ' 'Proceed with caution.' .format(self._TARGET_VERSION, self.biab_version), file=sys.stderr) self._app = Application(backend='win32') if try_connect: try: self._app.connect(path=binary_path) except ProcessNotFoundError: try_connect = False if not try_connect: self._app.start(binary_path) self._app.wait_cpu_usage_lower(threshold=5) def get_ready(): rb_window = self._app.window(class_name='TBandWindow') if rb_window.exists() and rb_window.is_visible() and rb_window.is_enabled(): return raise TimeoutError() wait_until_passes(func=get_ready, exceptions=(ElementNotFoundError, TimeoutError), timeout=15, retry_interval=1) @property def app(self): return self._app def kill(self): self._app.kill() for proc in psutil.process_iter(): if proc.name() == 'bbw.exe': print('Killing', proc, file=sys.stderr) try: proc.kill() except psutil.NoSuchProcess: traceback.print_exc(file=sys.stderr) def load_song(self, path): """Load a song from the given file.""" self.menu_select('File->Open') self._open_file(path) def _open_file(self, path): """Input a path in the file open dialog.""" while True: dialog = self._app.window(class_name='#32770') dialog.wait('ready') # If asked whether to save changes, say no try: dialog_text = dialog.StaticWrapper2.element_info.name if 'Save it?' in dialog_text: dialog.Button2.click() continue except MatchError: pass break dialog.Edit1.set_edit_text(path) dialog.Edit1.send_keystrokes('{ENTER}') self._wait_ready(timeout=60) def save_song(self, path): """Save the current song under the given filename.""" self.menu_select('File->Save song As') file_dialog = self._app.window(class_name='#32770') file_dialog.wait('ready') file_dialog.Edit1.set_edit_text(path) file_dialog.Edit1.send_keystrokes('{ENTER}') self._wait_ready() def menu_select(self, path, timeout=10, retry_interval=0.5): self._wait_ready() def select_option(): self._app.TBandWindow.menu_select(path) wait_until_passes(func=select_option, exceptions=(ElementNotEnabled, RuntimeError), timeout=timeout, retry_interval=retry_interval) def _wait_ready(self, timeout=30): self._app.TBandWindow.wait('ready', timeout=timeout)
def cra_3dmax(install_dir: str, program_name: str): """ 激活3dmax2014及CAD2014 :param program_name: 程序名称 CAD2014 OR 3DMAX2014 :param install_dir: 用户程序安装路径 :return: """ program_name_dict = { "3DMAX2014": ['3ds Max 2014', '3dsmax'], "CAD2014": ['AutoCAD 2014', 'acad'] } program_path = join(install_dir, program_name, program_name_dict[program_name][0], program_name_dict[program_name][1]) # 启动文件所在路径 program_temp = Application().start(program_path + str(" /Language=CHS")) # 以中文语言打开程序 while True: try: Application().connect(title='Autodesk 许可') except: pass else: break sleep_time = [5, 1, 1, 1, 1] # 各图片的等待时间 grayscale = [True, False, True, True, True] # 各图片是否使用灰度搜索 skewing = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] # x、y坐标偏移 if install_from_png(app_name=program_name, confidence=0.8, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, png_file_name="_shot1"): # 点击同意协议一直到复制申请号的界面 sleep_time = [2, 1] # 各图片的等待时间 grayscale = [True, True] # 各图片是否使用灰度搜索 skewing = [[200, 0], [0, 0]] # x、y坐标偏移 coordinate_list = install_from_png(app_name=program_name, confidence=0.8, sleep_time_list=sleep_time, grayscale_list=grayscale, skewing_list=skewing, png_file_name="_shot2", coordinate=True) if len(coordinate_list) == 2: button1 = coordinate_list[0] # 申请号坐标 button2 = coordinate_list[1] # 我具有激活码坐标 tripleClick(button1[0], button1[1]) hotkey('ctrl', 'c') # 复制申请号 key_soft = Application().start( join(getcwd(), 'app_pkg', program_name, 'crack', 'xf-adsk64')) # 打开注册机 step = { 0: ["Request :Edit", paste(), 'edit', 10], # 将申请号粘贴 1: ["CButton", 'click', 6], # 按下注册机patch按钮 2: ["确定Button", 'click', 6], # 按下弹出窗口的确定按钮 3: ["GButton", 'click', 6] } # 按下注册机Gen按钮获得激活码 if simple_install(window_backend='win32', step=step, program=key_soft): while True: # 判断生成的激活码是否正确 dict_temp = key_soft.top_window()._ctrl_identifiers() for each in dict_temp.keys(): # 通过按钮便签值获取激活码 if 'Activation :Edit' in dict_temp[each]: temp = str(each) key = temp.split("'")[1] if len(key) == 57: copy(key) break else: key_soft.top_window()['GButton'].click_input() key_soft.top_window()['QQButton'].click_input() # 按下注册机Quit按钮 click(button2[0], button2[1]) # 按下我具有激活码坐标 sleep(1) hotkey('ctrl', 'v') # 粘贴激活码 sleep(1) for _ in range(5): hotkey('tab') sleep(.5) hotkey('enter') sleep(2) hotkey('enter') sleep(5) program_temp.kill()