def typeString(s): #m = PyMouse() k = PyKeyboard() #print args #k.press_keys(args) k.type_string(s)
def sendMessage(message): if Var.locked: return if not (type(message) is str): try: message = str(message) except Exception: pass try: message = message.encode('ascii', 'ignore') except Exception: message = message.encode('utf-8', 'ignore') Var.locked = True k = PyKeyboard() try: k.type_string(message) except Exception: k.press_key(k.control_l_key) k.tap_key('A') k.release_key(k.control_l_key) k.tap_key(k.backspace_key) k.type_string("Message Contains Unknown Characters") k.tap_key(k.enter_key) Var.locked = False
class Keyboard(object): def __init__(self): super(Keyboard, self).__init__() self.k = PyKeyboard() def write(self,text): self.k.type_string(text)
def type_msg(string): """ Stimulates typing a string of characters Args: string (str) : A string of characters to enter """ k = PyKeyboard() k.type_string(string)
def run(self): # Set up the keyboard sim K = PyKeyboard() # Let the program start running # Run till it's over. if self.lines: for i in lines: K.type_string(str(i))
def run(self, some_input=[]): # print("Run") # How long to run for counter = 0 # Remove "run" from the input some_input.pop(0) # Get the run number for i in some_input: if i == "cmd": command(some_input) elif i: try: counter = int(i) except ValueError: print("Value Error in Run") pass finally: some_input.remove(i) # If the counter didn't get defined. if counter == 0: counter = len(self.list_of_runs) # NOW we can run. We should check the length of the # command sequences, and the number of runs i = 0 # times through string = "" # string that will be printed length = len(self.list_of_runs) # Allow for 5 seconds to change windows print("Please Change Windows Now.") sleep(5) some_keyboard = PyKeyboard() # DO WORK YO while i < counter and i < length: string = self.list_of_runs.pop(0) sys.stdout.write(string) some_keyboard.type_string(string) sleep(self.sleep_num) i += 1 # Reset the variable if empty. if not self.list_of_runs: self.list_of_runs.append("")
def type_unicode(symbol): k = PyKeyboard() hexval = symbol.encode("unicode_escape") print hexval if hexval[:2] == '\u': # if the value is a hex number k.press_key('Control_L') # press the control k.press_key('Shift_L') # the left shift k.tap_key('u') # and the u key k.release_key('Control_L') # release the control k.release_key('Shift_L') # and shift keys hexval = hexval[2:] # remove the unicode escape character k.type_string(hexval) # type the unicode string k.tap_key('Return') # tap the return key else: # if the given string isnt a unicode character k.type_string(hexval) # just type the string
def main(): #Get an instance of PyKeyboard, and our custom PyMouseEvent keyboard = PyKeyboard() mouse = AbortMouse() input('Press Enter when ready.') print('Typing will begin in {0} seconds...'.format(opts['--pause'])) time.sleep(opts['--pause']) mouse.start() with open(opts['<file>'], 'r') as readfile: for line in readfile: if not mouse.state: print('Typing aborted!') break keyboard.type_string(line, opts['--interval'])
def main(): """ Retrieves the ID of the attached Card and returns it as keyboard-presses """ while True: try: # define the apdus used in this script apdu = [0xFF, 0xCA, 0x00, 0x00, 0x00] # request card insertion card_request = CardRequest(timeout=None, cardType=AnyCardType(), newcardonly=True) card_service = card_request.waitforcard() # connect to the card and perform a few transmits card_service.connection.connect() response, sw1, sw2 = card_service.connection.transmit(apdu) rfid_string = '_'.join([str(id_val) for id_val in response]) keyboard = PyKeyboard() keyboard.type_string('<U>RFID_ID_'+rfid_string) except: continue
def pLabel(pep,spec,gene,row_no): m = PyMouse() k = PyKeyboard() # ALL button m.click(1243,204) sleep(2) m.click(362,762) sleep(1) m.click(362,762) sleep(0.3) m.click(362,762) sleep(1) for n in range(30): k.press_key(k.backspace_key) sleep(1) k.type_string(spec) sleep(1) k.press_key(k.enter_key) sleep(1) capture(pep,spec,gene,row_no,0) sleep(1) m.click(609,182) sleep(1) # peptide m.click(132,728) sleep(1) m.click(132,728) sleep(0.3) m.click(132,728) sleep(1) k.press_key(k.backspace_key) sleep(1) k.type_string(pep) sleep(1) k.press_key(k.enter_key) sleep(1) capture(pep,spec,gene,row_no,1) sleep(1)
def runScript(delay, SCRIPT_PATH, SCRIPT_NAME): screen = wnck.screen_get(0) #screen = wnck.screen_get_default() while gtk.events_pending(): gtk.main_iteration() windowTitle = re.compile('.*Board.*') for window in screen.get_windows(): if windowTitle.match(window.get_name()): window.activate(int(time.time())) window.maximize() #MOUSE CLICK TO ACTUALLY FOCUS EAGLE BOARD m = PyMouse() x, y = m.screen_size() #m.click(x/4, y/4, 1) #KEYBOARD INPUT k = PyKeyboard() caps_flag = 0 if int(commands.getoutput('xset q | grep LED')[65]) % 2: k.tap_key(k.caps_lock_key) caps_flag = 1 #BRING UP ALT-FILE MENU k.press_key(k.alt_key) k.type_string('f') k.release_key(k.alt_key) #PRESS T TO RUN SCRIPT FROM ALT-FILE MENUs k.type_string('t') time.sleep(delay) #TYPE IN SCRIPT NAME TO DIALOG BOX k.type_string(SCRIPT_PATH + SCRIPT_NAME) time.sleep(delay) time.sleep(delay) k.tap_key(k.enter_key) if caps_flag: k.tap_key(k.caps_lock_key)
def runScript(delay, SCRIPT_NAME): #screen = wnck.screen_get_default() screen = wnck.screen_get(0) while gtk.events_pending(): gtk.main_iteration() windowTitle = re.compile('.*Board.*') for window in screen.get_windows(): if windowTitle.match(window.get_name()): window.activate(int(time.time())) window.maximize() #MOUSE CLICK TO ACTUALLY FOCUS EAGLE BOARD m = PyMouse() x, y = m.screen_size() #m.click(x/4, y/4, 1) #KEYBOARD INPUT k = PyKeyboard() #BRING UP ALT-FILE MENU k.press_key(k.alt_key) k.type_string('f') k.release_key(k.alt_key) #PRESS T TO RUN SCRIPT FROM ALT-FILE MENU k.type_string('t') time.sleep(delay) #TYPE IN SCRIPT NAME TO DIALOG BOX k.type_string('/home/anton/Documents/st/st-py/' + SCRIPT_NAME) time.sleep(delay) time.sleep(delay) k.tap_key(k.enter_key)
time.sleep(0.1) m.click(x_dim / 2, y_dim / 2, 1) time.sleep(0.1) k.press_key(k.alt_key) time.sleep(0.1) k.tap_key(k.tab_key) time.sleep(0.1) k.release_key(k.alt_key) time.sleep(0.1) for _ in range(50): m.click(x_dim * 0.95, y_dim / 2, 1) time.sleep(0.1) k.press_key(k.control_key) time.sleep(0.1) k.type_string("a") time.sleep(0.1) k.release_key(k.control_key) time.sleep(0.1) k.press_key(k.control_key) time.sleep(0.1) k.type_string("c") time.sleep(0.1) k.release_key(k.control_key) time.sleep(0.1) k.press_key(k.alt_key) time.sleep(0.1) k.tap_key(k.tab_key) time.sleep(0.1) k.release_key(k.alt_key) time.sleep(0.1)
print 'Mouse at '+str(curr_posi)+'(timeout in '+str(i+1)+'/'+str(timer_max)+')' if curr_posi == prev_posi == oldr_posi: mouse_ready = True; break else: oldr_posi = prev_posi; prev_posi = curr_posi; time.sleep(0.5) if mouse_ready: print "I'm going to click at"+str(curr_posi) m.click(m.position()[0],m.position()[1]) time.sleep(0.5) # Shot number k.type_string(str(shotnr)) k.tap_key(k.tab_key) #Iplasma in kA k.type_string('{0:.2f}'.format(iplasma_mean_val)) k.tap_key(k.tab_key) #density in *1e18m-3 k.type_string('{0:.2f}'.format(dens_mean_val)) k.tap_key(k.tab_key) #duration in ms k.type_string(str(int((iplasma_shot_time//25)*25))) k.tap_key(k.tab_key) #Shot comments k.type_string('Sn-spectra, ') k.type_string('Sn cold at a)XXXX cm. ') k.type_string('P_ed)XXXX . ')
return def moveMouseAndClick(p,delay=MOVE_DELAY): moveMouse(p,delay) pyautogui.leftClick() return def moveMouseAndDoubleClick(p,delay=MOVE_DELAY): moveMouse(p,delay) pyautogui.doubleClick() return i=0 for comSeq in comSeqs: moveMouseAndClick(p1) moveMouseAndClick(p2, 2) moveMouseAndClick(p3) moveMouseAndClick(p4) moveMouseAndClick(p5, 5) k.type_string('100093') moveMouseAndClick(p6) moveMouseAndDoubleClick(p7,5) moveMouseAndClick(p8) moveMouseAndClick(p9) moveMouseAndClick(p10) pyautogui.moveTo(p12[0],p12[1]) pyautogui.dragRel(50, 50) moveMouseAndClick(p11,5) moveMouseAndDoubleClick((p13[0], p13[1]+(comSeq*18))) moveMouseAndClick(p15) moveMouseAndClick(p14) #break
if (len(sys.argv) > 1): associate_flag = int(sys.argv[1]) RUNNING_TIME = int(sys.argv[2]) AI_BOTS_DIR = sys.argv[3] RESULT_DIR = sys.argv[4] BIND_CPU = int(sys.argv[5]) HUMAN_RUN = int(sys.argv[6]) Reso_Width = int(sys.argv[7]) Reso_Hight = int(sys.argv[8]) MultipleMode = int(sys.argv[9]) #terminalFocus=[200,200,200,200] terminalFocus = [980, 980, 540, 540] keyboard_action.mouse_click(terminalFocus) time.sleep(1) key_board = PyKeyboard() key_board.type_string('cd $CGR_BENCHMARK_PATH/') key_board.tap_key(key_board.enter_key) key_board.type_string('./collectData.sh supertuxkart-1 ' + str(associate_flag) + ' ' + str(RUNNING_TIME) + ' ' + str(BIND_CPU) + ' ' + str(HUMAN_RUN) + ' ' + str(MultipleMode) + ' &') key_board.tap_key(key_board.enter_key) time.sleep(5) key_board.tap_key(key_board.enter_key) time.sleep(3) RUNNING_TIME -= 30 #frequently modified parameters logs_path = AI_BOTS_DIR + '/training_scripts/AI-models/supertuxkart-1/lstm-logs/' n_input = 1 # sequential input vector numbers for lstm tensor_size = 6 # length of each input vector
#!/usr/bin/python import time import thread from pymouse import PyMouse from pykeyboard import PyKeyboard m = PyMouse() k = PyKeyboard() x_dim, y_dim = m.screen_size() m.click(x_dim/2, y_dim/2, 1) k.type_string('Hello, Sir!') # print "This prints once a minute." current_time = time.time() time_to_sleep = 10 - (current_time % 10) time.sleep(time_to_sleep) while True: reply = raw_input('Enter you_re name, [tpye "stop" to quit]: ') print reply.lower() if reply == 'stop': break for counter in range(1, 6): print counter
new_result = line.split() #t = (float(result[0])*100) #print result[0] # result = map(lambda x: (0, float(x) % 360)[(float(x)) != 0.0], result) def slow_func(x): return x*x*x try: result = map(lambda i: alpha_result * float(new_result[i]) + \ (1.0 - alpha_result) * result[i], range(len(new_result))) print result # Using older convention # mouse_x = center_x + int(result[0]*screen_size[0]/100.0) # mouse_y = center_y + int((result[1])*screen_size[1]/100.0) mouse_x += 40 * slow_func(result[1] / 256.0) #int((result[1] + 180.0) * screen_size[0] / 80) mouse_y -= 40 * slow_func(result[0] / 256.0) #int((result[0] + 180.0) * screen_size[1] / 80.0) mouse_x = max(0, (0, mouse_x)[mouse_x < screen_size[0]]) mouse_y = max(0, min(mouse_y, screen_size[1])) except: pass # Sometimes arduino throws poorly formatted text print mouse_x/10 , mouse_y/10 mouse.move(mouse_x,mouse_y) elif line[0] in ['-', '+']: if line[0] in ['-', '+']: if line[0] == '-': press_spl_key(int(line[1:])) else: keyboard.type_string(line[1]) elif line[0] == "#": mouse.click(mouse_x, mouse_y, 1)
#https://github.com/SavinaRoja/PyUserInput #pip install pyuserinput from pymouse import PyMouse from pykeyboard import PyKeyboard import time import datetime m = PyMouse() k = PyKeyboard() agora=datetime.datetime.now() print(agora.minute) x_dim, y_dim = m.screen_size() m.click(1439, 899,1) time.sleep(0.1) m.click(712,885,1) time.sleep(0.5) m.click(700,707,1) time.sleep(0.1) k.type_string('fiz as conta') time.sleep(0.1) k.tap_key(k.enter_key) aux=0 while aux<15: #m.click(1300,710,1) k.type_string('tudo puta e viado') time.sleep(1) k.tap_key(k.enter_key) #m.click(1300,710,1) aux++
class Winauto(object): def __init__(self): self.k = PyKeyboard() #get pykeyboard self.software= u'网上股票交易系统5.0' self.hWndChildList=0 self.para_hld=win32gui.FindWindow(None,self.software) if self.IsWindow(): self.hWndChildList=self.demo_child_windows(self.para_hld) #get hld attr=self.show_window_attr(self.para_hld) win32api.SetCursorPos([attr['post'][0],attr['post'][1]]) #Mover to post(x,y) ''' 判定窗口是否激活 ''' def IsWindow(self): if self.para_hld>0: return 1; else: return 0; ''' 窗口置顶 ''' def topWindow(self): self.Key_event(VK_CODE['ctrl']) win32gui.SetForegroundWindow(self.para_hld) #show window ''' 输入键盘事件 ''' def Key_event(self,key): win32api.keybd_event(key,0,0,0) # win32api.keybd_event(key,0,win32con.KEYEVENTF_KEYUP,0) # ''' ldList: 'post:?§|left, top, right, bottom ''' def GetHld(self,post): for hld in self.hWndChildList: left, top, right, bottom =win32gui.GetWindowRect(hld) #get hld post left top right bottom #if (post[0]==left) & (post[1]==top) & (post[2]==right) & (post[3]==right): if (post[0]==left) & (post[1]==top): #get hld by (x,y) left top return hld return 0 ''' 通过字符找到窗口 ''' def GetHldWord(self,word): for hld in self.hWndChildList: title = win32gui.GetWindowText(hld) title=title.decode('gbk') if title==word: return hld return 0 ''' 获取窗口下的所有子窗口 ''' def demo_child_windows(self,parent): if not parent: return hWndChildList = [] win32gui.EnumChildWindows(parent, lambda hWnd, param: param.append(hWnd), hWndChildList) return hWndChildList #get all hld attr def show_window_attr(self,hWnd): if not hWnd: return title = win32gui.GetWindowText(hWnd) clsname = win32gui.GetClassName(hWnd) left, top, right, bottom =win32gui.GetWindowRect(hWnd) # attr = {'hWnd':hWnd,'title': title, 'clsname':clsname, 'post':[left,top,right,bottom]} return attr ''' 买入股票 ''' def Buy(self,buy_stock,buy_price,buy_nun): self.topWindow() self.Key_event(VK_CODE['F2']) self.Key_event(VK_CODE['F1']) self.backspace(5) time.sleep(0.5) self.k.type_string(buy_stock) self.Key_event(VK_CODE['tab']) time.sleep(1) if buy_price!='0': self.k.type_string(buy_nun) self.Key_event(VK_CODE['tab']) self.k.type_string(buy_nun) self.Key_event(VK_CODE['enter']) self.Key_event(VK_CODE['enter']) def Sell(self,buy_stock,buy_price,buy_nun): self.topWindow() self.Key_event(VK_CODE['F1']) self.Key_event(VK_CODE['F2']) self.backspace(5) time.sleep(0.5) self.k.type_string(buy_stock) self.Key_event(VK_CODE['tab']) time.sleep(1) if buy_price!='0': self.k.type_string(buy_price) self.Key_event(VK_CODE['tab']) self.k.type_string(buy_nun) self.Key_event(VK_CODE['enter']) self.Key_event(VK_CODE['enter']) def getAllAsset(self): self.topWindow() time.sleep(0.5)# win32api.keybd_event(VK_CODE['F4'],0,0,0) # distance = 54 #left_distance balance = u'资金余额' #通过距离判断 balance =self.getSset(balance,distance) othe_balance = u'可用金额' othe_balance =self.getSset(othe_balance,distance) market_value = u'股票市值' market_value =self.getSset(market_value,distance) propertys = u'总 资 产' propertys =self.getSset(propertys,distance) AssetList={'balance':balance['title'],'othe_balance':othe_balance['title'],'market_value':market_value['title'],'propertys':propertys['title']} return AssetList def backspace(self,n): for i in range(0,n): self.Key_event(VK_CODE['backspace']) def getSset(self,word,distance): hld = self.GetHldWord(word) attr = self.show_window_attr(hld) hld = self.GetHld((attr['post'][0]+distance,attr['post'][1])) attr = self.show_window_attr(hld) return attr #start app go go go def appStart(self,fileext,ver): win32api.ShellExecute(0, 'open',fileext,ver,'',1) time.sleep(5) self.k.type_string(self.password) win32api.keybd_event(VK_CODE['tab'],0,0,0) win32api.keybd_event(VK_CODE['enter'],0,0,0) ''' ctrl+c ''' def copyKey(self): win32api.keybd_event(VK_CODE['ctrl'],0,0,0) # Alt win32api.keybd_event(VK_CODE['c'],0,0,0) # O win32api.keybd_event(VK_CODE['c'],0,win32con.KEYEVENTF_KEYUP,0) # win32api.keybd_event(VK_CODE['ctrl'],0,win32con.KEYEVENTF_KEYUP,0) ''' 获取持仓 ''' def getAllStock(self): win32api.keybd_event(VK_CODE['F4'],0,0,0) attr = self.show_window_attr(self.para_hld) x = attr['post'][0]+300 y = attr['post'][1]+300 win32api.SetCursorPos([x,y]) #Mover to post(x,y) self.copyKey() copy_txt = self.getCopyText() copy_txt = copy_txt.rstrip().split("\n") c = [] cArray = {} cloun = '' for vv in copy_txt: cloun = vv.split(" ") for v in cloun: c.append(v) cArray[c[1]]=c c=[] return cArray ''' 实现复制功能 ''' def getCopyText(self): wc.OpenClipboard() copy_text = wc.GetClipboardData(win32con.CF_TEXT) wc.CloseClipboard() return copy_text ''' 关闭软件 ''' def closApp(self): self.para_hld=win32gui.FindWindow(None,self.software) #get hld by app word win32gui.PostMessage(self.para_hld, win32con.WM_CLOSE, 0, 0)
from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from pykeyboard import PyKeyboard driver = webdriver.Chrome() pykey = PyKeyboard() driver.get("chrome://settings/importData") # driver.get("https://www.imooc.com/user/newlogin") # email = driver.find_element_by_name("email") # email.send_keys("18018845546") # password = driver.find_element_by_name("password") # password.send_keys("z54821348123") # driver.find_element_by_class_name("moco-btn").click() # time.sleep(2) # driver.get("https://www.imooc.com/user/setprofile") # time.sleep(2) # driver.find_element_by_class_name("update-avator").click() # driver.find_elements_by_id("uypload").send_keys("输入图片地址") pykey.tap_key(pykey.shift_key) time.sleep(3) pykey.type_string("asddasd") pykey.type_key(pykey.enter_key) time.sleep(3) driver.close()
class Winauto(object): def __init__(self,fileext,ver,password): self.k = PyKeyboard() #get pykeyboard self.software= u'网上股票交易系统5.0' self.hWndChildList=0 fileext = fileext ver = ver self.password = password self.para_hld=win32gui.FindWindow(None,self.software) #get hld by app word if self.para_hld<=0: self.appStart(fileext,ver) time.sleep(5) if self.para_hld>0: win32gui.SetForegroundWindow(self.para_hld) #show window self.hWndChildList=self.demo_child_windows(self.para_hld) #get hld attr=self.show_window_attr(self.para_hld) #print attr win32api.SetCursorPos([attr['post'][0],attr['post'][1]]) #Mover to post(x,y) ''' ldList: 'post:?§|left, top, right, bottom ''' #获取头 def GetHld(self,post): for hld in self.hWndChildList: left, top, right, bottom =win32gui.GetWindowRect(hld) #get hld post left top right bottom #if (post[0]==left) & (post[1]==top) & (post[2]==right) & (post[3]==right): if (post[0]==left) & (post[1]==top): #get hld by (x,y) left top return hld return 0 def GetHldWord(self,word): for hld in self.hWndChildList: title = win32gui.GetWindowText(hld) title=title.decode('gbk') if title==word: return hld return 0 #get all demo chlid hld window def demo_child_windows(self,parent): if not parent: return hWndChildList = [] win32gui.EnumChildWindows(parent, lambda hWnd, param: param.append(hWnd), hWndChildList) return hWndChildList #get all hld attr def show_window_attr(self,hWnd): if not hWnd: return title = win32gui.GetWindowText(hWnd) clsname = win32gui.GetClassName(hWnd) left, top, right, bottom =win32gui.GetWindowRect(hWnd) # attr = {'hWnd':hWnd,'title': title, 'clsname':clsname, 'post':[left,top,right,bottom]} return attr #buy a stock parameter stock price nun def BuyS(self,buy_stock,buy_price,buy_nun): win32api.keybd_event(VK_CODE['F1'],0,0,0) #F2 self.k.type_string(buy_stock) win32api.keybd_event(VK_CODE['tab'],0,0,0) # time.sleep(2) if buy_price!='0': self.k.type_string(buy_nun) #k.type_string(buy_price) win32api.keybd_event(VK_CODE['tab'],0,0,0) # self.k.type_string(buy_nun) # win32api.keybd_event(VK_CODE['enter'],0,0,0) # #win32api.keybd_event(VK_CODE['enter'],0,0,0) # def SellS(self,buy_stock,buy_price,buy_nun): win32api.keybd_event(VK_CODE['F2'],0,0,0) # self.k.type_string(buy_stock) #import stock win32api.keybd_event(VK_CODE['tab'],0,0,0) #import tab time.sleep(2)# #sleep 2s if buy_price!='0': self.k.type_string(buy_price) win32api.keybd_event(VK_CODE['tab'],0,0,0) self.k.type_string(buy_nun) win32api.keybd_event(VK_CODE['enter'],0,0,0) time.sleep(2) win32api.keybd_event(VK_CODE['enter'],0,0,0) def getAllAsset(self): win32api.keybd_event(VK_CODE['F4'],0,0,0) # distance = 54 #left_distance balance = u'资金余额' balance =self.getSset(balance,distance) othe_balance = u'可用金额' othe_balance =self.getSset(othe_balance,distance) market_value = u'股票市值' market_value =self.getSset(market_value,distance) propertys = u'总 资 产' propertys =self.getSset(propertys,distance) AssetList={'balance':balance['title'],'othe_balance':othe_balance['title'],'market_value':market_value['title'],'propertys':propertys['title']} return AssetList def getSset(self,word,distance): hld = self.GetHldWord(word) attr = self.show_window_attr(hld) hld = self.GetHld((attr['post'][0]+distance,attr['post'][1])) attr = self.show_window_attr(hld) return attr #start app go go go def appStart(self,fileext,ver): win32api.ShellExecute(0, 'open',fileext,ver,'',1) time.sleep(5) self.k.type_string(self.password) win32api.keybd_event(VK_CODE['tab'],0,0,0) win32api.keybd_event(VK_CODE['enter'],0,0,0) def copyKey(self): win32api.keybd_event(VK_CODE['ctrl'],0,0,0) # Alt win32api.keybd_event(VK_CODE['c'],0,0,0) # O win32api.keybd_event(VK_CODE['c'],0,win32con.KEYEVENTF_KEYUP,0) # win32api.keybd_event(VK_CODE['ctrl'],0,win32con.KEYEVENTF_KEYUP,0) def getAllStock(self): win32api.keybd_event(VK_CODE['F4'],0,0,0) attr = self.show_window_attr(self.para_hld) x = attr['post'][0]+300 y = attr['post'][1]+300 win32api.SetCursorPos([x,y]) #Mover to post(x,y) self.copyKey() #copy crtl+f4 copy_txt = self.getCopyText() #get copy txt copy_txt = copy_txt.rstrip().split("\n") c = [] cArray = {} cloun = '' for vv in copy_txt: cloun = vv.split(" ") #split one for v in cloun: #get vlaue c.append(v) cArray[c[1]]=c #add list into dicitonary c=[] #clear all data return cArray #get copy text def getCopyText(self): wc.OpenClipboard() copy_text = wc.GetClipboardData(win32con.CF_TEXT) wc.CloseClipboard() return copy_text def closApp(self): writTxt('x.txt',str(self.para_hld)) self.para_hld=win32gui.FindWindow(None,self.software) #get hld by app word win32gui.PostMessage(self.para_hld, win32con.WM_CLOSE, 0, 0)
---------------------------------------------------------------------------------- import pymouse, pykeyboard, os, sys from pymouse import * from pykeyboard import PyKeyboard ## 键盘 + 鼠标操作 #完成点击屏幕中央并键入“Hello, World!”的功能:! m = PyMouse() k = PyKeyboard() xxxx, yyyy = m.screen_size() ## 获取屏幕的尺寸 分别是X 和 Y print(xxxx , yyyy) m.click(822,133) k.type_string('wwwwwwwwwwwwww!') #鼠标操作: ''' m.click(x, y, button, n) –鼠标点击 x, y –是坐标位置 buttong –1 表示左键,2 表示点击右键 n –点击次数,默认是1次,2表示双击 m.move(x, y) –鼠标移动到坐标(x, y) x_dim, y_dim = m.screen_size() –获得屏幕尺寸 ''' wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'EYE Typing Keypad', pos=(0, 0), size=wx.DisplaySize()) self.panel = wx.Panel(self) self.keyboard_control = PyKeyboard() #place to store what is being entered font1 = wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.BOLD) self.text = wx.TextCtrl(self.panel, 30, "", size=wx.DLG_SZE(self, 500, 40)) self.text.SetFont(font1) self.outer_box = wx.BoxSizer(wx.VERTICAL) self.outer_box.Add(self.text, border=5, flag=wx.ALL) #place to make the actual keyboard self.keyboard = wx.BoxSizer(wx.VERTICAL) self.keys = [chr(ord('a') + i) for i in range(10)] self.keys.append('space') # chr(ord('a')) + i self.keys = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'space', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm'] i = 1 self.hash = {} self.hash_label = {} self.key_buttons = [] for key in self.keys: b = wx.Button(self.panel, i, key, size=wx.DLG_SZE(self, 50, 50)) self.key_buttons.append(b) self.Bind(wx.EVT_BUTTON, self.connect_keys, b) self.hash_label[i] = key self.hash[i] = b if key == "space": self.hash_label[i] = 'spc' i += 1 i = 0 j = 0 self.keybox = [] font = wx.Font(20, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.BOLD) k = 1 self.flag = [False] * 28 for button in self.key_buttons: if i % 7 == 0: if self.keybox != []: self.keyboard.AddSpacer(40) self.keyboard.Add(self.keybox[j]) j += 1 self.keybox.append(wx.BoxSizer(wx.HORIZONTAL)) button.Bind(wx.EVT_ENTER_WINDOW, self.change_colour) button.Bind(wx.EVT_LEAVE_WINDOW, self.revert_colour) button.SetFont(font) self.keybox[j].Add(button) self.keybox[j].AddSpacer(40) i += 1 k += 1 self.keyboard.AddSpacer(40) self.keyboard.Add(self.keybox[j]) self.outer_box.Add(self.keyboard, border=5, flag=wx.ALL) self.panel.SetSizer(self.outer_box) def change_colour(self, event_change_colour): global GAZE_RADIUS i = event_change_colour.GetId() self.colour_changed = i button = self.hash[i] self.flag[i] = True button.SetBackgroundColour('red') if self.flag[i] is True: wx.CallLater(int((GAZE_RADIUS/3)*1000), self.colour_change, i, "yellow") def colour_change(self, i, colour): button = self.hash[i] if self.flag[i] is True: button.SetBackgroundColour(colour) if self.flag[i] is True: wx.CallLater(int((GAZE_RADIUS/3)*1000), self.connect_keys, i) def revert_colour(self, event_revert_colour): i = self.colour_changed self.flag[i] = False button = self.hash[self.colour_changed] button.SetBackgroundColour('lightgrey') def connect_keys(self, i): self.colour_changed = i label = self.hash_label[i] button = self.hash[i] if label == "spc": label = "__" if self.flag[i] is True: button.SetBackgroundColour("green") if self.flag[i] is True: self.keyboard_control.type_string(label) self.initial_text = self.text.GetValue() self.text.SetValue(self.initial_text + label) return def update_text(self, letter): initial_text = self.text.GetValue() self.text.SetValue(initial_text + letter)
class Bot(object): """Mouse and Keyboard robot class. Abbreviation table: - m: stands for mouse - k: stands for keyboard - dl: stands for delay - n: how many times you want to tap the key - i: usually for the ith function key, F1 ~ F12 Almost every method have an option keyword ``dl`` (dl stands for delay), there is ``dl`` seconds delay applied at begin. By default it is ``None``, means no delay applied. Keyboard Key Name Table (Case Insensitive):: # Main Keyboard Keys "ctrl": self.k.control_key, "l_ctrl": self.k.control_l_key, "r_ctrl": self.k.control_r_key, "alt": self.k.alt_key, "l_alt": self.k.alt_l_key, "r_alt": self.k.alt_r_key, "shift": self.k.shift_key, "l_shift": self.k.shift_l_key, "r_shift": self.k.shift_r_key, "tab": self.k.tab_key, "space": self.k.space_key, "enter": self.k.enter_key, "back": self.k.backspace_key, "backspace": self.k.backspace_key, # Side Keyboard Keys "home": self.k.home_key, "end": self.k.end_key, "page_up": self.k.page_up_key, "pageup": self.k.page_up_key, "page_down": self.k.page_down_key, "page_down": self.k.page_down_key, "insert": self.k.insert_key, "ins": self.k.insert_key, "delete": self.k.delete_key, "del": self.k.delete_key, "up": self.k.up_key, "down": self.k.down_key, "left": self.k.left_key, "right": self.k.right_key, # Function Keys "f1": F1 """ def __init__(self): self.m = PyMouse() self.k = PyKeyboard() self.dl = 0 self._key_mapper = { # Main Keyboard Keys "ctrl": self.k.control_key, "l_ctrl": self.k.control_l_key, "r_ctrl": self.k.control_r_key, "alt": self.k.alt_key, "l_alt": self.k.alt_l_key, "r_alt": self.k.alt_r_key, "shift": self.k.shift_key, "l_shift": self.k.shift_l_key, "r_shift": self.k.shift_r_key, "tab": self.k.tab_key, "space": self.k.space_key, "enter": self.k.enter_key, "back": self.k.backspace_key, "backspace": self.k.backspace_key, # Side Keyboard Keys "home": self.k.home_key, "end": self.k.end_key, "page_up": self.k.page_up_key, "pageup": self.k.page_up_key, "page_down": self.k.page_down_key, "page_down": self.k.page_down_key, "insert": self.k.insert_key, "ins": self.k.insert_key, "delete": self.k.delete_key, "del": self.k.delete_key, "up": self.k.up_key, "down": self.k.down_key, "left": self.k.left_key, "right": self.k.right_key, # f1 - f12 is the function key } for i in range(1, 1+12): self._key_mapper["f%s" % i] = self.k.function_keys[i] def _parse_key(self, name): name = str(name) if name in string.printable: return name elif name.lower() in self._key_mapper: return self._key_mapper[name.lower()] else: raise ValueError( "%r is not a valid key name, use one of %s." % (name, list(self._key_mapper))) def delay(self, dl=0): """Delay for ``dl`` seconds. """ if dl is None: time.sleep(self.dl) elif dl < 0: sys.stderr.write( "delay cannot less than zero, this takes no effects.\n") else: time.sleep(dl) #--- Meta --- def get_screen_size(self): """Return screen's width and height in pixel. **中文文档** 返回屏幕的像素尺寸。 """ width, height = self.m.screen_size() return width, height def get_position(self): """Return the current coordinate of mouse. **中文文档** 返回鼠标所处的位置坐标。 """ x_axis, y_axis = self.m.position() return x_axis, y_axis #--- Mouse Macro --- def left_click(self, x, y, n=1, pre_dl=None, post_dl=None): """Left click at ``(x, y)`` on screen for ``n`` times. at begin. **中文文档** 在屏幕的 ``(x, y)`` 坐标处左键单击 ``n`` 次。 """ self.delay(pre_dl) self.m.click(x, y, 1, n) self.delay(post_dl) def right_click(self, x, y, n=1, pre_dl=None, post_dl=None): """Right click at ``(x, y)`` on screen for ``n`` times. at begin. **中文文档** 在屏幕的 ``(x, y)`` 坐标处右键单击 ``n`` 次。 """ self.delay(pre_dl) self.m.click(x, y, 2, n) self.delay(post_dl) def middle_click(self, x, y, n=1, pre_dl=None, post_dl=None): """Middle click at ``(x, y)`` on screen for ``n`` times. at begin. **中文文档** 在屏幕的 ``(x, y)`` 坐标处中键单击 ``n`` 次。 """ self.delay(pre_dl) self.m.click(x, y, 3, n) self.delay(post_dl) def scroll_up(self, n, pre_dl=None, post_dl=None): """Scroll up ``n`` times. **中文文档** 鼠标滚轮向上滚动n次。 """ self.delay(pre_dl) self.m.scroll(vertical=n) self.delay(post_dl) def scroll_down(self, n, pre_dl=None, post_dl=None): """Scroll down ``n`` times. **中文文档** 鼠标滚轮向下滚动n次。 """ self.delay(pre_dl) self.m.scroll(vertical=-n) self.delay(post_dl) def scroll_right(self, n, pre_dl=None, post_dl=None): """Scroll right ``n`` times. **中文文档** 鼠标滚轮向右滚动n次(如果可能的话)。 """ self.delay(pre_dl) self.m.scroll(horizontal=n) self.delay(post_dl) def scroll_left(self, n, pre_dl=None, post_dl=None): """Scroll left ``n`` times. **中文文档** 鼠标滚轮向左滚动n次(如果可能的话)。 """ self.delay(pre_dl) self.m.scroll(horizontal=-n) self.delay(post_dl) def move_to(self, x, y, pre_dl=None, post_dl=None): """Move mouse to (x, y) **中文文档** 移动鼠标到 (x, y) 的坐标处。 """ self.delay(pre_dl) self.m.move(x, y) self.delay(post_dl) def drag_and_release(self, start_x, start_y, end_x, end_y, pre_dl=None, post_dl=None): """Drag something from (start_x, start_y) to (end_x, endy) **中文文档** 从start的坐标处鼠标左键单击拖曳到end的坐标处 start, end是tuple. 格式是(x, y) """ self.delay(pre_dl) self.m.press(start_x, start_y, 1) self.m.drag(end_x, end_y) self.m.release(end_x, end_y, 1) self.delay(post_dl) #--- Keyboard Single Key --- def tap_key(self, key_name, n=1, interval=0, pre_dl=None, post_dl=None): """Tap a key on keyboard for ``n`` times, with ``interval`` seconds of interval. Key is declared by it's name Example:: bot.tap_key("a") bot.tap_key(1) bot.tap_key("up") bot.tap_key("space") bot.tap_key("enter") bot.tap_key("tab") **中文文档** 以 ``interval`` 中定义的频率按下某个按键 ``n`` 次。接受按键名作为输入。 """ key = self._parse_key(key_name) self.delay(pre_dl) self.k.tap_key(key, n, interval) self.delay(post_dl) def enter(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press enter key n times. **中文文档** 按回车键/换行键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.enter_key, n, interval) self.delay(post_dl) def backspace(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press backspace key n times. **中文文档** 按退格键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.backspace_key, n, interval) self.delay(post_dl) def space(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press white space key n times. **中文文档** 按空格键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.space_key, n) self.delay(post_dl) def fn(self, i, n=1, interval=0, pre_dl=None, post_dl=None): """Press Fn key n times. **中文文档** 按 Fn 功能键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.function_keys[i], n, interval) self.delay(post_dl) def tab(self, n=1, interval=0, pre_dl=None, post_dl=None): """Tap ``tab`` key for ``n`` times, with ``interval`` seconds of interval. **中文文档** 以 ``interval`` 中定义的频率按下某个tab键 ``n`` 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.tab_key, n, interval) self.delay(post_dl) def up(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press up key n times. **中文文档** 按上方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.up_key, n, interval) self.delay(post_dl) def down(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press down key n times. **中文文档** 按下方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.down_key, n, interval) self.delay(post_dl) def left(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press left key n times **中文文档** 按左方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.left_key, n, interval) self.delay(post_dl) def right(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press right key n times. **中文文档** 按右方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.right_key, n, interval) self.delay(post_dl) def delete(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres delete key n times. **中文文档** 按 delete 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.delete_key, n, interval) self.delay(post_dl) def insert(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres insert key n times. **中文文档** 按 insert 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.insert_key, n, interval) self.delay(post_dl) def home(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres home key n times. **中文文档** 按 home 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.home_key, n, interval) self.delay(post_dl) def end(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press end key n times. **中文文档** 按 end 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.end_key, n, interval) self.delay(post_dl) def page_up(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres page_up key n times. **中文文档** 按 page_up 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.page_up_key, n, interval) self.delay(post_dl) def page_down(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres page_down key n times. **中文文档** 按 page_down 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.page_down, n, interval) self.delay(post_dl) #--- Keyboard Combination --- def press_and_tap(self, press_key, tap_key, n=1, interval=0, pre_dl=None, post_dl=None): """Press combination of two keys, like Ctrl + C, Alt + F4. The second key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "c") bot.press_and_tap("shift", "1") **中文文档** 按下两个键的组合键。 """ press_key = self._parse_key(press_key) tap_key = self._parse_key(tap_key) self.delay(pre_dl) self.k.press_key(press_key) self.k.tap_key(tap_key, n, interval) self.k.release_key(press_key) self.delay(post_dl) def press_two_and_tap(self, press_key1, press_key2, tap_key, n=1, interval=0, pre_dl=None, post_dl=None): """Press combination of three keys, like Ctrl + Shift + C, The tap key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "shift", "c") **中文文档** 按下三个键的组合键。 """ press_key1 = self._parse_key(press_key1) press_key2 = self._parse_key(press_key2) tap_key = self._parse_key(tap_key) self.delay(pre_dl) self.k.press_key(press_key1) self.k.press_key(press_key2) self.k.tap_key(tap_key, n, interval) self.k.release_key(press_key1) self.k.release_key(press_key2) self.delay(post_dl) def ctrl_c(self, pre_dl=None, post_dl=None): """Press Ctrl + C, usually for copy. **中文文档** 按下 Ctrl + C 组合键, 通常用于复制。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("c") self.k.release_key(self.k.control_key) self.delay(post_dl) def ctrl_v(self, pre_dl=None, post_dl=None): """Press Ctrl + V, usually for paste. **中文文档** 按下 Ctrl + V 组合键, 通常用于粘贴。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("v") self.k.release_key(self.k.control_key) self.delay(post_dl) def ctrl_x(self, pre_dl=None, post_dl=None): """Press Ctrl + X, usually for cut. **中文文档** 按下 Ctrl + X 组合键, 通常用于剪切。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("x") self.k.release_key(self.k.control_key) self.delay(post_dl) def ctrl_z(self, pre_dl=None, post_dl=None): """Press Ctrl + Z, usually for undo. **中文文档** 按下 Ctrl + Z 组合键, 通常用于撤销上一次动作。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("z") self.k.release_key(self.k.control_key) self.delay(post_dl) def ctrl_y(self, pre_dl=None, post_dl=None): """Press Ctrl + Y, usually for redo. **中文文档** 按下 Ctrl + Y 组合键, 通常用于重复上一次动作。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("y") self.k.release_key(self.k.control_key) self.delay(post_dl) def ctrl_a(self, pre_dl=None, post_dl=None): """Press Ctrl + A, usually for select all. **中文文档** 按下 Ctrl + A 组合键, 通常用于选择全部。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("a") self.k.release_key(self.k.control_key) self.delay(post_dl) def ctrl_f(self, pre_dl=None, post_dl=None): """Press Ctrl + F, usually for search. **中文文档** 按下 Ctrl + F 组合键, 通常用于搜索。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("f") self.k.release_key(self.k.control_key) self.delay(post_dl) def ctrl_fn(self, i, pre_dl=None, post_dl=None): """Press Ctrl + Fn1 ~ 12 once. **中文文档** 按下 Ctrl + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.control_key) self.delay(post_dl) def alt_fn(self, i, pre_dl=None, post_dl=None): """Press Alt + Fn1 ~ 12 once. **中文文档** 按下 Alt + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.alt_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.alt_key) self.delay(post_dl) def shift_fn(self, i, pre_dl=None, post_dl=None): """Press Shift + Fn1 ~ 12 once. **中文文档** 按下 Shift + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.shift_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.shift_key) self.delay(post_dl) def alt_tab(self, n=1, pre_dl=None, post_dl=None): """Press Alt + Tab once, usually for switching between windows. Tab can be tapped for n times, default once. **中文文档** 按下 Alt + Tab 组合键, 其中Tab键按 n 次, 通常用于切换窗口。 """ self.delay(pre_dl) self.k.press_key(self.k.alt_key) self.k.tap_key(self.k.tab_key, n=n, interval=0.1) self.k.release_key(self.k.alt_key) self.delay(post_dl) #--- Other --- def type_string(self, text, interval=0, pre_dl=None, post_dl=None): """Enter strings. **中文文档** 从键盘输入字符串, interval是字符间输入时间间隔, 单位是秒。 """ self.delay(pre_dl) self.k.type_string(text, interval) self.delay(post_dl) def copy_text_to_clipboard(self, text): """Copy text to clipboard. **中文文档** 拷贝字符串到剪贴板。 """ pyperclip.copy(text)
def runExp(self): k = PyKeyboard() # Resetting both gammas k.type_string('s') k.type_string('d') for i in xrange(self.SWEEP_STEP_SIZE): if (self.running): # Resetting gammaSta k.type_string('s') for j in xrange(self.SWEEP_STEP_SIZE): if (self.running): self.currTrial = i*self.SWEEP_STEP_SIZE + j + 1 # Reset and cool-down for nagging in xrange(5): k.type_string('0') sleep(0.3) self.strong_damper.damping = 0.0 # Perturbation k.type_string('j') sleep(3) # Increasing gammaSta k.type_string('w') sleep(1.0) # Add a strong damper to stop any motion self.strong_damper.damping = 100.0 # attmept to remove the residual torque. bitVal = convertType(0.0, fromType = 'f', toType = 'I') xem_spindle_bic.SendPara(bitVal = bitVal, trigEvent = 1) # Ia gain xem_spindle_tri.SendPara(bitVal = bitVal, trigEvent = 1) xem_spindle_bic.SendPara(bitVal = bitVal, trigEvent = 10) # II gain xem_spindle_tri.SendPara(bitVal = bitVal, trigEvent = 10) sleep(2.0) bitVal = convertType(1.2, fromType = 'f', toType = 'I') xem_spindle_bic.SendPara(bitVal = bitVal, trigEvent = 1) # Ia gain xem_spindle_tri.SendPara(bitVal = bitVal, trigEvent = 1) bitVal_II = convertType(2.0, fromType = 'f', toType = 'I') xem_spindle_bic.SendPara(bitVal = bitVal_II, trigEvent = 10) # II gain xem_spindle_tri.SendPara(bitVal = bitVal_II, trigEvent = 10) # Increasing gammaDyn k.type_string('e') k.tap_key(k.escape_key)
from pymouse import PyMouse from pykeyboard import PyKeyboard m = PyMouse() k = PyKeyboard() # pressing a key k.press_key('H') # which you then follow with a release of the key k.release_key('H') # or you can 'tap' a key which does both k.tap_key('e') # note that that tap_key does support a way of repeating keystrokes with a interval time between each k.tap_key('l', n=2, interval=1) # and you can send a string if needed too k.type_string('o World!') # move the mouse to int x and int y (these are absolute positions) m.move(200, 200) # click works about the same, except for int button possible values are 1: left, 2: right, 3: middle m.click(600, 900, 1) # get the screen size m.screen_size() # (1024, 768) # get the mouse positionHello World!Hello World! m.position() # (500, 300)lo World!
class TestSaisieCarhab(object): '''Speed of mouse cursor move, 0.01 =< float =< 1 (0.2 for realistic move)''' MOVE_SPEED = 0.2 # Do full test or a part only TESTS_TO_CHECK = '' ''' available values : 'up_to_fusion', 'up_to_undo_fusion', 'up_to_quit_edit_fusion' 'up_to_fusion_import_feat', 'up_to_undo_import_feat', 'up_to_quit_edit_import_feat', every thing else for full test''' def __init__(self): '''Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface ''' self.mouse = PyMouse() self.keyboard = PyKeyboard() def screenShot(self, imgName = 'debugScreenshot'): '''Shoot screen. :param imgName: Text value of the action to click on. :type imgName: QString :default imgName: 'debugScreenshot.png' ''' iface.mapCanvas().saveAsImage(imgName) def addTestVectorLayer(self, path='test/data/segment.shp'): '''Add a vector layer to the map. :param path: Shapefile name to add. :type path: QString :default path: 'test/data/segement.shp' :return: Vector layer which has been added to map canvas :rtype: QgsVectorLayer ''' # Set legend name from path layerName = path.split('/')[-1:][0].split('.shp')[0] layer = QgsVectorLayer(path, layerName, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(layer) # Useful to let QGIS processing QgsApplication.processEvents() return iface.mapCanvas().layers()[0] def findButtonByAction(self, action): '''Find button corresponding to the given action. :param buttonActionName: Text value of the action. :type buttonActionName: QString :return: Widget if found, None else. :rtype: QWidget or None ''' for widget in action.associatedWidgets(): if type(widget) == QtGui.QToolButton: return widget return None def findButtonByActionName(self, buttonActionName): '''Find button corresponding to the given action. :param buttonActionName: Text value of the action. :type buttonActionName: QString :return: Widget if found, None else. :rtype: QWidget or None ''' for tbar in iface.mainWindow().findChildren(QtGui.QToolBar): for action in tbar.actions(): if action.text() == buttonActionName: for widget in action.associatedWidgets(): if type(widget) == QtGui.QToolButton: return widget return None def mapToScreenPoint(self, mapCoordPoint): '''Convert point on the map canvas from map to screen coordinates. :param mapCoordPoint: Point in map coordinates. :type mapCoordPoint: QgsPoint :return: Point in screen coordinates :rtype: QPoint ''' # Get point in px into map canvas referential sourceScreen = iface.mapCanvas().getCoordinateTransform().transform(mapCoordPoint) sourceRelScreen = sourceScreen.toQPointF().toPoint() # find top left canvas pos canvas = iface.mapCanvas() canvasPos = canvas.mapToGlobal(QtCore.QPoint( canvas.rect().x(), canvas.rect().y())) # Get point in px into screen referential sourceAbsScreen = QtCore.QPoint(sourceRelScreen.x() + canvasPos.x(), sourceRelScreen.y() + canvasPos.y()) return sourceAbsScreen def moveTo(self, dest, rate=MOVE_SPEED): '''Move smoothly mouse cursor to a destination point. :param dest: Mouse cursor destination point. :type dest: QPoint :param rate: Speed of mouse movement : 1 = 100px/sec. :type rate: float >= 0.01 :default rate: TestSaisieCarhab constant MOVE_SPEED ''' source = self.mouse.position() npoints = int(np.sqrt((dest.x()-source[0])**2 + (dest.y()-source[1])**2 ) / (rate*100)) for i in range(npoints): x = int(source[0] + ((dest.x()-source[0])/npoints)*i) y = int(source[1] + ((dest.y()-source[1])/npoints)*i) self.mouse.move(x,y) time.sleep(0.01) # Useful to let QGIS processing QgsApplication.processEvents() self.mouse.move(dest.x(), dest.y()) # Useful to let QGIS processing QgsApplication.processEvents() def clickOnMapPoint(self, point): '''Click on the map at the given point (map coordinates). :param point: Widget to click on. :type point: QgsPoint ''' sceenCoordPoint = self.mapToScreenPoint(point) self.moveTo(sceenCoordPoint) self.mouse.click(sceenCoordPoint.x(), sceenCoordPoint.y(), 1) # Useful to let QGIS processing QgsApplication.processEvents() def clickOnWidget(self, widget): '''Click on the given widget. :param widget: Widget to click on. :type widget: QWidget ''' widgetX = widget.rect().center().x() widgetY = widget.rect().center().y() widgetPos = widget.mapToGlobal(QtCore.QPoint(widgetX, widgetY)) self.moveTo(widgetPos) self.mouse.click(widgetPos.x(), widgetPos.y(), 1) # Useful to let QGIS processing QgsApplication.processEvents() def clickOnWidgetByActionName(self, actionName): '''Click on action by its text value. :param actionName: Text value of the action to click on. :type actionName: QString ''' button = self.findButtonByActionName(actionName) self.clickOnWidget(button) def dragAndDropScreen(self, source, dest): '''Press mouse at source point, move to destination point and release. :param source: Drag start position. :type source: QPoint :param dest: Mouse cursor destination point. :type dest: QPoint ''' self.moveTo(source) self.mouse.press(source.x(), source.y(), 1) # Useful to let QGIS processing QgsApplication.processEvents() self.moveTo(dest) self.mouse.release(dest.x(), dest.y(), 1) # Useful to let QGIS processing QgsApplication.processEvents() def dragAndDropMap(self, source, dest): '''DragAndDropScreen in map coordinates. :param source: Drag start position. :type source: QPoint in map coordinates :param dest: Mouse cursor destination point. :type dest: QPoint in map coordinates ''' screenCoordSource = self.mapToScreenPoint(source) screenCoordDest = self.mapToScreenPoint(dest) self.dragAndDropScreen(screenCoordSource, screenCoordDest) def ctrlZ(self): '''Simulates 'CTRL + z' type on the keyboard.''' self.keyboard.press_key(self.keyboard.control_l_key) time.sleep(0.25) self.keyboard.tap_key(self.keyboard.type_string('z'), 0, 0) time.sleep(0.25) self.keyboard.release_key(self.keyboard.control_l_key) # Useful to let QGIS processing QgsApplication.processEvents() def quitLayerEditMode(self, layer): '''Rollback changes on the layer and quit edit mode. :param layer: Layer in edit mode. :type layer: QVectorLayer ''' layer.rollBack() # Useful to let QGIS processing QgsApplication.processEvents() # Refresh layer layout layer.triggerRepaint() def featuresCount(self, layer): '''Count the features of a vector layer. :param layer: Vector layer. :type layer: QgsVectorLayer :return: Layer features count. :rtype: int ''' count = 0 for feature in layer.getFeatures(): count += 1 return count def printTest(self, expected, result, testName, valueToTestName): '''Print test result. :param expected: expected value to test. :type expected: unknown :param result: result value to test. :type result: unknown :param testName: Name of test (into header printed). :type testName: QString :param valueToTestName: Tested variable name (printed if test fails). :type valueToTestName: QString :return: True if test pass, False else. :rtype: Bool ''' test = False msg = testName+''' : Fails '''+valueToTestName+''' expected : '''+str(expected)+''' '''+valueToTestName+''' : '''+str(result) if expected == result: test = True msg = testName+''' : OK''' print msg return test def testFusion(self): '''Simulate user moves and check results.''' # Open python console iface.actionShowPythonDialog().trigger() # Get map tool action that is activated previousActivatedMapToolActionName = iface.mapCanvas().mapTool().action().text() # Simulate click on edit mode button # self.clickOnWidgetByActionName(iface.actionToggleEditing().text()) # Simulate click on plugin fusion button JobManager().create_carhab_lyr('test') # # Simulate 2nd click and check if fusion button stay checked # self.clickOnWidgetByActionName('Fusion') # # Fusion button must be enabled # if not self.printTest(True, self.findButtonByActionName('Fusion').isChecked(), 'Fusion button stays checked', 'Fusion button status'): # return # # # Press (left click) and move mouse on the map canvas to carry out the fusion # self.dragAndDropMap(QgsPoint(783902,6528458), QgsPoint(785223,6528279)) # # # Features must have been merged (test with features count) # if not self.printTest(35, self.featuresCount(layer), 'Fusion', 'Features count'): # return # # # End of test ? # if self.TESTS_TO_CHECK == 'up_to_fusion': # return # # # Test undo action # self.ctrlZ() # if not self.printTest(37, self.featuresCount(layer), 'Undo fusion(Ctrl + z)', 'Features count'): # return # # # End of test ? # if self.TESTS_TO_CHECK == 'up_to_undo_fusion': # return # # # Quit edit mode # self.clickOnWidgetByActionName(iface.actionToggleEditing().text()) # # # Fusion button must be enabled # if not self.printTest(False, self.findButtonByActionName('Fusion').isEnabled(), 'Disable fusion button', 'Fusion button status'): # return # # # Fusion button must be enabled # if not self.printTest(False, self.findButtonByActionName('Fusion').isChecked(), 'Uncheck fusion button', 'Fusion button status'): # return # # # Previous map tool button must be re-checked # if not self.printTest(True, self.findButtonByActionName(previousActivatedMapToolActionName).isChecked(), 'Check previous map tool button ('+previousActivatedMapToolActionName+')', 'Previous map tool button ('+previousActivatedMapToolActionName+') status'): # return # # # End of test ? # if self.TESTS_TO_CHECK == 'up_to_quit_edit_fusion': # return # # # Clear layers # QgsMapLayerRegistry.instance().removeAllMapLayers() # iface.mapCanvas().refresh() # # Close python console # iface.actionShowPythonDialog().trigger() # # self.testImportFeature() def testImportFeature(self): '''Simulate user moves and check results.''' # Open python console iface.actionShowPythonDialog().trigger() # Get map tool action that is activated previousActivatedMapToolActionName = iface.mapCanvas().mapTool().action().text() #Add test layers to map registry layerDest = self.addTestVectorLayer() layerSource = self.addTestVectorLayer('test/data/segment2.shp') iface.setActiveLayer(layerDest) # Simulate click on edit mode button self.clickOnWidgetByActionName(iface.actionToggleEditing().text()) # Simulate click on plugin fusion button self.clickOnWidgetByActionName('Import Feature') # Move and click on the feature to import self.clickOnMapPoint(QgsPoint(785519,6528705)) # Feature must have been added if not self.printTest(38, self.featuresCount(layerDest), 'Import feature', 'Features count'): return # End of test ? if self.TESTS_TO_CHECK == 'up_to_import_feature': return # Test undo action self.ctrlZ() if not self.printTest(37, self.featuresCount(layerDest), 'Undo Import feature(Ctrl + z)', 'Features count'): return # End of test ? if self.TESTS_TO_CHECK == 'up_to_undo_import_feat': return # Quit edit mode self.clickOnWidgetByActionName(iface.actionToggleEditing().text()) # Fusion button must be enabled if not self.printTest(False, self.findButtonByActionName('Import Feature').isEnabled(), 'Disable fusion button', 'Fusion button status'): return # Previous map tool button must be re-checked if not self.printTest(True, self.findButtonByActionName(previousActivatedMapToolActionName).isChecked(), 'Check previous map tool button ('+previousActivatedMapToolActionName+')', 'Previous map tool button ('+previousActivatedMapToolActionName+') status'): return # End of test ? if self.TESTS_TO_CHECK == 'up_to_quit_edit_import_feat': return # Clear layers #QgsMapLayerRegistry.instance().removeAllMapLayers() iface.mapCanvas().refresh()
key = fichier.read() fichier.close() fichier = open("iv", "r") iv = fichier.read() fichier.close() fichier = open("cipher", "r") len = int(fichier.readline()) cipher = fichier.readline() fichier.close() aes = AES.new(key, AES.MODE_CBC, iv) mp = aes.decrypt(cipher)[-len:] k = PyKeyboard() m = PyMouse() time.sleep(1) k.type_string(mp) k.tap_key('return') time.sleep(1) m.move(500, 500) time.sleep(1) m.move(0, 0) m.move(0, 0)
class BookingBot(object): def __init__(self, user_name, user_pwd): self._user_name = user_name self._user_pwd = user_pwd self.keyboard = PyKeyboard() self.mouse = PyMouse() def start_wechat(self): # itchat.send('start booking bot, input:help, get info', 'filehelper') self._book_day = time.localtime(time.time()).tm_mday self._book_hour = time.localtime(time.time()).tm_hour self._sport_name = 'basketball' self._sport_day = 7 self._sport_hour = [21] @itchat.msg_register([itchat.content.TEXT]) def chat_trigger(msg): if msg['Text'] == 'help': itchat.send(u'input your user_name', 'filehelper') itchat.send(u'example:u=txf', 'filehelper') itchat.send(u'input your user_pwd', 'filehelper') itchat.send(u'example:p=123', 'filehelper') itchat.send(u'input booking day', 'filehelper') itchat.send(u'example:bd=15', 'filehelper') itchat.send(u'input booking hour', 'filehelper') itchat.send(u'example:bh=8', 'filehelper') itchat.send(u'input sport name', 'filehelper') itchat.send(u'example:sn=basketball', 'filehelper') itchat.send(u'input sport day', 'filehelper') itchat.send(u'example:sd=7', 'filehelper') itchat.send(u'input sport hour', 'filehelper') itchat.send(u'example:sh=21 19 15', 'filehelper') itchat.send(u'start booking, input:start', 'filehelper') elif 'u=' in msg['Text']: self._user_name = msg['Text'][2:] itchat.send(u'record your name', 'filehelper') elif 'p=' in msg['Text']: self._user_pwd = msg['Text'][2:] itchat.send(u'record your password', 'filehelper') elif 'bd=' in msg['Text']: self._book_day = int(msg['Text'][3:]) itchat.send(u'record booking day: {}'.format(self._book_day), 'filehelper') elif 'bh=' in msg['Text']: self._book_hour = int(msg['Text'][3:]) itchat.send(u'record booking hour: {}'.format(self._book_hour), 'filehelper') elif 'sn=' in msg['Text']: self._sport_name = msg['Text'][3:] itchat.send(u'record sport name: {}'.format(self._sport_name), 'filehelper') elif 'sd=' in msg['Text']: self._sport_day = int(msg['Text'][3:]) itchat.send(u'record sport day: {}'.format(self._sport_day), 'filehelper') elif 'sh=' in msg['Text']: in_msg = msg['Text'][3:] itchat.send(u'record sport hours: {}'.format(in_msg), 'filehelper') in_msg = in_msg.split(' ') hour_list = [int(hour) for hour in in_msg] self._sport_hour = hour_list elif msg['Text'] == u'start': assert self._user_name is not None assert self._user_pwd is not None assert self._book_day is not None assert self._book_hour is not None assert self._sport_name is not None assert self._sport_day is not None assert self._sport_hour is not None while True: daytime = time.localtime(time.time()).tm_mday hourtime = time.localtime(time.time()).tm_hour mintime = time.localtime(time.time()).tm_min print('Now time: {} day {} hour {} min'.format( daytime, hourtime, mintime)) if daytime == self._book_day and hourtime == self._book_hour: if self.book(self._sport_hour, self._sport_name, self._sport_day) == 1: itchat.send(u'booking successful', 'filehelper') break else: itchat.send(u'no available time', 'filehelper') self._log_failed() itchat.send_image('failed.jpg', 'filehelper') break else: time.sleep(60) itchat.auto_login(hotReload=True) # itchat.auto_login() itchat.run() def _login(self): self.browser = webdriver.Firefox() self.browser.set_window_size(1920, 1080) self.browser.set_window_position(0, 0) self.browser.get('http://www.cityu.edu.hk/sfbi-std/fbi_fp.htm') time.sleep(2) self.keyboard.type_string(self._user_name) self.keyboard.tap_key(self.keyboard.tab_key) self.keyboard.type_string(self._user_pwd) self.keyboard.tap_key(self.keyboard.enter_key) time.sleep(2) def book(self, sport_hours, sport_name='basketball', sport_day=7): self._login() self._choose_day(sport_day) self._choose_sport(sport_name) time.sleep(3) labels = self._get_access_lable() for hour in sport_hours: if labels[hour - 8]: self._choose_hour(hour) break else: print('Sorry, no available time') self.browser.close() time.sleep(30) return 0 self._confirm_booking() self.browser.close() return 1 def _choose_day(self, day): assert day < 8 assert day >= 0 curr_wday = time.localtime(time.time()).tm_wday booking_day = curr_wday + day + 1 if booking_day > 13: booking_day -= 13 if booking_day > 6: pos = self._get_day_pos(1, (booking_day - 7)) else: pos = self._get_day_pos(0, booking_day) self._click(pos[0], pos[1]) time.sleep(1) def _choose_sport(self, sport): # you need to add the sport you want if sport == 'basketball': self._click(1075, 460) time.sleep(1) def _choose_hour(self, hour): hour = hour - 8 pos = self._get_hour_pos(hour) self._click(pos[0], pos[1]) time.sleep(1) def _confirm_booking(self): self._click(377, 600) self.keyboard.type_string(self._user_pwd) self.keyboard.tap_key(self.keyboard.enter_key) def _click(self, x, y): self.mouse.move(x, y) time.sleep(1) self.mouse.click(x, y, 1, 3) def _get_day_pos(self, row, column): return [300 + column * 27, 470 + row * 30] def _get_hour_pos(self, row): return [368, 316 + row * 23] def _get_access_lable(self): img = ImageGrab.grab() b, g, r = img.split() img = Image.merge("RGB", (r, g, b)) img = np.array(img, dtype=np.uint8) roi = img[315:624, 350:379] flags = [] for i in range(14): sub_roi = roi[i * 22:(i + 1) * 22, :] blue = sub_roi[sub_roi.shape[0] // 2, sub_roi.shape[1] // 2, 0] if blue > 120: flag = True else: flag = False flags.append(flag) return flags def _log_failed(self): img = ImageGrab.grab() img = np.array(img, dtype=np.uint8) screen_roi = img[:1080, :1920] img = Image.fromarray(screen_roi) img.save('failed.jpg')
class Bot(): def __init__(self): self.mouse = PyMouse() self.keyboard = PyKeyboard() def Delay(self, n): time.sleep(n) """ ====== Mouse Macro ====== """ def Left_click(self, x, y, n = 1, dl = 0): """在屏幕某点左键点击若干次 """ self.Delay(dl) self.mouse.click(x, y, 1, n) def Right_click(self, x, y, n = 1, dl = 0): """在屏幕某点右键点击若干次 """ self.Delay(dl) self.mouse.click(x, y, 2, n) def Double_click(self, x, y, dl = 0): """在屏幕的某点双击 """ self.Delay(dl) self.mouse.click(x, y, 1, n = 2) def Scroll_up(self, n, dl = 0): """鼠标滚轮向上n次 """ self.Delay(dl) self.mouse.scroll(vertical = n) def Scroll_down(self, n, dl = 0): """鼠标滚轮向下n次 """ self.Delay(dl) self.mouse.scroll(vertical = -n) def Move_to(self, x, y, dl = 0): """鼠标移动到x, y的坐标处 """ self.Delay(dl) self.mouse.move(x, y) def Drag_and_release(self, start, end, dl = 0): """从start的坐标处鼠标左键单击拖曳到end的坐标处 start, end是tuple. 格式是(x, y) """ self.Delay(dl) self.mouse.press(start[0], start[1], 1) self.mouse.drag(end[0], end[1]) self.Delay(0.1) self.mouse.release(end[0], end[1], 1) def Screen_size(self): width, height = self.mouse.screen_size() return width, height def WhereXY(self): x_axis, y_axis = self.mouse.position() return x_axis, y_axis """ ====== Keyboard Macro ====== """ """COMBINATION组合键""" """Ctrl系列""" def Ctrl_c(self, dl = 0): """Ctrl + c 复制 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key("c") self.keyboard.release_key(self.keyboard.control_key) def Ctrl_x(self, dl = 0): """Ctrl + x 剪切 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key("x") self.keyboard.release_key(self.keyboard.control_key) def Ctrl_v(self, dl = 0): """Ctrl + v 粘贴 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key("v") self.keyboard.release_key(self.keyboard.control_key) def Ctrl_z(self, dl = 0): """Ctrl + z 撤销上一次操作 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key("z") self.keyboard.release_key(self.keyboard.control_key) def Ctrl_y(self, dl = 0): """Ctrl + y 重复上一次操作 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key("y") self.keyboard.release_key(self.keyboard.control_key) def Ctrl_a(self, dl = 0): """Ctrl + a 全选 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key("a") self.keyboard.release_key(self.keyboard.control_key) def Ctrl_Fn(self, n, dl = 0): """Ctrl + Fn1~12 组合键 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key(self.keyboard.function_keys[n]) self.keyboard.release_key(self.keyboard.control_key) """Alt系列""" def Alt_Tab(self, dl = 0): """Alt + Tab 组合键 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.alt_key) self.keyboard.tap_key(self.keyboard.tab_key) self.keyboard.release_key(self.keyboard.alt_key) def Alt_Fn(self, n, dl = 0): """Alt + Fn1~12 组合键 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.alt_key) self.keyboard.tap_key(self.keyboard.function_keys[n]) self.keyboard.release_key(self.keyboard.alt_key) """SINGLE KEY单个键盘键""" def Up(self, n = 1, dl = 0): """上方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.up_key, n) def Down(self, n = 1, dl = 0): """下方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.down_key, n) def Left(self, n = 1, dl = 0): """左方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.left_key, n) def Right(self, n = 1, dl = 0): """右方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.right_key, n) def Enter(self, n = 1, dl = 0): """回车键/换行键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.enter_key, n) def Delete(self, n = 1, dl = 0): """删除键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.delete_key, n) def Back(self, n = 1, dl = 0): """退格键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.backspace_key, n) def Space(self, n = 1, dl = 0): """空格键n次 """ self.Delay(dl) self.keyboard.tap_key(" ", n) def Fn(self, n, dl = 0): """功能键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.function_keys[n]) def Char(self, char, n = 1, dl = 0): """输入任意单字符n次,只要能在键盘上打出来的字符都可以 """ if len(char) == 1: self.Delay(dl) self.keyboard.tap_key(char) else: raise Exception("""method "Char()" can only take one character.""") def Type_string(self, text, interval = 0, dl = 0): """键盘输入字符串,interval是字符间输入时间间隔,单位"秒" """ self.Delay(dl) self.keyboard.type_string(text, interval)
# 按F5 功能键 # keyboard.press_key(keyboard.function_keys[5]) # keyboard.release_key(keyboard.function_keys[5]) # 按数字 keyboard.press_key(keyboard.numpad_keys[9]) keyboard.release_key(keyboard.numpad_keys[9]) # 回车、空格、shift # keyboard.press_key(keyboard.enter_key) # keyboard.press_key(keyboard.space) # keyboard.press_key(keyboard.shift_key) # 键盘输入 keyboard.type_string("123") # 组合键Ctrl+A keyboard.press_key(keyboard.control_key) keyboard.press_key("a") keyboard.release_key(keyboard.control_key) keyboard.release_key("a")
k.press_key(k.control_key) k.tap_key('t') k.release_key(k.control_key) # Getting an element where Keys can be passed # Opening a NEW TAB browser.get('http://hck.re/qcKgO4') time.sleep(11) m.click(598L,798L,1,1) mail='monkeydluffy'+str(i)+'@superrito.com' k.type_string(mail) k.tap_key(k.return_key) time.sleep(15) m.click(444L,378L,1,1) m.click(654L,514L,1,1) m.click(723L,641L,1,1)
# coding=utf-8 from pykeyboard import PyKeyboard from pymouse import PyMouse from time import sleep m = PyMouse() s = m.screen_size() print(s) # (1093, 614) 1366 * 768 m.move(s[0] // 2, s[1] // 2) sleep(1) kb = PyKeyboard() kb.type_string('hello')
import time m = PyMouse() k = PyKeyboard() with open('names.txt') as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line names = [x.strip().lower() for x in content] for name in names: email = name + '@gmail.com' webbrowser.open_new("http://insider.finimize.com/?kid=FKBTC") time.sleep(5) k.tap_key(k.tab_key) k.tap_key(k.tab_key) k.type_string(email) k.tap_key(k.tab_key) k.type_string(name) k.tap_key(k.tab_key) k.type_string("smith") k.tap_key(k.enter_key) time.sleep(5) k.press_key(k.control_key) k.tap_key('w') k.release_key(k.control_key)
m = PyMouse() k = PyKeyboard() sleep(2) GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Doorbell Button GPIO.setup(9, GPIO.OUT) # Indicator LED while True: if (GPIO.input(22) == 1): print("Doorbell Pressed") GPIO.output(9, True) m.click(276, 372) # Click in the Duo text box sleep(0.5) k.tap_key('Delete', n=6, interval=0.05) # Delete existing characters k.type_string("Father") # Type name of Duo contact sleep(0.2) k.tap_key('Return') # Hit Return to select contact sleep(1.5) m.click(683, 445) # Click on Video Call button GPIO.output(9, False) for count in range(0, 30): GPIO.output(9, True) sleep(0.8) GPIO.output(9, False) sleep(0.8) else: sleep(0.05)
print " .o0@@@0o. .o0@@@0o." time.sleep(0.02) print " .0@@@@0o.. ..o0@@@@0." time.sleep(0.02) print " .o00@@@@0oo.. ..oo0@@@@00o." time.sleep(0.02) print " .o00@@@@@00oooo.........oooo000@@@@@00o." time.sleep(0.02) print " .oo000@@@@@@@@@@@@@@@@@@@@000oo." time.sleep(0.02) print " ...oooooooooooooo..." for i in range(rows): time.sleep(0.03) print "" k.type_string('htop -d 50') time.sleep(0.1) k.tap_key('Return') time.sleep(0.01) k.press_keys(['Alt_L', '\\']) time.sleep(0.1) k.press_keys(['Alt_L', 'h']) time.sleep(0.01) k.press_keys(['Alt_L', '-']) time.sleep(0.1) k.type_string('mutt') time.sleep(0.01) k.tap_key('Return') time.sleep(0.01) k.press_key('Alt_L') k.tap_key(character='Up', n=8)
#!/usr/bin/env python from pymouse import PyMouse from pykeyboard import PyKeyboard import time import sys if len(sys.argv) < 2: print "Usage: ./brute.py DELAY" quit() WAIT_TIME = float(sys.argv[1]) m = PyMouse() k = PyKeyboard() x_dim, y_dim = m.screen_size() time.sleep(4) for i in range(130, 2000): for ii in range(0, 10): k.tap_key(k.backspace_key) k.type_string(str(i)) k.tap_key(k.enter_key) time.sleep(WAIT_TIME)
# self.click(self.loc_add_trunck) # self.sendKeys(self.loc_title, title) # js = 'document.getElementsByClassName("ke-edit-iframe")[0].contentWindow.document.body.innerHTML="Hello World"' # self.driver.execute_script(js) self.click(self.loc_upload) self.click(self.loc_view) # def is_save_success(self, text): # return self.is_text_exist(self.loc_name, text) if __name__ == "__main__": driver = webdriver.Firefox() LogInPage(driver).log_in_page("admin", "123456") a = AddBug(driver) # timestr = time.strftime("%Y_%m_%d_%H_%M_%S") # title = "test BUG"+timestr a.add_bug() time.sleep(5) k = PyKeyboard() k.type_string('c:\hello.txt') time.sleep(2) k.tap_key(k.enter_key) k.tap_key(k.enter_key) time.sleep(2) su = driver.find_element_by_xpath( "html/body/div[3]/div[1]/div[3]/span[1]/input") su.click()
# Thresholds - these are wiped each time the scale is back to ZERO # Archives each output, to not repeat itself indefinitely previous = [0] # Used as threshold to wait for scale to balance before outputting to the user (100 executions by default) counts = {}; while True: try: data = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize) weight = float(data[4])/100 weightStr = str(weight) if (weight == 0.0): previous = [] counts = {} continue if (weightStr not in counts): counts[weightStr] = 0; else: counts[weightStr] = counts[weightStr] + 1; if (counts[weightStr] > BALANCE_THRESHOLD and weight not in previous): k.type_string(weightStr) previous.append(weight) except usb.core.USBError as e: data = None if e.args == ('Operation timed out',): continue
# -*- coding: utf-8 -*- """ Created on Mon Apr 13 19:35:11 2020 @author: 11260 """ ### open the software terminal PASSWORD = '******' import os cmd1 = 'cd /D D:\wind\V2' cmd2 = '.\launcher.exe' os.system(cmd1 + '&' + cmd2) from pymouse import * from pykeyboard import PyKeyboard k = PyKeyboard() k.type_string(PASSWORD) ######选择服务器 和 用户代码一定要有记录 k.press_key(k.enter_key) #which you then follow with a release of the key k.release_key(k.enter_key) m = PyMouse() m.click(1195, 531)
driver.find_element_by_id("input1").send_keys(data[0]) driver.find_element_by_id("input2").send_keys(data[1]) driver.find_element_by_id("signin").click() driver.implicitly_wait(30) driver.find_element_by_id("user_nav_blog_link").click() driver.find_element_by_link_text("新随笔").click() time.sleep(3) # 点开编辑器图片 driver.find_element_by_css_selector("img.mceIcon").click() time.sleep(3) # 定位所有iframe,取第二个 iframe = driver.find_elements_by_tag_name('iframe')[1] # 切换到iframe上 driver.switch_to.frame(iframe) # 文件路径 time.sleep(2) driver.find_element_by_class_name("qq-upload-button").click() # driver.find_element_by_name("file").click() # 这里点文件上传按钮也是一个坑,我用它父元素定位了,参考上面一行 time.sleep(5) # 点击Shift键,切换英文输入法 k.tap_key(k.shift_key) time.sleep(1) # 键盘输入内容 k.type_string(r"D:\Pycharm\Pycharm\python-selenium\b1.jpg") # 输入文件地址 time.sleep(1) k.press_key(k.enter_key) # 按住回车键
r.adjust_for_ambient_noise(source) print(u"Minimum thres was set to {}".format(r.energy_threshold)) while True: audio = r.listen(source) try: value = r.recognize(audio) if (value == 'open command prompt'): k.press_key('Control_L') k.press_key('Alt_L') k.tap_key('t') k.release_key('Control_L') k.release_key('Alt_L') elif (value == 'go'): k.tap_key('Return') elif (value == 'music'): k.type_string('mpsyt') k.tap_key('Return') k.type_string('.') # Tell him you're ready! Put Google stt here : https://github.com/Glutanimate/simple-google-tts print ("What do you wanna listen?") elif (value == 'search in music'): k.type_string('.') else: k.type_string(value) k.tap_key('Return')
class ImageAuto: def __init__(self, wait=1): self.mouse = PyMouse() self.keyboard = PyKeyboard() self.wait = wait #图像匹配:参数为:模版图片的(由于模版图片每次不一样,所以要做为参数传参) def find_image(self, filename): ImageGrab.grab().save("./screen.png") # 通过ImageGrab的方法对当前屏幕截图 source = cv.imread("./screen.png") # 打开屏幕截图,也就是大图 template = cv.imread(filename) # 打开模版图片,也就是小图 result = cv.matchTemplate(source, template, cv.TM_CCOEFF_NORMED) #参数为、把大图、小图、算法 location = cv.minMaxLoc(result) pos_start = location[3] # 获取匹配度最高所对应的坐标,也就是小图的左顶点在大图中的位置 x = int(pos_start[0]) + int(template.shape[1] / 2) y = int(pos_start[1]) + int(template.shape[0] / 2) similarity = location[1] # 拿到匹配度最高的那个值来做判断 if similarity >= 0.85: return (x, y) else: return -1, -1 #单击,参数为模版图片,因为要利用模版图片来进行匹配,匹配成功后对得到的坐标进行单击 def click(self, filename): x, y = self.find_image(filename) self.mouse.click(x, y) time.sleep(self.wait) RecordLog.write(x, y, "单击") time.sleep(self.wait) # 双击,参数为模版图片,因为要利用模版图片来进行匹配,匹配成功后对得到的坐标进行单击 def double_click(self, filename): x, y = self.find_image(filename) self.mouse.click(x, y, n=2) time.sleep(self.wait) RecordLog.write(x, y, "双击") time.sleep(self.wait) #输入,参数为模版图片及输入的内容 def input(self, filename, content): x, y = self.find_image(filename) self.mouse.click(x, y, n=2) #双击选中文本框 self.keyboard.press_key(self.keyboard.backspace_key) #清空内容 self.keyboard.release_key(self.keyboard.backspace_key) #松开 time.sleep(self.wait) self.keyboard.type_string(content) time.sleep(self.wait) RecordLog.write(x, y, "输入", content=content) time.sleep(self.wait) #回退键 def key_backspace(self): self.keyboard.press_key(self.keyboard.backspace_key) self.keyboard.release_key(self.keyboard.backspace_key) time.sleep(self.wait) #回车键 def key_enter(self): self.keyboard.press_key(self.keyboard.enter_key) self.keyboard.release_key(self.keyboard.enter_key) time.sleep(self.wait) #上键--参数n为次数 def key_up(self, n=1): for i in range(n): self.keyboard.press_key(self.keyboard.up_key) self.keyboard.release_key(self.keyboard.up_key) time.sleep(self.wait) #下键--参数n为次数 def key_down(self, n=1): for i in range(n): self.keyboard.press_key(self.keyboard.down_key) self.keyboard.release_key(self.keyboard.down_key) time.sleep(self.wait) #F5刷新 def key_F5(self): self.keyboard.press_key(self.keyboard.function_keys[5]) self.keyboard.release_key(self.keyboard.function_keys[5]) time.sleep(self.wait) #移动 def move(self, filename): x, y = self.find_image(filename) self.mouse.move(x, y) self.mouse.click(x, y) RecordLog.write(x, y, "移动并单击") #下拉框的操作 def select(self, filename, n=1): x, y = self.find_image(filename) self.mouse.click(x, y) self.key_down(n=n) self.key_enter() #启动应用程序 def start_app(self, cmd): os.system("start /b " + cmd) time.sleep(self.wait * 3) def start_web(self, type, url): os.system("start /b %s %s" % (type, url)) time.sleep(self.wait) #断言 def exists(self, filename): time.sleep(self.wait) x, y = self.find_image(filename) if (x, y) == (-1, -1): return False else: return True
# @Time : 2019/9/4 9:01 # # @Author : WZG # --coding:utf-8-- import time from pymouse import PyMouse from pykeyboard import PyKeyboard k = PyKeyboard() m = PyMouse() a = m.position() print(a) m.click(699, 367) k.type_string('1、预先飞行计划管理系统功能测试(6)')
class Action(object): def __init__(self, file): self.file = file self.m = PyMouse() self.k = PyKeyboard() def action_read(self): # 从filename中读取操作序列 action_list = [] with open(self.file) as f: f_csv = csv.reader(f) for row in f_csv: action_list.append(row) return action_list def key_translate(self, key_data): # 识别序列中的键 if len(key_data) == 1: return key_data elif len(key_data) == 2 and key_data.startswith('F'): return self.k.function_keys[int(key_data[1])] elif key_data == 'enter': return self.k.enter_key elif key_data == 'space': return self.k.space_key elif key_data == 'control': return self.k.control_key elif key_data == 'alt': return self.k.alt_key else: raise Exception("未定义此操作!") def action_translte(self, action_unit): # 将序列语言翻译成指令 if action_unit[0] == '0': try: xy = eval(action_unit[1]) except Exception as e: return False x, y = xy[0], xy[1] self.m.click(x, y, 1) return True elif action_unit[0] == '1': try: keyboard_action_list = action_unit[1].split('_') if keyboard_action_list[0] == 'tap': # 敲击某个键 self.k.tap_key(key_data) elif keyboard_action_list[0] == 'press': # 按住某个键 key_data = self.key_translate(keyboard_action_list[1]) self.k.press_key(key_data) elif keyboard_action_list[0] == 'presses': # 按住某两个键 key_data1 = self.key_translate(keyboard_action_list[1]) key_data2 = self.key_translate(keyboard_action_list[2]) self.k.press_keys([key_data1, key_data2]) elif keyboard_action_list[0] == 'release': # 松开某个键 key_data = self.key_translate(keyboard_action_list[1]) self.k.release_key(key_data) elif keyboard_action_list[0] == 'type': # 输入 self.k.type_string(keyboard_action_list[1]) elif keyboard_action_list[0] == 'callcpp': x = int(keyboard_action_list[1]) y = int(keyboard_action_list[2]) #i_path = keyboard_action_list[3] #t_path = keyboard_action_list[4] result, x_t, y_t = call_c(x, y) #x_tt = x_t.value #y_tt = y_t.value print(x_t, y_t) x_tt = x_t.value y_tt = y_t.value self.k.type_string(str(x_tt) + '_' + str(y_tt)) elif keyboard_action_list[0] == 'drawc': self.draw_circle() except Exception: traceback.print_exc() return False else: print("对象输入错误") return False def run(self): action_list = self.action_read() action_lens = len(action_list) for i in range(1, action_lens): self.action_translte(action_list[i]) delay = eval( action_list[i][2] ) ######################################################??????????????????????????????? time.sleep(delay) def draw_circle(self): self.m.click(421, 62, 1) self.m.click(422, 61, 1) self.m.click(419, 59, 1) time.sleep(0.5) self.m.press(421, 500) time.sleep(0.5) self.m.move(600, 500) time.sleep(0.5) self.m.move(600, 670) time.sleep(0.5) self.m.release(600, 600) # type some words self.m.click(293, 68) self.m.click(478, 549) self.k.type_string("Hello World!")
def upload(self, file_path): self.click() time.sleep(5) kk = PyKeyboard() kk.type_string(file_path) kk.tap_key(kk.enter_key)
# m.click(486, 255, 1) # time.sleep( 0.5 ) # k.type_string(line.strip()) # m.click(669, 374, 1) # n=n+1 # time.sleep( 1 ) # # print(line) # 基地使用坐标 for line in open("ip.txt"): #print line, #python2 用法 m.click(288, 147, 1) time.sleep( 1 ) m.click(442, 178, 1) time.sleep( 0.5 ) k.type_string('neweyip'+str(n)) time.sleep( 1 ) m.click(466, 250, 1) time.sleep( 0.5 ) k.type_string(line.strip()) m.click(663, 375, 1) n=n+1 time.sleep( 1 ) # print(line) # for line in open("ip.txt"): # #print line, #python2 用法 # m.click(269, 142, 1)
import pymouse, pykeyboard, os, sys from pymouse import * from pykeyboard import PyKeyboard import time m = PyMouse() k = PyKeyboard() # m.click(int(297),int(53),int(-1),int(5)) #–鼠标点击 x_dim, y_dim = m.screen_size() # –获得屏幕尺寸 k.tap_key('G') # –模拟点击H键 print("x_dim, y_dim", x_dim, y_dim) m.move(1444, 400) time.sleep(3) m.click(1444, 327, -1, 2) #–鼠标点击 k.type_string('Hello, World!')
from pymouse import PyMouse from pykeyboard import PyKeyboard import time m=PyMouse() k=PyKeyboard() x,y=m.position() #print y print x,y m.move(790,304) m.click(790,304) k.type_string("*****@*****.**") time.sleep(1) m.move(784,345) m.click(784,345) k.type_string("gigglepig5") time.sleep(1) m.move(1054,325) m.click(1054,325) #m.click(x,y) #time.sleep(5) #m.click(648,98) #k.type_string("Y") #time.sleep(5) #k.tap_key(k.enter_key) #smithe65 #beaker1!
class Bot: MOVE_OKAY = 0 #Enumerated values for movement results MOVE_FAIL = 1 MOVE_INPR = 2 OBT_WT = 0.01 #Wait times for detection loops ENT_WT = 0.01 LWT_WT = 0.01 def AttackPos(self, pc): ''' Perform an attack on a given position ''' l, t, _, _ = self.sv.GetWindowPos() pc = (pc[0] + l, pc[1] + t) self.MouseMove(self.m.position(), pc) self.k.press_key('w') time.sleep(np.random.rand() / 2) self.k.release_key('w') print('Attack: ' + str(pc)) def __init__(self, name): self.wname = name #Name of the game window self.sv = ScreenViewer() #For getting screens of the game self.mm = MovementMap() #Bot's internal map of the world self.ts = TargetingSystem(m=7, n=9, ss=(800, 600), sb=(4, 0, 4, 12), cp=(400, 274), forceTrain=False) #self.ts = TargetingSystem(m = 6, n = 9, ss = (1278, 786), cp = (642, 342)) self.m = PyMouse() #PyMouse object for triggering mouse input self.k = PyKeyboard() #For triggering keyboard self.pm = ProjMap(800, 600) #Convert between 3d and 2d coords self.p = None #The current path of the bot self.pt = None #The current type of the path (to frontier, item, or home) self.pind = None #The next element to visit in the path self.p self.ghf = False #Go home flag self.cpi = 0 #Current potion index self.ssn = 0 #Debug: screenshot number self.mfc = 0 #Debug: movement flag count self.lwc = 0 #LW detection count self.hp = None #Home position self.pHealth, self.pMana = 0, 0 #Player health and mana self.nmmpm = 1 #Number of mouse move points multiplier self.ctl = False #Continue target loop flag self.ecp = [] #Enemy cell positions self.tlMut = Lock() self.tlut = None #Targeting loop update time self.tllct = None #Targeting loop last check time self.lwMut = Lock() #Mutex lock for checking if LW is happening self.clwl = False #Continue LW detection loop self.lwof = False #Lightning-warp occuring flag self.lwuo = False #Lightning-warp update occured self.obMut = Lock() self.cobl = False self.pct = [] #Shared grid position list self.pctlu = None #PCT last update time self.pctlg = None #PCT last get time def __del__(self): pass def ClickOnDoor(self): print('At door; reset instance!') raise NotImplementedError('ClickOnDoor not implemented.') def CPE(self): if self.p is None: return None return self.p[self.pind] def GetEnemyPositions(self): ''' Gets a current list of enemy positions in a thread safe manner ''' self.tlMut.acquire() lut = self.tlut #Last update time for enemy cell positions rv = self.ecp[:] #Make copy of current list to prevent race conditions self.tlMut.release() if self.tllct == lut: return [] #No update since last time self.tllct = lut #self.ecp has been updated; update time of last check return rv #Return copy def GetPath(self): ''' Makes a path for character ''' if self.mfc >= 4: #Moved failed 4 times; move anywhere else #print('Neighbor') self.p = self.mm.GetPathToNeighbor() self.pt = 0 elif len(self.mm.ItemPos()) > 0: #print('Item') self.p = self.mm.GetPathToItem() self.pt = 1 elif self.ghf: #Go home flag set; return to start #print('GO HOME!') self.p = self.mm.GetPathToHome() self.pt = 2 else: #Find path to frontier #print('Frontier') self.p = self.mm.GetPathToFrontier() self.pt = 0 if self.p is None: #Character doesn't know where to go #print('Path is still none.') self.p = self.mm.GetPathToNeighbor() self.pt = 0 if self.p is None: return False self.pind = max(len(self.p) - 2, 0) return True def GetPlayerPos(self): ''' Returns the current position of the player in 3d coords ''' cppl = self.ts.CharPos() #Get pixel location of character on screen return self.pm.Solve3DT( cppl[0], cppl[1]) #Get 3d location corresponding to pixel location def GetScreenDifference(self): I1, its = self.sv.GetScreenWithTime() #self.k.type_string('z') #Toggle item highlight while True: #Loop until new screen is available time.sleep(0.05) I2, its2 = self.sv.GetScreenWithTime() if its != its2: break #self.k.type_string('z') #Toggle item highlight #imsave('DI/' + str(self.ssn) + '.jpg', I1.astype(np.uint8)) #self.ssn += 1 #imsave('DI/' + str(self.ssn) + '.jpg', I2.astype(np.uint8)) #self.ssn += 1 R = np.where(np.abs(I1 - I2) >= 16, I2, 0) return R def GetScreenPredictions(self): self.lwMut.acquire() rv = self.pct[:] lut = self.pctlu self.lwMut.release() if self.pctlg == lut: return [] #No update since last time return rv def GoToPosition(self, pc): ''' #Click on a given pixel coordinate ''' l, t, _, _ = self.sv.GetWindowPos() pc = (pc[0] + l, pc[1] + t) self.MouseMove(self.m.position(), pc) self.k.type_string('r') #Use lightning warp to move to cell time.sleep(0.1) def GoToPosition2(self, pc): ''' Click on a given pixel coordinate ''' l, t, _, _ = self.sv.GetWindowPos() pc = (pc[0] + l, pc[1] + t) self.MouseMove(self.m.position(), pc) self.k.type_string('r') #Use lightning warp to move to cell mf = False r = 0 for j in range(64): #Detect lightning-warp animation r += self.ts.DetectLW(self.sv.GetScreen(), self.ts.CharPos()) if r > 2: print('LW1 Break!! ' + str(j)) mf = True break time.sleep(0.005) if not mf: return False nllw = 20 #Number of past DetectLW calls to remember lflw = np.ones((nllw)) #Result of last nllw DetectLW calls for j in range(256): lflw[j % nllw] = self.ts.DetectLW(self.sv.GetScreen(), self.ts.CharPos()) if lflw.sum() < 1: print('LW2 Break!! ' + str(j)) break time.sleep(0.005) return True def IsMoving(self): self.lwMut.acquire() rv = (self.lwof, self.lwuo) self.lwMut.release() return rv def LWDetectLoop(self): nllw = 20 #Number of past DetectLW calls to remember lwdt = 10 #Lightning-warp detection threshold lflw = np.zeros((nllw)) #Result of last nllw DetectLW calls i = 0 #Index into lflw tlwof = False while self.clwl: #LWPM scales prediction result based on time since LW button was pressed lflw[i] = self.ts.DetectLW(self.sv.GetScreen()) print(str(lflw[i])) i = (i + 1) % nllw #Use lflw as a circular array tlwof = lflw.sum() > lwdt self.lwMut.acquire() if not tlwof and self.lwof: #Update occurs when bot stops moving self.lwuo = True #Lightning-warp update occured self.lwof = tlwof self.lwMut.release() time.sleep(Bot.LWT_WT) def LWTest(self): ''' Used to determine delay for lightning-warp ''' self.sv.GetHWND(self.wname) self.sv.Start() l, t, _, _ = self.sv.GetWindowPos() pc = (700 + l, 150 + t) self.MouseMove(self.m.position(), pc) st = time.time() self.k.type_string('r') ftt, ltt = -1, -1 for _ in range(10): res = self.ts.DetectLW(self.sv.GetScreen()) print(str(time.time()) + ': ' + str(res)) if res and ftt == -1: ftt = time.time() if res: ltt = time.time() else: ltf = time.time() time.sleep(0.1) self.sv.Stop() print('First True: ' + str(ftt - st)) print('Last True: ' + str(ltt - st)) print('Total: ' + str(max(ltt, ltf) - st)) def MouseMove(self, sp, ep): nmmp = int(16 * self.nmmpm) if self.nmmpm > 1: self.nmmpm = 1 x = np.linspace(sp[0], ep[0], num=nmmp) y = np.linspace(sp[1], ep[1], num=nmmp) for i in range(len(x)): self.m.move(int(x[i]), int(y[i])) time.sleep(0.00005) def NextPathEle(self): self.pind -= 1 def ObjDetectLoop(self): while self.ctl: #Loop while continue targeting loop flag is set self.ts.ClassifyInput(self.sv.GetScreen( )) #Predicted cell types for portions of the screen #self.ts.DisplayPred() WP, PP = self.pm.GridIter() n = WP.shape[0] PCT = [(WP[i][0:3], CIi, self.ts.CellLookup(CIi)) for i, CIi in enumerate( self.ts.PixelToCell(PPi) for PPi in PP)] PCT = [PCTi for PCTi in PCT if PCTi[2] is not None ] #Filter out any grid cells covered by HUD self.obMut.acquire() self.pct = PCT #Update shared grid position list self.pctlu = time.time() #Update time self.obMut.release() time.sleep(Bot.OBT_WT) def PathDone(self): return self.p is None or self.pind < 0 def PickupItem(self): if self.p is None: return pp = self.ts.CharPos() dip = [(abs(pp[0] - px) + abs(pp[1] - py), (px, py)) for px, py in self.ts.GetItemLocations()] nip = len(dip) if nip == 0: print('No items found.') return dip.sort() l, t, _, _ = self.sv.GetWindowPos() for id, pc in dip[0:1]: self.k.press_key('z') self.k.press_key('f') #Depress pick-up key time.sleep(0.4) pc = (pc[0] + l, pc[1] + t) self.MouseMove(self.m.position(), pc) print('Pickup item: ' + str(pc)) self.m.click(int(pc[0]), int(pc[1]), 1) #Try to pick-up the item self.k.release_key('f') #Release pick-up key self.k.release_key('z') time.sleep(id / 512) #Wait long enough to get item self.mm.ItemRemove(self.p[0]) def Run(self): if not self.sv.GetHWND( self.wname): #Get the window handle for the game print("Failed to find window.") self.Start() cv, M_ITER = 0, 64 #Counter value and max number of loops while True: if cv >= M_ITER and not self.ghf: self.ghf = True cv = 0 if self.ghf and cv >= M_ITER: break self.pHealth = self.ts.GetHealth(self.sv.GetScreen()) self.pMana = self.ts.GetMana(self.sv.GetScreen()) if self.pHealth < 0.75: #Life is lower than 75%; use potion self.UseHealthPotion() if self.pMana < 0.25: #Mana is lower than 25%; user potion self.UseManaPotion() MSF = self.UpdatePosition() if MSF == Bot.MOVE_INPR: #Bot is still moving; don't try to move now print('Moving.') time.sleep(0.05) continue if MSF == Bot.MOVE_OKAY: #Predict open/obstacle if character moved cv += 1 print("Moved to: " + str(self.CPE())) winsound.Beep(600, 250) for WP, CI, PCTi in self.GetScreenPredictions(): self.mm.InsertCellPrelim(WP, PCTi, (not self.ts.IsEdgeCell(*CI)) or (PCTi == 'C')) if self.mm.InsertFinished( ): #Insert cells into map; may shift player location self.ShiftMap( ) #Translate projection to match new location self.p = None #Need to recompute path from new location if MSF == Bot.MOVE_FAIL: print("Move Failed.") winsound.Beep(440, 250) ecp = self.GetEnemyPositions() for ecpi in ecp: #Attack enemies self.AttackPos(tuple(int(k) for k in ecpi.round())) #Check for items on the screen. Doesn't work well!! #self.PickupItem() if len(ecp) > 0: self.SlowMouseMove() if self.PathDone(): #If there is no route current; find a new path if self.ghf and self.mm.AtHome(): self.ClickOnDoor() #Back to start elif self.pt == 1: self.PickupItem() #Pickup item on screen if not self.GetPath(): print("Couldn't make path...") time.sleep(0.05) continue #Failed to find a path; try again #Get pixel location on screen of 3d cell to go to l2d = tuple( int(k) for k in self.pm.Get2DT(np.array([self.CPE() ])).ravel().round()) self.GoToPosition(l2d) #Perform lightning-warp def ShiftMap(self, st=None): if st is None: #Translate projection map based on new character position st = self.mm.GetPosition() cpx, cpy, cpz = st #X, Y, Z components of shift hpx, hpy, hpz = self.hp self.pm.TranslateM(hpx - cpx, hpy - cpy, hpz - cpz) def SlowMouseMove(self): self.nmmpm = 10 def Start(self): self.sv.Start() #Start capturing images of the window cp3d = self.GetPlayerPos() #Get initial player position self.hp = cp3d #Update data member self.mm.Start(cp3d) #Update internal map self.p = None #The current path (of Exile, HA!) self.StartTargetLoop() #Start obtaining targets concurrently self.StartObjLoop() #Start detecting obstacles concurrently self.StartLWLoop() #Start detecting lightning-warp def StartLWLoop(self): self.clwl = True thrd = Thread(target=self.LWDetectLoop) thrd.start() return True def StartObjLoop(self): self.cobl = True thrd = Thread(target=self.ObjDetectLoop) thrd.start() return True def StartTargetLoop(self): self.ctl = True thrd = Thread(target=self.TargetLoop) thrd.start() return True def Stop(self): #Notify all concurrent threads to stop self.StopObjDetectLoop() self.StopTargetLoop() self.StopLWLoop() self.sv.Stop() def StopLWLoop(self): self.clwl = False def StopObjDetectLoop(self): self.cobl = False def StopTargetLoop(self): self.ctl = False #Turn off continue targeting loop flag def TargetLoop(self): while self.ctl: #Loop while continue targeting loop flag is set self.ts.DetectMovement( self.GetScreenDifference()) #Find cells that have movement self.ts.ClassifyDInput(self.sv.GetScreen( )) #Determine which cells contain enemies or items tecp = self.ts.EnemyPositionsToTargets() #Obtain target locations self.tlMut.acquire() self.ecp = tecp #Update shared enemy position listed self.tlut = time.time() #Update time self.tlMut.release() time.sleep(Bot.ENT_WT) def SplitSave(self, p='TSD/Train/Images', wp='TSD/Train/Split'): ''' #p: #Dir contains images to split #wp: #Dir to write split images ''' c = 0 if not os.path.exists(wp): os.mkdir(wp) pdl = np.random.choice( [fni for fni in os.listdir(p) if fni.startswith('di')], 32, replace=False) for i, fn in enumerate(pdl): print('{:4d}/{:4d}:\t{:s}'.format(i + 1, len(pdl), fn)) #A = imread(os.path.join(p, fn))[0:-14, 1:-1] #A = self.GetScreen() #S = self.ts.DivideIntoSubimages(A).astype(np.uint8) A = imread(os.path.join(p, fn))[0:-12, 4:-4, :] S = self.ts.DivideIntoSubimages(A).astype(np.uint8) for i, Si in enumerate(S): imsave(os.path.join(wp, '{:03d}.png'.format(c)), Si) c += 1 def SplitDataset(self, p='TS/Train', wp='TS/Train'): if not os.path.exists(wp): os.mkdir(wp) if not os.path.exists(os.path.join(wp, 'Enemy')): os.mkdir(os.path.join(wp, 'Enemy')) if not os.path.exists(os.path.join(wp, 'Closed')): os.mkdir(os.path.join(wp, 'Closed')) if not os.path.exists(os.path.join(wp, 'Open')): os.mkdir(os.path.join(wp, 'Open')) if not os.path.exists(os.path.join(wp, 'Overlay')): os.mkdir(os.path.join(wp, 'Overlay')) #Use old targeting system to classify new input #ts2 = TargetingSystem(m = 6, n = 9, ss = (1278, 786), cp = (642, 342), forceTrain = True) self.ts.C.RestoreClasses(['C', 'O', 'E']) dl = os.listdir(os.path.join(p, 'Split')) S, F = [], [] c = [0, 0, 0, 0] for i, fni in enumerate(dl): fpn = os.path.join(p, 'Split', fni) fnInt = int(fni[0:-4]) if fnInt % 63 == 0 or fnInt % 63 == 54 or fnInt % 63 == 55 or fnInt % 63 == 56 or fnInt % 63 == 57 or fnInt % 63 == 59 or fnInt % 63 == 60 or fnInt % 63 == 61 or fnInt % 63 == 62: nfp = os.path.join(wp, 'Overlay', fni) os.rename(fpn, nfp) print('os.rename(' + str(fpn) + ', ' + str(nfp)) continue S.append(imread(fpn)) F.append(fni) if len(S) > 20 or (i + 1) == len(dl): SS = np.stack(S) yh = self.ts.C.predict(SS) for j, yhj in enumerate(yh): if yhj == 'E': mp = 'Enemy' c[0] += 1 elif yhj == 'C': mp = 'Closed' c[1] += 1 elif yhj == 'H': mp = 'Overlay' c[2] += 1 else: mp = 'Open' c[3] += 1 nfp = os.path.join(wp, mp, F[j]) ofp = os.path.join(p, 'Split', F[j]) os.rename(ofp, nfp) print('os.rename(' + str(ofp) + ', ' + str(nfp)) S, F = [], [] print(str(c)) def UpdatePosition(self): isMoving, hasMoved = self.IsMoving() if isMoving: #Bot is still moving return Bot.MOVE_INPR if hasMoved: #Bot was moving but has now stopped self.mm.MoveTo(self.CPE()) #Update char pos in movement map self.ShiftMap() #Translate projection map self.NextPathEle() #Move on to next element in the path self.mm.ClearBlocked() #Blocked cells may change after moving self.lwMut.acquire() self.lwuo = False #Turn off the updated flag self.lwMut.release() return Bot.MOVE_OKAY #Only executes if neither condition above is true; meaning the bot failed to move entirely if self.CPE() is None: return Bot.MOVE_OKAY #Path is none when bot first starts self.mm.InsertBlocked(self.CPE()) self.p = None #Path didn't work; find new one return Bot.MOVE_FAIL def UseHealthPotion(self): self.k.type_string(str(self.cpi + 1)) self.cpi = (self.cpi + 1) % 2 #Rotate through potions def UseManaPotion(self): self.k.type_string('3')
def computer_type_input(my_string): '''模拟键盘输入字符串''' # 定义鼠标键盘实例 k = PyKeyboard() k.type_string(my_string)
def TapKeyBoard(self, keys): sleep(1) k = PyKeyboard() k.type_string(keys)
class ImageFrame: def __init__(self, process): self.mouse = PyMouse() self.keyboard = PyKeyboard() self.sleep = 1 self.process = process os.system("start /b %s" % process) time.sleep(1) # 模拟鼠标左键单击 def left_click(self, x, y): self.mouse.click(x, y) print("在(%s,%s)位置进行了鼠标左键单击操作" % (x, y)) time.sleep(self.sleep) # 模拟鼠标左键双击 def left_doubleclick(self, x, y): self.mouse.click(x, y, button=1, n=2) print("在(%s,%s)位置进行了鼠标左键双击操作" % (x, y)) time.sleep(self.sleep) # 模拟鼠标右键单击 def right_click(self, x, y): self.mouse.click(x, y, button=2, n=1) print("在(%s,%s)位置进行了鼠标右键单击操作" % (x, y)) self.mouse.click(x, y, button=1, n=1) time.sleep(self.sleep) # 模拟使用键盘按键 def enter_key(self, x, y, keys=[]): key = keys[0] self.keyboard.press_key(key) self.keyboard.release_key(key) print("在(%s,%s)位置进行了键盘按键操作" % (x, y)) time.sleep(self.sleep) # 模拟使用键盘产生输入 def input_key(self, x, y, strs=[]): str0 = strs[0] self.keyboard.type_string(str0) print("在(%s,%s)位置进行了键盘输入操作" % (x, y)) time.sleep(self.sleep) # 取坐标 def match_opencv(self, screen="screen", target="target", simi=1.0): basefolder = os.path.abspath(".") + "//screendata//" # ImageGrab.grab().convert("RGBA").save(basefolder + "%s.png" % screendata) screen1 = cv.imread(basefolder + "%s.png" % screen) target1 = cv.imread(basefolder + "%s.png" % target) result = cv.matchTemplate(screen1, target1, cv.TM_CCOEFF_NORMED) res = cv.minMaxLoc(result) minVal, maxVal, minLoc, maxLoc = res similar = maxVal # 取出最大匹配度 x, y = maxLoc # 取出识别到的最大匹配时的左上角的坐标 t = target1.shape h, w = t[0], t[1] position_x = x + w // 2 position_y = y + h // 2 if similar >= simi: return position_x, position_y else: return -1, -1
class Software(object): def __init__(self,keyword): self.k = PyKeyboard() #get pykeyboard self.software=keyword self.hWndChildList=0 self.para_hld=win32gui.FindWindow(None,self.software) if self.IsWindow(): self.hWndChildList=self.demo_child_windows(self.para_hld) #get hld attr=self.show_window_attr(self.para_hld) win32api.SetCursorPos([attr['post'][0],attr['post'][1]]) #Mover to post(x,y) ''' 判定窗口是否激活 ''' def IsWindow(self): if self.para_hld>0: return 1; else: return 0; ''' 窗口置顶 ''' def topWindow(self): self.Key_event('ctrl') win32gui.SetForegroundWindow(self.para_hld) #show window ''' 输入键盘事件 ''' def keyStr(self,st): self.k.type_string(st) ''' 输入键盘事件 ''' def Key_event(self,key): win32api.keybd_event(VK_CODE[key],0,0,0) # win32api.keybd_event(VK_CODE[key],0,win32con.KEYEVENTF_KEYUP,0) # ''' ldList: 'post:?§|left, top, right, bottom ''' def GetHld(self,post): for hld in self.hWndChildList: left, top, right, bottom =win32gui.GetWindowRect(hld) #get hld post left top right bottom #if (post[0]==left) & (post[1]==top) & (post[2]==right) & (post[3]==right): if (post[0]==left) & (post[1]==top): #get hld by (x,y) left top return hld return 0 ''' 通过字符找到窗口 ''' def GetHldWord(self,word): for hld in self.hWndChildList: title = win32gui.GetWindowText(hld) title=title.decode('gbk') if title==word: return hld return 0 ''' 获取窗口下的所有子窗口 ''' def demo_child_windows(self,parent): if not parent: return hWndChildList = [] win32gui.EnumChildWindows(parent, lambda hWnd, param: param.append(hWnd), hWndChildList) return hWndChildList #get all hld attr def show_window_attr(self,hWnd): if not hWnd: return title = win32gui.GetWindowText(hWnd) clsname = win32gui.GetClassName(hWnd) left, top, right, bottom =win32gui.GetWindowRect(hWnd) # attr = {'hWnd':hWnd,'title': title, 'clsname':clsname, 'post':[left,top,right,bottom]} return attr
""" Created on 2015. 5. 12. @author: Administrator """ from pymouse import PyMouse from pykeyboard import PyKeyboard m = PyMouse() k = PyKeyboard() x_dim, y_dim = m.screen_size() print x_dim print y_dim m.click(x_dim / 2, y_dim / 2, 1) k.type_string("Hello, World!") x, y = m.position() print x print y
Common(driver).sendWord("故上的束缚,造成纯真的人性的扭曲,造成入选初中语文,人民教育出版社九年级") # Common(driver).withdraw() # Common(driver).sendWord("间客房哈萨克发动机哈斯卡拉答复哈士大夫快速减肥还是卡及地方海事局卡的发挥看大夫撒反抗撒旦发萨科范德萨科技孵化\ # zxc,mvzx.vxmvxzvm.xzvcmxz,.vx.zv,mx,.cvmxz,cvmxcz,vmx,zvm看看撒开发撒士大夫卡萨开发;拉框受到法律飒飒离开对方 啊撒飞洒领导啊打发啊士\ # 离开房间拉萨的房间爱上了的看法金属拉丝卢萨卡发动机萨拉丁飞机撒赖扩大飞机加快速度khkj") # Common(driver).delete() # Common(driver).sendWord("《故乡》是现代文学家鲁迅于1921年创作的一篇短篇小说。小说以“我”回故乡的活动为线索,按照“回故乡”——“在故乡”——“离故\ # 乡”的情节安排,依据“我”的所见所闻所忆所感,着重描写了闰土和杨二嫂的人物形象,从而反映了辛亥革命前后农村破产、农民痛苦生活的现实;同时深刻\ # 指出了由于受封建社会传统观念的影响,劳苦大众所受的精神上的束缚,造成纯真的人性的扭曲,造成人与人之间的冷漠、隔膜,表达了作者对现实的强烈\ # 不满和改造旧社会、创造新生活的强烈愿望。该小说入选初中语文,人民教育出版社九年级") # Common(driver).copy() # Common(driver).transpond() # sleep(1) # driver.find_element_by_xpath('//*[@id="app"]/div/section/section/div[2]/div/div[2]/div/div[2]/div[1]/span[2]').click() # sleep(1) # # 发送附件 # os.system('C:\\Users\\LENOVO\\Desktop\\张凯\\111.exe') pym = PyMouse() pyk = PyKeyboard() driver.find_element_by_xpath( '//*[@id="app"]/div/section/section/div[2]/div/div[2]/div/div[2]/div[1]/span[2]' ).click() sleep(1) pyk.tap_key(pyk.shift_key) #切换为英文,看实际情况是否需要 sleep(1) pyk.type_string("C:\\Users\\LENOVO\\Desktop\\zhangkai\\webv1.1.xlsx" ) #打开文件所在目录,方便多个文件上传 sleep(1) pyk.tap_key(pyk.enter_key) sleep(1)
k.press_key(k.control_key) k.tap_key('t') k.release_key(k.control_key) # Getting an element where Keys can be passed # Opening a NEW TAB browser.get('http://hck.re/qcKgO4') m.click(598L,798L,1,1) k.type_string('*****@*****.**') k.tap_key(k.return_key) time.sleep(9) k.press_key(k.control_key) k.tap_key('w') k.release_key(k.control_key)
class EasyMonkey: def __init__(self): self.mouse = PyMouse() self.keyboard = PyKeyboard() self.sleep = 0.5 time.sleep(1) # 产生一个随机坐标 def get_position(self): x = random.randint(0, 1600) y = random.randint(0, 900) self.mouse.move(x, y) print(x, y) return x, y # 模拟鼠标左键单击 def left_click(self): x, y = self.get_position() self.mouse.click(x, y) print("在(%s,%s)位置进行了鼠标左键单击操作" % (x, y)) time.sleep(self.sleep) return x, y # 模拟鼠标左键双击 def left_doubleclick(self): x, y = self.get_position() self.mouse.click(x, y, button=1, n=2) print("在(%s,%s)位置进行了鼠标左键双击操作" % (x, y)) time.sleep(self.sleep) return x, y # 模拟鼠标右键单击 def right_click(self): x, y = self.get_position() self.mouse.click(x, y, button=2, n=1) print("在(%s,%s)位置进行了鼠标右键单击操作" % (x, y)) self.mouse.click(x, y, button=1, n=1) time.sleep(self.sleep) return x, y # 模拟使用键盘随机按键 def enter_key(self): x, y = self.get_position() keys = [ "a", "b", self.keyboard.numpad_keys[2], self.keyboard.numpad_keys[4] ] index = random.randint(0, (len(keys) - 1)) key = keys[index] self.keyboard.press_key(key) self.keyboard.release_key(key) print("在(%s,%s)位置进行了键盘随机按键操作" % (x, y)) time.sleep(self.sleep) return x, y # 模拟使用键盘产生随机输入 def input_key(self): x, y = self.get_position() strs = ["123", "456"] index = random.randint(0, (len(strs) - 1)) str0 = strs[index] self.keyboard.type_string(str0) print("在(%s,%s)位置进行了键盘产生随机输入操作" % (x, y)) time.sleep(self.sleep) return x, y