Example #1
0
def wowForFront():
    print('Searching for WoW process..')
    for pid in psutil.pids():
        if psutil.Process(pid).name().lower() == 'wow.exe':
            print('Found WoW')
            app = Application().connect(process=pid)
            app.top_window().set_focus()
            pyautogui.moveTo(960, 540, duration=1)
Example #2
0
    def foreGroundDiscord(
            self):  # it will make discord window top of all other windows

        windows = Desktop(backend="uia").windows()

        title = ""
        for w in windows:
            if "Discord" in str(w.window_text):
                title = str(w.window_text).split("'")[1]
                break

        app = None
        try:
            app = Application().connect(title_re=title)

        except (__import__("re").error,
                pywinauto.findwindows.ElementAmbiguousError):
            raise GuiDoesNotExists
            return

        hwin = app.top_window()

        hwin.set_focus()

        sleep(0.9)
Example #3
0
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()
Example #4
0
def main():
    minecraft_handle = Application().connect(title_re="Minecraft 1.14.4",
                                             class_name="GLFW30")
    main_window = minecraft_handle.top_window()
    while True:
        main_window.right_click()
        time.sleep(0.1)
Example #5
0
def todo():
    app = Application(backend='uia')
    app.connect(title_re=".*Chrome.*")
    dlg = app.top_window()
    url = dlg.child_window(title="Address and search bar",
                           control_type="Edit").get_value()
    site = url.split('/')[0]
    print(site)
Example #6
0
class E2ETest:
    def __init__(self,
                 test_name: str,
                 fragments: Iterable[Fragment],
                 dev_mode: bool = False,
                 auto_connect: bool = True):
        try:
            self._application = Application(backend='uia').connect(
                title_re='orbitprofiler')
        except Exception:
            logging.error(
                "Could not find Orbit application. Make sure to start Orbit before running E2E tests."
            )
            raise
        self._test_name = test_name
        self._dev_mode = dev_mode or flags.FLAGS.dev_mode
        self._fragments = fragments[:]
        self._auto_connect = auto_connect
        self._top_window = None

    name = property(lambda self: self._test_name)
    application = property(lambda self: self._application)
    dev_mode = property(lambda self: self._dev_mode)

    def top_window(self, force_update=False):
        if force_update:
            self._top_window = self._application.top_window()
        return self._top_window

    def set_up(self):
        timings.Timings.after_click_wait = 0.5
        ot.wait_for_orbit()
        logging.info("Setting up with dev_mode = %s", self.dev_mode)
        if not self.dev_mode:
            if self._auto_connect:
                ot.connect_to_gamelet(self.application)
        else:
            logging.info(
                "DEV MODE: Skipped gamelet connection, assuming Main Window is active"
            )
        self.top_window(True).set_focus()

    def tear_down(self):
        if not self._dev_mode:
            find_control(self.top_window(), "Button", "Close").click_input()
            logging.info('Closed Orbit.')
        else:
            logging.info("DEV MODE: Skipped closing Orbit")
        logging.info('Test "%s" executed without errors', self._test_name)
        timings.Timings.defaults()

    def execute(self):
        self.set_up()
        for fragment in self._fragments:
            logging.info('Executing fragment "%s"',
                         fragment.__class__.__name__)
            fragment.execute(self)
        self.tear_down()
Example #7
0
def WindowInFront(processpath):
    #Bring window in front
    app = Application().connect(path=processpath)
    w = app.top_window()

    #bring window into foreground
    if w.HasStyle(win32defines.WS_MINIMIZE):  # if minimized
        ShowWindow(w.wrapper_object(), 9)  # restore window state
    else:
        SetForegroundWindow(w.wrapper_object())  #bring to front
Example #8
0
 def auto_input_writer(self):
     try:
         app = Application().connect(path='nvcontainer.exe')
         dialog = app.top_window()
         if dialog.is_visible():
             dialog.Edit.type_keys('1111')
             dialog.Button.click()
             self.state = 'reserved'
     except Exception:
         print(Exception)
Example #9
0
class URL:
    def giveurl(self):
        try:
            self.app = Application(backend='uia')
            self.app.connect(title_re=".*Chrome.*")
            self.dlg = self.app.top_window()
            self.obj = self.dlg.child_window(title="Address and search bar",
                                             control_type="Edit")
            self.url = self.obj.get_value()
        except Exception:
            return ''
        return str(self.url)
    def ipo(self):
        pyperclip.copy("")
        app = Application().connect(handle=self.main)
        app["股票交易系统"].window(handle=self.tree_handle).select("\\新股申购\\新股批量申购")
        print_time(self.tree_handle)
        time.sleep(9)
        app.top_window()["确定"].click()
        print_time(" width:%d,height:%d", self.screen_width,
                   self.screen_height)
        self.ipo_grid_handle = op.WindowFromPoint(
            POINT(int(self.screen_width / 2), int(self.screen_height / 2)))
        print_time(ctypes.WinError())
        print_time(
            op.SendMessageW(self.ipo_grid_handle, WM_COMMAND, 57634,
                            self.ipo_grid_path[-1]))
        print_time("ipo grid handle:%d" % self.ipo_grid_handle)
        can_ipo = pyperclip.paste()
        print_time(ctypes.WinError())
        print_time(can_ipo)
        dict_ipo = util.BaseTypeUtil.analyze_position(can_ipo)
        pos = []
        for (j, k) in zip(dict_ipo.values(), range(1, 10, 1)):
            if float(dict(j).get("可申购数量")) > 0.99:
                pos.append(k)
        if len(pos) < 1:
            return
        rect = app.window(handle=self.ipo_grid_handle).rectangle()
        height = 16
        x = rect.left + 10
        first = rect.top + 20 + height / 2
        print_time(pos)
        for i in pos:
            y = first + (i - 1) * height
            print_time("x:%d,y:%d,i:%d" % (x, y, i))
            mouse_move_click(int(x), int(y))

        app["股票交易系统"]["申购Button"].click()
        time.sleep(9)
        app.top_window()["是Button"].click()
Example #11
0
def run_CAN_simulator():
    os.system(r".\su_tool\RunCAN_Simulator.bat")
    time.sleep(2)
    app = Application().connect(path=r".\su_tool\MBC_CAN-rx_Simulator.exe")
    w = app.top_window()
    if w.HasStyle(win32defines.WS_MINIMIZE):  # if minimized
        ShowWindow(w.wrapper_object(), 9)  # restore window state
    else:
        SetForegroundWindow(w.wrapper_object())  #bring to front
    wsh = comclt.Dispatch("WScript.Shell")
    for count in range(0, 9):
        wsh.SendKeys("{+}")
    time.sleep(1)
    wsh.SendKeys("{2}")
    for count in range(0, 9):
        wsh.SendKeys("{+}")
Example #12
0
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 test_update_available_win_sparkle_check_update_with_ui(self):

        # Remind me later
        pywinsparkle.win_sparkle_check_update_with_ui()
        is_exception = False
        try:
            app = Application().connect(title_re="Software Update")
            app.top_window().window(title="Remind me later").click()
        except Exception:
            is_exception = True
        self.assertFalse(is_exception, "Remind me later failed")

        time.sleep(3)

        # Install Updates
        pywinsparkle.win_sparkle_check_update_with_ui()
        is_exception = False
        try:
            app = Application().connect(title_re="Software Update")
            app.top_window().window(title="Install update").click()
            app.top_window().window(title="Cancel").click()
        except Exception:
            is_exception = True
        self.assertFalse(is_exception, "Install update window not clicked")
Example #14
0
import win32com.client
import pyautogui
from pywinauto import Application, win32defines
import pywinauto.win32functions as win32fun

app = Application().start("Notepad.exe")
#app = Application().connect(path="C:\\Windows\\System32\\notepad.exe")
w = app.top_window()

#bring window into foreground
if w.has_style(win32defines.WS_MINIMIZE): # if minimized
    win32fun.ShowWindow(w.wrapper_object(), 9) # restore window state
else:
    win32fun.SetForegroundWindow(w.wrapper_object()) #bring to front

while w.is_active():
    pyautogui.keyDown('a')
   
Example #15
0
import json
import urllib.request
from bs4 import BeautifulSoup
from pywinauto import Application
import os
import sys 

if(len(sys.argv)==1):
	app = Application(backend='uia')
	app.connect(title_re=".*Chrome.*")
	dlg = app.top_window()
	url = dlg.child_window(title="Address and search bar", control_type="Edit").get_value()
	url = "https://" + url
	filename = "main.cpp__tests"
elif(len(sys.argv)==2):
	app = Application(backend='uia')
	app.connect(title_re=".*Chrome.*")
	dlg = app.top_window()
	url = dlg.child_window(title="Address and search bar", control_type="Edit").get_value()
	url = "https://" + url
	filename = sys.argv[1] + "__tests"
else:
	url = sys.argv[1]
	filename = sys.argv[2] + ".cpp__tests"

if( url.find('https://codeforces.com/') == -1):
	with open("main.cpp__tests", "w") as outfile:
		outfile.write('Please open a problem page')
	exit()
else:
	try:
Example #16
0
import pyscreeze
import os
from Singleton import Singleton
from threading import Lock

basedir = os.path.abspath(os.path.dirname(__file__))
imagedir = basedir + '\\' + 'images'
os.makedirs(imagedir, exist_ok=True)

try:
    browser = AutoApp().connect(title_re=".*Mozilla")
except:
    print("Can't find mozilla firefox")
    exit()

window = browser.top_window()
info = window.WrapperObject()
rect = info.rectangle()
oldX = -1
oldY = -1

try:
    window.MoveWindow(0, 0, 1347, 1028)
    SetForegroundWindow(info.handle)
    ShowWindow(info.handle, 5)
    SetFocus(info.handle)
    SetActiveWindow(info.handle)
except Exception as e:
    print(e)

#hse_name = hse_list[0]
for hse_name in hse_list:
    app = Application().start("C:\HOT2000 v11.3\HOT2000.exe")
    app.HOT2000.menu_select("File->Open")

    #hardcoding input hse folder path for now.
    app.Open.Edit.type_keys(
        "C:\\ERS_Database\\hse-to-h2k-conversion\\files_to_convert\\{}.HSE".
        format(hse_name))
    app.Open.Open.click()

    # spams enter to get by errors and messages. Hopefully 8 is enough?
    send_keys('{ENTER 8}')

    # Sleep while H2k does its thing.
    app.top_window().maximize()
    time.sleep(0.2)
    # Hot 2000 dialog name has changed.
    new_name = "HOT2000 - [{} - General]".format(hse_name)
    for y_coordinate in [130, 150, 170, 190, 210, 230, 250, 270]:
        pywinauto.mouse.click(button='left', coords=(50, y_coordinate))
        time.sleep(0.2)
        pywinauto.mouse.click(button='left', coords=(300, 130))
        send_keys('{ENTER}')
        time.sleep(0.1)
#Switch to summary view
    pywinauto.mouse.click(button='left', coords=(50, 100))
    time.sleep(0.02)

    for y_coordinate in [115, 130, 150, 220, 260, 280]:
        pywinauto.mouse.click(button='left', coords=(50, y_coordinate))
class unity():
    ''' 多账户交易集中处理 '''
    def __init__(self, main):
        self.main = main
        keystroke(main, F6)  # 切换到双向委托
        wait_a_second()  # 可调整区间值(0.01~0.5)

        # 打新快捷键554

        self.buff = ctypes.create_unicode_buffer(32)
        #            代码,价格,数量,买入,代码,价格,数量,卖出,全撤, 撤买, 撤卖
        id_members = 1032, 1033, 1034, 1006, 1035, 1058, 1039, 1008, 30001, 30002, 30003, \
                     32790, 1038, 1047, 2053, 30022, 1019  # 刷新,余额、表格、最后一笔、撤相同
        self.path_grid = 1047, 200, 1047
        self.ipo_grid_path = 0xe900, -1, 0x417, 0xc8, 0x417
        self.tree_path = 0xe900, 0xe900, 0x81, 0xc8, 0x81
        self.two_way = reduce(op.GetDlgItem, (59648, 59649), main)
        self.members = {i: op.GetDlgItem(self.two_way, i) for i in id_members}
        self.grid = reduce(op.GetDlgItem, self.path_grid, self.two_way)

        self.ipo_btn_path = 0xe900, 0xe901, 0x3ee
        self.ipo_btn_handle = reduce(op.GetDlgItem, self.ipo_btn_path, main)
        self.screen_width = op.GetSystemMetrics(0)
        self.screen_height = op.GetSystemMetrics(1)

        self.tree_handle = reduce(op.GetDlgItem, self.tree_path, main)
        self.ipo_grid_handle = reduce(op.GetDlgItem, self.ipo_grid_path, main)
        print_time(ctypes.WinError())
        print_time("tree_handle:%d ipo_grid_handle:%d" %
                   (self.tree_handle, self.ipo_grid_handle))
        print_time("members:")
        print_time(self.members)
        # 获取登录账号
        self.account = reduce(op.GetDlgItem, (59392, 0, 1711), main)
        op.SendMessageW(self.account, WM_GETTEXT, 32, self.buff)
        self.account = self.buff.value

        print_time("account:")
        print_time(self.account)

        # 撤单工具条
        self.id_toolbar = {'全选': 1098, \
                           '撤单': 1099, \
                           '全撤': 30001, \
                           '撤买': 30002, \
                           '撤卖': 30003, \
                           '填单': 3348, \
                           '查单': 3349}  # '撤尾单': 2053, '撤相同': 30022}    # 华泰独有

        op.SendMessageW(main, WM_COMMAND, 163, 0)  # 切换到撤单操作台
        wait_a_second()
        self.cancel_panel = reduce(op.GetDlgItem, (59648, 59649), main)
        self.cancel_toolbar = {
            k: op.GetDlgItem(self.cancel_panel, v)
            for k, v in self.id_toolbar.items()
        }
        keystroke(main, F6)  # 切换到双向委托
        self._app = Application().connect(handle=self.main)

    def buy(self, symbol, price, qty):  # 买入(B)
        # buy = order('b')
        self.__set_text(self.members[1032], symbol)
        self.__set_text(self.members[1033], price)
        # op.SendMessageW(self.members[1034], WM_SETTEXT, 0, qty)
        self.__set_text(self.members[1034], qty)
        op.PostMessageW(self.two_way, WM_COMMAND, 1006, self.members[1006])

    def sell(self, symbol, price, qty):  # 卖出(S)
        # buy = order('s')
        # op.SendMessageW(self.members[1035], WM_SETTEXT, 0, symbol)
        # op.SendMessageW(self.members[1058], WM_SETTEXT, 0, price)
        # op.SendMessageW(self.members[1039], WM_SETTEXT, 0, qty)
        self.__set_text(self.members[1035], symbol)
        self.__set_text(self.members[1058], price)
        self.__set_text(self.members[1039], qty)
        op.PostMessageW(self.two_way, WM_COMMAND, 1008, self.members[1008])

    def refresh(self):  # 刷新(F5)
        op.PostMessageW(self.two_way, WM_COMMAND, 32790, self.members[32790])

    def cancel_order(self, symbol=''):  # 撤单
        op.SendMessageW(self.main, WM_COMMAND, 163, 0)  # 切换到撤单操作台
        if symbol:
            op.SendMessageW(self.cancel_toolbar['填单'], WM_SETTEXT, 0, symbol)
            time.sleep(0.1)  # 必须有
            op.PostMessageW(self.cancel_panel, WM_COMMAND,
                            self.id_toolbar['查单'], self.cancel_toolbar['查单'])
            op.PostMessageW(self.cancel_panel, WM_COMMAND,
                            self.id_toolbar['撤单'], self.cancel_toolbar['撤单'])
            keystroke(self.main, F6)  # 必须返回双向委托操作台!

    def cancel_all(self):  # 全撤(Z)
        # op.PostMessageW(self.two_way, WM_COMMAND, 30001, self.members[30001])
        self._app.top_window().window_(best_match="全撤(Z)Button").wait(
            "visible", 0.5)
        self._app.top_window().window_(best_match="全撤(Z)Button",
                                       visible_only=True).click()

    def cancel_buy(self):  # 撤买(X)
        # op.PostMessageW(self.two_way, WM_COMMAND, 30002, self.members[30002])
        self._app.top_window().window_(best_match="撤买(X)Button").wait(
            "visible", 0.5)
        self._app.top_window().window_(best_match="撤买(X)Button",
                                       visible_only=True).click()
        # keyboard.SendKeys("X")

    def cancel_sell(self):  # 撤卖(C)
        # op.PostMessageW(self.two_way, WM_COMMAND, 30003, self.members[30003])
        self._app.top_window().window_(best_match="撤卖(C)Button").wait(
            "visible", 0.5)
        self._app.top_window().window_(best_match="撤卖(C)Button",
                                       visible_only=True).click()

    def cancel_last(self):  # 撤最后一笔,仅限华泰定制版有效
        op.PostMessageW(self.two_way, WM_COMMAND, 2053, self.members[2053])

    def cancel_same(self):  # 撤相同代码,仅限华泰定制版
        # op.PostMessageW(self.two_way, WM_COMMAND, 30022, self.members[30022])
        pass

    def is_client_dead(self):
        return 0 == SendMessageTimeout(self.main, WM_NULL, 0, 0,
                                       SMTO_ABORTIFHUNG | SMTO_BLOCK, 2000)

    def balance(self):  # 可用余额
        op.SendMessageW(self.members[1038], WM_GETTEXT, 32, self.buff)
        return self.buff.value

    def get_data(self, key='W'):
        """"将CVirtualGridCtrl|Custom<n>的数据复制到剪贴板,默认取持仓记录"""
        pyperclip.copy("")
        print_time("get data %c" % key)
        keystroke(self.main, F6)
        keystroke(self.two_way, ord(key))  # 切换到持仓('W')、成交('E')、委托('R')
        wait_a_second(8)  # 等待券商的数据返回...
        op.SendMessageW(self.grid, WM_COMMAND, 57634,
                        self.path_grid[-1])  # background mode
        time.sleep(1)
        return pyperclip.paste()

    @staticmethod
    def __set_text(handle, txt, by_msg=False):
        if by_msg:
            return op.SendMessageW(handle, WM_SETTEXT, 0, txt)
        else:
            Desktop()["股票交易系统"].window(handle=handle).set_text(txt)

    def type_keys(self, keys):
        # app = Application().connect(handle=self.main)
        # app["股票交易系统"].type_keys(keys)
        keyboard.SendKeys(keys)

    def ipo(self):
        pyperclip.copy("")
        app = Application().connect(handle=self.main)
        app["股票交易系统"].window(handle=self.tree_handle).select("\\新股申购\\新股批量申购")
        print_time(self.tree_handle)
        time.sleep(9)
        app.top_window()["确定"].click()
        print_time(" width:%d,height:%d", self.screen_width,
                   self.screen_height)
        self.ipo_grid_handle = op.WindowFromPoint(
            POINT(int(self.screen_width / 2), int(self.screen_height / 2)))
        print_time(ctypes.WinError())
        print_time(
            op.SendMessageW(self.ipo_grid_handle, WM_COMMAND, 57634,
                            self.ipo_grid_path[-1]))
        print_time("ipo grid handle:%d" % self.ipo_grid_handle)
        can_ipo = pyperclip.paste()
        print_time(ctypes.WinError())
        print_time(can_ipo)
        dict_ipo = util.BaseTypeUtil.analyze_position(can_ipo)
        pos = []
        for (j, k) in zip(dict_ipo.values(), range(1, 10, 1)):
            if float(dict(j).get("可申购数量")) > 0.99:
                pos.append(k)
        if len(pos) < 1:
            return
        rect = app.window(handle=self.ipo_grid_handle).rectangle()
        height = 16
        x = rect.left + 10
        first = rect.top + 20 + height / 2
        print_time(pos)
        for i in pos:
            y = first + (i - 1) * height
            print_time("x:%d,y:%d,i:%d" % (x, y, i))
            mouse_move_click(int(x), int(y))

        app["股票交易系统"]["申购Button"].click()
        time.sleep(9)
        app.top_window()["是Button"].click()
Example #19
0
class RS3Controller:
    def __init__(self, share_loc, RS3_loc):
        self.RS3_loc = RS3_loc
        self.share_loc = share_loc
        self.app = Application()
        self.save_dir = ''
        self.basename = ''
        self.nextnum = None
        self.hopefully_saved_files = []
        self.failed_to_open = False
        self.numspectra = None
        self.wr_success = False
        self.wr_failure = False
        self.opt_complete = False
        self.interval = 0.25

        try:
            #print(errortime)
            self.app = Application().connect(path=RS3_loc)
        except:
            print('\tStarting RS³')
            self.app = Application().start(RS3_loc)
        print('\tConnected to RS3')
        self.spec = None
        self.spec_connected = False
        self.spec = self.app.ThunderRT6Form
        self.spec.draw_outline()
        self.pid = self.app.process
        self.menu = RS3Menu(self.app)

    def check_connectivity(self):
        try:
            top_window = top = self.app.top_window()
        except Exception as e:
            print(e)
            return False
        try:
            top_element = findwindows.find_element(handle=top_window.handle)
            if top_element.name == 'TCP Servers Not Found.\r\nCheck Connection':
                return False
            elif top_element.name == 'Check Connection':
                return False
            elif top_element.name == 'Searching for TCP Servers...':
                return False
            elif top_element.name == 'TCP Servers Not Found.':
                return False
            elif top_element.name == 'Check Connection':
                return False
            elif top_element.name == 'Connecting...':
                print('Connecting...')
                return False

            elif 'Initializing' in top_element.name:
                print('Initializing...')
                return False

            elif 'Unable to connect' in top_element.name:
                return False
            elif top_element.name == 'RS³':
                return False
            elif 'was lost' in top_element.name:
                return False
            elif top_element.name == '':
                return True
            elif top_element.name == 'About':
                print('About, returning false')
                return False
            elif top_element.name == 'Unable to collect at current gain and offset values.  Please optimize instrument.':
                print('Optimize instrument before collecting data.')
                return True
            elif top_element.name == 'Type mismatch':
                return False

            elif 'Connected to' in top_element.name:
                return True
            elif top_element.name == 'RS³   18483 1':
                return True

            else:
                if 'Initial' in top_element.name:
                    print('Why is this initializing unexpected?')
                print('unexpected name:')
                print(top_element.name)
                return True

        except Exception as e:
            print(e)
            return True

    def take_spectrum(self, filename):
        self.spec.set_focus()
        time.sleep(1)
        pyautogui.press('space')

        self.hopefully_saved_files.append(
            filename)  #Know to expect this file in the data directory

        self.nextnum = str(int(self.nextnum) + 1)
        while len(self.nextnum) < INDEXNUMLEN:
            self.nextnum = '0' + self.nextnum

    def white_reference(self):
        self.spec.set_focus()
        keyboard.SendKeys('{F4}')
        start_timeout = 10
        t = 0
        started = False
        while not started and t < start_timeout:
            loc = find_image(
                IMG_LOC + '/status_color.png',
                rect=self.spec.ThunderRT6PictureBoxDC6.rectangle())
            if loc != None:
                started = True
            else:
                time.sleep(self.interval)
                t += self.interval
        if t >= start_timeout:
            print('wr failed')
            self.wr_failure = True
            return
        print('wr started')
        finish_timeout = 10 + int(self.numspectra) / 9
        t = 0
        finished = False
        while not finished and t < finish_timeout:
            loc = find_image(
                IMG_LOC + '/white_status.png',
                rect=self.spec.ThunderRT6PictureBoxDC6.rectangle())
            if loc != None:
                finished = True
            else:
                time.sleep(self.interval)
                t += self.interval
        if t >= finish_timeout:
            self.wr_failure = True
            print('wr failed')
            return
        time.sleep(
            2
        )  #This is important! Otherwise the spectrum won't be saved because the spacebar will get pushed before RS3 is ready for it.
        print('wr succeeded')
        self.wr_success = True

    #When you press optimize, first look for the word 'optimizing', then wait for the status bar to be white
    #for a few seconds. After that happens, wait for blue to turn up again in the status bar, and at that
    #point you are ready to take a spectrum.
    def optimize(self):
        self.opt_complete = False
        self.spec.set_focus()
        keyboard.SendKeys('^O')

        started = False
        t = 0
        timeout = 30
        while not started and t < timeout:
            loc = find_image(IMG_LOC + '/optimizing.png',
                             rect=self.spec.ThunderRT6Frame3.rectangle())
            if loc != None:
                started = True
                print('Initialized optimization')
            else:
                t += .1  #Note there is no sleeping. If we sleep, we might miss the words appearing on the screen, which aren't always there for long.
                if t % 5 == 0: print(t)
        if not started:
            print('opt timed out')
            raise Exception('Optimization timed out')

        time.sleep(
            int(self.numspectra) / 100
        )  #make sure we don't find the white status bar while it is still getting set up instead of after it completes.
        finished = False
        t = 0
        timeout = 10 + int(self.numspectra) / 9
        while not finished and t < timeout:
            loc = find_image(
                IMG_LOC + '/white_status.png',
                rect=self.spec.ThunderRT6PictureBoxDC5.rectangle())
            if loc != None:
                print('Found white status')
                while not finished and t < timeout:

                    loc = find_image(
                        IMG_LOC + '/white_status.png',
                        rect=self.spec.ThunderRT6PictureBoxDC5.rectangle())
                    if loc != None:
                        finished = True
                    else:
                        time.sleep(self.interval)
                        t = t + self.interval
            else:
                time.sleep(self.interval)
                t = t + self.interval
        if not finished:
            print('opt timed out 1')
            raise Exception('Optimization timed out')
        print('Completed optimization')

        ready = False
        t = 0
        timeout = 10 + int(self.numspectra) / 9
        while not ready and t < timeout:
            loc = find_image(
                IMG_LOC + '/status_color.png',
                rect=self.spec.ThunderRT6PictureBoxDC5.rectangle())
            if loc != None:
                ready = True
            else:
                time.sleep(self.interval)
                t = t + self.interval
        if not ready:
            print('opt timed out 2')
            raise Exception('Optimization timed out')
        sleep = int(self.numspectra) / 500 + 1
        time.sleep(sleep)
        print('Instrument ready')
        self.opt_complete = True

    def instrument_config(self, numspectra):
        pauseafter = False
        if self.numspectra == None or int(self.numspectra) < 20 or True:
            pauseafter = True
        self.numspectra = numspectra

        config = self.app['Instrument Configuration']
        if config.exists() == False:
            self.menu.open_control_dialog([
                IMG_LOC + '/rs3adjustconfig.png',
                IMG_LOC + '/rs3adjustconfig2.png'
            ])

        t = 0
        while config.exists() == False and t < 10:
            print('waiting for instrument config panel')
            time.sleep(self.interval)
            t += self.interval

        if config.exists() == False:
            print('ERROR: Failed to open instrument configuration dialog')
            self.failed_to_open = True
            return

        config.Edit3.set_edit_text(
            str(numspectra)
        )  #probably done twice to set numspectra for wr and taking spectra.
        config.Edit.set_edit_text(str(numspectra))
        config.set_focus()
        config.ThunderRT6PictureBoxDC.click_input()
        if pauseafter:
            time.sleep(2)
        print('Instrument configuration set with ' + str(numspectra) +
              ' spectra being averaged')

    def spectrum_save(self,
                      dir,
                      base,
                      startnum,
                      numfiles=1,
                      interval=0,
                      comment=None,
                      new_file_format=False):
        self.save_dir = dir
        self.basename = base
        self.nextnum = str(startnum)

        while len(self.nextnum) < INDEXNUMLEN:
            self.nextnum = '0' + self.nextnum
        save = self.app['Spectrum Save']
        if save.exists() == False:
            self.menu.open_control_dialog(
                [IMG_LOC + '/rs3specsave.png', IMG_LOC + '/rs3specsave2.png'])
        for _ in range(int(2.5 / self.interval)):
            save = self.app['Spectrum Save']
            if save.exists():
                break
            else:
                print('no spectrum save yet')
                time.sleep(self.interval)

        if save.exists() == False:
            print('ERROR: Failed to open save dialog')
            raise Exception
            return
        save.Edit6.set_edit_text(dir)
        save.Edit7.set_edit_text('')
        save.Edit5.set_edit_text(base)
        save.Edit4.set_edit_text(startnum)

        save.set_focus()
        okfound = False
        controls = [
            save.ThunderRT6PictureBoxDC3, save.ThunderRT6PictureBoxDC2,
            save.ThunderRT6PictureBox
        ]
        while True:
            for control in controls:
                control.draw_outline()
                rect = control.rectangle()
                loc = find_image(IMG_LOC + '/rs3ok.png', rect=rect)
                if loc != None:
                    control.click_input()
                    okfound = True
                    break
            if okfound:
                break
            print('searching for OK button')
            time.sleep(0.5)

        message = self.app['Message']
        if message.exists():
            self.app['Message'].set_focus()
            keyboard.SendKeys('{ENTER}')
Example #20
0
root = arquivo.read()
arquivo.close()

# ENTRA NO DIRETORIO E PROCURA POR ARQUIVOS JPG
qt_lida = 0
porcento = 0
nomeprocesso = os.getpid()
for path, subdirs, files in os.walk(root):
    for name in files:
        if fnmatch(name,
                   pattern):  # se nome do arquivo do subdir tiver a extensao
            dir = os.path.join(path, name)
            if os.path.isfile(
                    dir +
                    ".txt") == 0:  # se nao existir o .txt com texto, cria
                os.system("cls")
                comandoAbrir = "start " + dir
                comandoFechar = "taskkill.exe /IM Microsoft.Photos.exe /F"
                os.system(comandoFechar)
                os.system(comandoAbrir)
                print(dir)
                app = Application().connect(process=int(nomeprocesso))
                app.top_window().set_focus()
                nome = input("NOME>>>")
                img = Image.open(dir)
                draw = ImageDraw.Draw(img)
                texto = nome
                font = ImageFont.truetype("arial-bold.ttf", 36)
                draw.text((50, 50), nome, (0, 0, 0), font=font)
                img.save(dir)
Example #21
0
	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
Example #22
0
class RS3Controller:
    def __init__(self, share_loc, RS3_loc):
        self.RS3_loc = RS3_loc
        self.share_loc = share_loc
        self.app = Application()
        self.save_dir = ""
        self.basename = ""
        self.nextnum = None
        self.hopefully_saved_files = []
        self.failed_to_open = False
        self.numspectra = None
        self.wr_success = False
        self.wr_failure = False
        self.opt_complete = False
        self.interval = 0.25

        try:
            self.app = Application().connect(path=self.RS3_loc)
        except:
            print("\tStarting RS³")
            self.app = Application().start(self.RS3_loc)
        print("\tConnected to RS3")
        self.spec = None
        self.spec_connected = False
        self.spec = self.app.ThunderRT6Form
        self.spec.draw_outline()
        self.pid = self.app.process
        self.menu = RS3Menu(self.app)

    def restart(self):
        self.spec.set_focus()
        rect = self.spec.rectangle()
        print(rect)
        loc = find_image(IMG_LOC + "/exit.png", rect=rect)
        if loc is not None:
            x_left = self.spec.rectangle().left
            y_top = self.spec.rectangle().top
            while x_left < -10 or y_top < -10:
                x_left = self.spec.rectangle().left
                y_top = self.spec.rectangle().top
                time.sleep(0.25)
            x = loc[0] + x_left
            y = loc[1] + y_top
            mouse.click(coords=(x, y))
            print("clicked x")
            time.sleep(0.5)
            keyboard.send_keys("{ENTER}")
            time.sleep(10)
            self.app = Application().start(self.RS3_loc)
            self.spec = None
            self.spec_connected = False
            self.spec = self.app.ThunderRT6Form
            self.spec.draw_outline()
            self.pid = self.app.process
            self.menu = RS3Menu(self.app)
        else:
            print("Error: Failed to restart RS3")

    def check_connectivity(self):
        try:
            top_window = self.app.top_window()
        except Exception as e:
            print("Cannot find top window")
            print(e)
            return False
        try:
            top_element = findwindows.find_element(handle=top_window.handle)
            if top_element.name == "TCP Servers Not Found.\r\nCheck Connection":
                return False
            elif top_element.name == "Check Connection":
                return False
            elif top_element.name == "Searching for TCP Servers...":
                return False
            elif top_element.name == "TCP Servers Not Found.":
                return False
            elif top_element.name == "Check Connection":
                return False
            elif top_element.name == "Connecting...":
                print("Connecting...")
                return False

            elif "Initializing" in top_element.name:
                print("Initializing...")
                return False

            elif "Unable to connect" in top_element.name:
                return False
            elif "Address in use" in top_element.name:
                return False
            elif top_element.name == "RS³":
                return False
            elif "was lost" in top_element.name:
                return False
            elif top_element.name == "":
                return True
            elif top_element.name == "About":
                # print('About, returning false')
                return False
            elif (top_element.name ==
                  "Unable to collect at current gain and offset values.  Please optimize instrument."
                  ):
                print("Optimize instrument before collecting data.")
                return True
            elif top_element.name == "Type mismatch":
                return False

            elif "Connected to" in top_element.name:
                return True
            elif top_element.name == "RS³   18483 1":
                return True
            elif top_element.name == "Spectrum Save":
                return True
            elif top_element.name == "Take White Reference Measurement":
                return True
            elif top_element.name == "Instrument Configuration":
                return True
            elif "Initial" in top_element.name:
                # This should be redundant with the check for "Initializing" but it catches an extra message
                return True
            else:
                if "Initial" in top_element.name:
                    print("Why is this initializing unexpected?")
                print("unexpected name:")
                print(top_element.name)
                return True

        except Exception as e:
            print(e)
            return True

    def take_spectrum(self, filename):
        focused = try_set_focus(self.spec)
        if not focused:
            return False
        time.sleep(1)
        pyautogui.press("space")

        self.hopefully_saved_files.append(
            filename)  # Know to expect this file in the data directory

        self.nextnum = str(int(self.nextnum) + 1)
        while len(self.nextnum) < INDEXNUMLEN:
            self.nextnum = "0" + self.nextnum
        return True

    def white_reference(self):
        if (
                int(self.numspectra) < 100
        ):  # WR often fails for small numbers of spectra, I think maybe because it hasn't finished catching up after optimizing?
            time.sleep(2)
        focused = try_set_focus(self.spec)
        if not focused:
            self.wr_failure = True
            return
        keyboard.send_keys("{F4}")
        start_timeout = 10
        t = 0
        started = False
        while not started and t < start_timeout:
            loc = find_image(
                IMG_LOC + "/status_color.png",
                rect=self.spec.ThunderRT6PictureBoxDC6.rectangle())
            if loc != None:
                started = True
            else:
                time.sleep(self.interval)
                t += self.interval
                if t % 2 == 0:
                    print(t)
                    print(start_timeout)
        if t >= start_timeout:
            print("wr failed")
            self.wr_failure = True
            return
        print("wr started")
        finish_timeout = 10 + int(self.numspectra) / 9
        t = 0
        finished = False
        while not finished and t < finish_timeout:
            loc = find_image(
                IMG_LOC + "/white_status.png",
                rect=self.spec.ThunderRT6PictureBoxDC6.rectangle())
            if loc is not None:
                finished = True
            else:
                time.sleep(self.interval)
                t += self.interval
                if t % 2 == 0:
                    print(finish_timeout)
                    print(t)
        if t >= finish_timeout:
            self.wr_failure = True
            print("wr failed")
            return
        time.sleep(
            2
        )  # This is important! Otherwise the spectrum won't be saved because the spacebar will get pushed before RS3 is ready for it.
        print("wr succeeded")
        self.wr_success = True

    # When you press optimize, first look for the word 'optimizing', then wait for the status bar to be white
    # for a few seconds. After that happens, wait for blue to turn up again in the status bar, and at that
    # point you are ready to take a spectrum.
    def optimize(self):
        self.opt_complete = False
        focused = try_set_focus(self.spec)
        if not focused:
            return False
        keyboard.send_keys("^O")

        started = False
        t = 0
        timeout = 30
        while not started and t < timeout:
            loc = find_image(IMG_LOC + "/optimizing.png",
                             rect=self.spec.ThunderRT6Frame3.rectangle())
            if loc != None:
                started = True
                print("Initialized optimization")
            else:
                t += 0.1  # Note there is no sleeping. If we sleep, we might miss the words appearing on the screen, which aren't always there for long.
                if t % 5 == 0:
                    print(t)
        if not started:
            print("opt timed out")
            raise Exception("Optimization timed out")

        time.sleep(
            1 + int(self.numspectra) / 25
        )  # make sure we don't find the white status bar while it is still getting set up instead of after it completes.
        finished = False
        t = 0
        timeout = 10 + int(self.numspectra) / 9
        while not finished and t < timeout:
            loc = find_image(
                IMG_LOC + "/white_status.png",
                rect=self.spec.ThunderRT6PictureBoxDC5.rectangle())
            if loc != None:
                print("Found white status")
                while not finished and t < timeout:

                    loc = find_image(
                        IMG_LOC + "/white_status.png",
                        rect=self.spec.ThunderRT6PictureBoxDC5.rectangle())
                    if loc != None:
                        finished = True
                    else:
                        time.sleep(self.interval)
                        t = t + self.interval
            else:
                time.sleep(self.interval)
                t = t + self.interval
        if not finished:
            print("opt timed out 1")
            raise Exception("Optimization timed out")

        ready = False
        t = 0
        timeout = 10 + int(self.numspectra) / 9
        while not ready and t < timeout:
            loc = find_image(
                IMG_LOC + "/status_color.png",
                rect=self.spec.ThunderRT6PictureBoxDC5.rectangle())
            if loc != None:
                ready = True
            else:
                time.sleep(self.interval)
                t = t + self.interval
        if not ready:
            print("opt timed out 2")
            raise Exception("Optimization timed out")
        sleep = int(self.numspectra) / 500 + 1
        time.sleep(sleep)
        print("Instrument ready")
        self.opt_complete = True

    def instrument_config(self, numspectra):
        pauseafter = False
        if self.numspectra == None or int(self.numspectra) < 20 or True:
            pauseafter = True
        self.numspectra = numspectra

        config = self.app["Instrument Configuration"]
        if config.exists() == False:
            self.menu.open_control_dialog([
                IMG_LOC + "/rs3adjustconfig.png",
                IMG_LOC + "/rs3adjustconfig2.png"
            ])

        t = 0
        while config.exists() == False and t < 10:
            print("waiting for instrument config panel")
            time.sleep(self.interval)
            t += self.interval

        if config.exists() == False:
            print("ERROR: Failed to open instrument configuration dialog")
            self.failed_to_open = True
            return

        config.Edit3.set_edit_text(
            str(numspectra)
        )  # probably done twice to set numspectra for wr and taking spectra.
        config.Edit.set_edit_text(str(numspectra))
        focused = try_set_focus(config)
        if not focused:
            self.failed_to_open = True
            return
        config.ThunderRT6PictureBoxDC.click_input()
        if pauseafter:
            time.sleep(2)
        print("Instrument configuration set with " + str(numspectra) +
              " spectra being averaged")

    def spectrum_save(self,
                      dir,
                      base,
                      startnum,
                      numfiles=1,
                      interval=0,
                      comment=None,
                      new_file_format=False):
        self.save_dir = dir
        self.basename = base
        self.nextnum = str(startnum)

        while len(self.nextnum) < INDEXNUMLEN:
            self.nextnum = "0" + self.nextnum
        save = self.app["Spectrum Save"]
        if save.exists() == False:
            self.menu.open_control_dialog(
                [IMG_LOC + "/rs3specsave.png", IMG_LOC + "/rs3specsave2.png"])
        for _ in range(int(2.5 / self.interval)):
            save = self.app["Spectrum Save"]
            if save.exists():
                break
            else:
                print("no spectrum save yet")
                time.sleep(self.interval)

        if save.exists() == False:
            print("ERROR: Failed to open save dialog")
            raise Exception
            return
        save.Edit6.set_edit_text(dir)
        save.Edit7.set_edit_text("")
        save.Edit5.set_edit_text(base)
        save.Edit4.set_edit_text(startnum)

        focused = try_set_focus(save)
        if not focused:
            print("ERROR: Failed to set focus on save dialog")
            raise Exception
            return
        okfound = False
        controls = [
            save.ThunderRT6PictureBoxDC3, save.ThunderRT6PictureBoxDC2,
            save.ThunderRT6PictureBox
        ]
        t = 15
        while t > 0:
            for control in controls:
                control.draw_outline()
                rect = control.rectangle()
                loc = find_image(IMG_LOC + "/rs3ok.png", rect=rect)
                if loc != None:
                    control.click_input()
                    okfound = True
                    break
            if okfound:
                break
            print("searching for OK button")
            time.sleep(0.5)
            t -= 0.5
        if t < 0:
            raise Exception("Timed out looking for OK button")

        message = self.app["Message"]
        if message.exists():
            self.app["Message"].set_focus()
            keyboard.send_keys("{ENTER}")
Example #23
0
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
Example #24
0
class SpotiHideGui(object):
    def __init__(self):
        self.__cmd_path = 'C:\WINDOWS\system32\cmd.exe'
        self.__spotify_path = os.path.join(
            'C:\\Users', getuser(), 'AppData\\Roaming\\Spotify\\Spotify.exe')
        self.__cmd = None
        self.__spotify = None
        self.__cmd_window = None
        self.__spotify_window = None

    def spotify_console(self):
        """
        """
        switch = {
            'add': self.add,
            'show': self.show,
            'help': self.help,
            'exit': self.exit
        }
        while True:
            self.spotify_window = None
            self.show_spotify_window()
            self.cmd_set_focus()
            command = input(
                colored.stylize("""\nSpotify > """,
                                colored.fg("light_green_3")))
            params = command.split()
            try:
                switch[params[0]](*params[1:])
            except KeyError:
                print(
                    colored.stylize("""\n[*] """, colored.fg("light_red")) +
                    'Unknown command: %s\n' % (command))
            except IndexError:
                try:
                    switch[params[0]]()
                except KeyError:
                    print(
                        colored.stylize("""\n[*] """, colored.fg("light_red"))
                        + 'Unknown command: %s\n' % (command))
                except IndexError:
                    pass
            except SystemExit:
                return

    def add(self, *args):
        """
        """
        if args and len(args) == 1:
            try:
                self.spotify_set_focus()
                self.spotify_window.maximize()
                self.spotify_window_button(title='Local Files',
                                           control_type='Hyperlink')
                time.sleep(0.5)
                self.spotify_direct_button('Custom2')
                send_keys('^a')
                self.spotify_direct_button('Custom2', 'right')
                self.spotify_window_button(title='Add to Playlist',
                                           control_type='Text')
                self.spotify_window_button(title=args[0], control_type='Text')
                time.sleep(1)
                send_keys('{ENTER}')
            except Exception:
                print(
                    colored.stylize("""\n[*] """, colored.fg("light_red")) +
                    "Timeout error, element not found!\n")
                raise KeyError
        else:
            print("\nUsage:\tadd PLAYLIST")
            raise KeyError

    def show(self, *args):
        """
        """
        if args and len(args) == 1 and args[0] == 'local':
            self.show_spotify_window()
            while True:
                try:
                    #time.sleep(5)
                    send_keys('^p')
                    self.spotify_window_button(title="Settings",
                                               control_type="Document")
                    break
                except TimeoutError:
                    pass
            while True:
                try:
                    self.spotify_window_button(title="Show Local Files",
                                               control_type="CheckBox",
                                               timeout=1)
                    #if show_local_files_checkbox.get_toggle_state() == 0:
                    #    show_local_files_checkbox.click_input()
                    return
                except TimeoutError:
                    send_keys('{DOWN 6}')
            self.cmd_set_focus()
        else:
            print("\nUsage:\tshow local")
            raise KeyError

    def help(self, *args):
        if not args:
            print(
                colored.stylize("""\n[*] """, colored.fg("light_green_3")) +
                "Usage:\tshow local")
            print("\n\t\tadd PLAYLIST")
        else:
            raise KeyError

    def exit(self, *args):
        """Exit function.

            :param args:
            :type args: list
        """
        self.spotify_window.close()
        if not args:
            raise SystemExit
        else:
            raise KeyError

    def show_spotify_window(self):
        """
        """
        try:
            self.cmd = Application(backend="win32").connect(path=self.cmd_path)
            self.cmd_window = self.cmd.top_window()
            self.spotify = Application(backend="uia").connect(
                title_re=r'Spotify.*')
            self.spotify_window = self.spotify.window(title_re=r'Spotify.*')
            self.spotify_set_focus()
        except ElementNotFoundError:
            self.spotify = Application(backend="uia").start(self.spotify_path)
            self.spotify_window = self.spotify.window(title_re=r'Spotify.*')
        except Exception:
            print(
                colored.stylize("""\n[*] """, colored.fg("light_red")) +
                "Timeout error, restart Spotify!\n")
            raise KeyError
        finally:
            self.spotify_window.maximize()

    def spotify_set_focus(self):
        """
        """
        self.spotify_window.set_focus()

    def cmd_set_focus(self):
        """
        """
        self.cmd_window.set_focus()

    def spotify_window_button(self,
                              title=None,
                              auto_id=None,
                              control_type=None,
                              timeout=10,
                              retry_interval=1):
        """
        """
        try:
            spotify_window_button = self.spotify_window.child_window(
                title=title, auto_id=auto_id, control_type=control_type).wait(
                    'visible', timeout=timeout,
                    retry_interval=retry_interval).click_input()
        except Exception as e:
            spotify_window_button = self.spotify_window.child_window(
                title=title,
                auto_id=auto_id,
                found_index=1,
                control_type=control_type).wait(
                    'visible', timeout=timeout,
                    retry_interval=retry_interval).click_input()

    def spotify_direct_button(self,
                              label,
                              button='left',
                              timeout=10,
                              retry_interval=1):
        self.spotify_window.label.wait(
            'visible', timeout=timeout,
            retry_interval=retry_interval).click_input(button=button)

    @property
    def spotify_path(self):
        """
            :returns: spotify_path
            :rtype: str
        """
        return self.__spotify_path

    @spotify_path.setter
    def spotify_path(self, value):
        self.__spotify_path = value

    @property
    def spotify(self):
        """
            :returns: spotify
            :rtype: str
        """
        return self.__spotify

    @spotify.setter
    def spotify(self, value):
        self.__spotify = value

    @property
    def spotify_window(self):
        """
            :returns: spotify window
            :rtype: str
        """
        return self.__spotify_window

    @spotify_window.setter
    def spotify_window(self, value):
        self.__spotify_window = value

    @property
    def cmd_path(self):
        """
            :returns: cmd_path
            :rtype: str
        """
        return self.__cmd_path

    @cmd_path.setter
    def cmd_path(self, value):
        self.__cmd_path = value

    @property
    def cmd(self):
        """
            :returns: cmd
            :rtype: str
        """
        return self.__cmd

    @cmd.setter
    def cmd(self, value):
        self.__cmd = value

    @property
    def cmd_window(self):
        """
            :returns: cmd window
            :rtype: str
        """
        return self.__cmd_window

    @cmd_window.setter
    def cmd_window(self, value):
        self.__cmd_window = value
Example #25
0
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()
Example #26
0
    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")
Example #27
0
from os import path
from pywinauto import Application
import win32api

rhino = "C:\Program Files\Rhinoceros 5 (64-bit)\System\Rhino.exe"

app = Application(backend="uia")

app.start(rhino)

print(app.top_window())
Example #28
0
chrome[tab_log_in].child_window(title="Google Chrome", control_type="Custom").\
    child_window(title="Back", control_type="Image").wait(wait_for='visible', timeout=10)

chrome.window().type_keys('testpywinauto123{ENTER}')  # password
ch_window.child_window(title="Getting started PDF",
                       control_type="ListItem").wait(wait_for='visible')

# start explorer in the current path
dir_path = path.join(path.dirname(path.realpath(__file__)), 'UIA_Drive')
explorer = Application().start('explorer.exe ' + dir_path)
Desktop(backend='uia').window(title='UIA_Drive',
                              active_only=True).wait('visible', timeout=10)
dlg = Application(backend='uia').connect(path='explorer.exe',
                                         title='UIA_Drive')

# find file
file = dlg.UIA_Drive.ItemsView.wrapper_object().get_item('test.zip')

# drag n drop
destination = chrome.top_window().wrapper_object()
file.press_mouse_input(coords=file.rectangle().mid_point())
file.move_mouse_input(coords=destination.rectangle().mid_point())
chrome.top_window().set_focus()
file.release_mouse_input(coords=destination.rectangle().mid_point())

# wait upload file
ch_window.child_window(title="test.zip Compressed Archive",
                       control_type="ListItem").wait('visible')

print('DONE')
ch_window = chrome[tab_drive].child_window(title="Google Chrome", control_type="Custom")

# log in
chrome.window().type_keys('TestPywinauto{ENTER}')  # username
chrome[tab_log_in].child_window(title="Google Chrome", control_type="Custom").\
    child_window(title="Back", control_type="Image").wait(wait_for='visible', timeout=10)

chrome.window().type_keys('testpywinauto123{ENTER}')  # password
ch_window.child_window(title="Getting started PDF", control_type="ListItem").wait(wait_for='visible')

# start explorer in the current path
dir_path = path.join(path.dirname(path.realpath(__file__)), 'UIA_Drive')
explorer = Application().start('explorer.exe ' + dir_path)
Desktop(backend='uia').window(title='UIA_Drive', active_only=True).wait('visible', timeout=10)
dlg = Application(backend='uia').connect(path='explorer.exe', title='UIA_Drive')

# find file
file = dlg.UIA_Drive.ItemsView.wrapper_object().get_item('test.zip')

# drag n drop
destination = chrome.top_window().wrapper_object()
file.press_mouse_input(coords=file.rectangle().mid_point())
file.move_mouse_input(coords=destination.rectangle().mid_point())
chrome.top_window().set_focus()
file.release_mouse_input(coords=destination.rectangle().mid_point())

# wait upload file
ch_window.child_window(title="test.zip Compressed Archive", control_type="ListItem").wait('visible')

print('DONE')