def special_commands(cmnd): if cmnd.lower().startswith('go up'): print('How many steps? (up to 9)') distance = keyboard.read_key() for i in range(0, int(distance)): inputter.press('w') time.sleep(input_sleep) inputter.release('w') append_vcp_log([datetime.now(),'go up','special']) elif cmnd.lower().startswith('go left'): print('How many steps? (up to 9)') distance = keyboard.read_key() for i in range(0, int(distance)): inputter.press('a') time.sleep(input_sleep) inputter.release('a') append_vcp_log([datetime.now(),'go left','special']) elif cmnd.lower().startswith('go down'): print('How many steps? (up to 9)') distance = keyboard.read_key() for i in range(0, int(distance)): inputter.press('s') time.sleep(input_sleep) inputter.release('s') append_vcp_log([datetime.now(),'go down','special']) elif cmnd.lower().startswith('go right'): print('How many steps? (up to 9)') distance = keyboard.read_key() for i in range(0, int(distance)): inputter.press('d') time.sleep(input_sleep) inputter.release('d') append_vcp_log([datetime.now(),'go right','special']) else: basic_commands(cmnd, 'special')
def read(self): print("\n{}".format(self.prompt)) char = keyboard.read_key() while (char!= 'enter'): print("Press Enter") char = keyboard.read_key()
def screeningRisque1(): global varRisque headerTitle() time.sleep(3) print("\tAppuyez sur la touche 'o' pour 'OUI' et 'n' pour 'NON'") print("\n") time.sleep(4) print("\t4) Êtes vous diabétique : ") print("\t(o) : OUI") print("\t(n) : NON") if keyboard.read_key() == "o": varRisque = varRisque + 35 print("\tReponse: OUI") time.sleep(3) screeningRisque2() elif keyboard.read_key() == "n": print("\tReponse: NON") time.sleep(3) screeningRisque2() else: time.sleep(4) print("\tOups! Votre choix semble ne pas exister") time.sleep(2) print("\n") print("\tNous allons réessayer, d'accord? C'est parti") time.sleep(3) screeningRisque1()
def main(): spamText = [] count = 0 flag = 'y' while (flag == 'y'): text = input("Spam Text : ") spamText.append(text) flag = input("Do you want to add more messages(y/n) : ") if (flag == 'n'): break count = int(input("How many times : ")) interval = float(input("Time interval(sec) : ")) # input time in seconds sec = 5 # countdown function call countdown(int(sec)) with alive_bar(count, title="Spaming!", spinner="classic") as bar: for _ in range(count): pyautogui.typewrite(random.choice(spamText)) pyautogui.press('enter') time.sleep(interval) bar() print('\nDone') print("Press any key to continue") keyboard.read_key() print("Happy hacking...! ;-)")
def fifth(self): if (self.image != ''): self.Mbox( 'Vui lòng nhấn phím chọn', '1.Directional Filer \n' '2.Median Threshold \n' '3.Exit \n', 1) while True: try: # used try so that if user pressed other than the given key error will not be shown if keyboard.read_key() == '1': self.directionalFilter() elif keyboard.read_key() == '2': image = cv2.imread(self.image, 0) kernel = np.ones((5, 5), np.float32) / 25 noise_img = self.sp_noise(image, 0.05) new_img = self.medianThreshold(noise_img, kernel, 50) plt.subplot(121), plt.imshow(noise_img), plt.title( 'SaltPepper') plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(new_img), plt.title( 'Threshold Median') plt.xticks([]), plt.yticks([]) plt.show() else: break except: break if self.image == '': self.Mbox('Message', 'Vui lòng chọn ảnh để hiển thị', 1)
def sixth(self): if self.image != '': self.Mbox( 'Vui lòng nhấn phím để chọn:', '1.Median filter \n' '2.Weiner \n' '3.Adaptive median \n' '4.Exit \n', 1) while True: try: # used try so that if user pressed other than the given key error will not be shown if keyboard.read_key() == '1': print("1") self.median() elif keyboard.read_key() == '2': self.weigner() elif keyboard.read_key() == '3': img = PIL.Image.open(self.image).convert('L') image = self.add_gaussian_noise(img, 30) adapImg = self.medianAdaptive(image, 3) cv2.imwrite('adaptiveMedian.jpg', adapImg) plt.subplot(221), plt.imshow(image), plt.title( "Image corrupted by noise") plt.xticks([]), plt.yticks([]) plt.subplot(222), plt.imshow(adapImg), plt.title( "Adaptive Median Filter") plt.show() elif keyboard.read_key() == '4': break except: break if self.image == '': self.Mbox('Message', 'Vui lòng chọn ảnh để hiển thị', 1)
def infoCivilite(): global varCivilite headerTitle() time.sleep(4) print("\tAppuyez sur la touche qui vous correspond") print("\n") time.sleep(4) print("\tCivilité : ") print("\t---------") print("\t(a) : Mlle") print("\t(z) : Mme") print("\t(e) : Mr") if keyboard.read_key() == "a": varCivilite = "Mlle" print("\tReponse: " + varCivilite) print("\n") infoIdentitifiant() elif keyboard.read_key() == "z": varCivilite = "Mme" print("\tReponse: " + varCivilite) print("\n") infoIdentitifiant() elif keyboard.read_key() == "e": varCivilite = "Mr" print("\tReponse: " + varCivilite) print("\n") infoIdentitifiant() else: time.sleep(4) print("\tOups! Votre choix semble ne pas exister") time.sleep(2) print("\n") print("\tNous allons réessayer, d'accord? C'est parti") time.sleep(3) infoCivilite()
def screeningExposition1(): global varExposition headerTitle() time.sleep(3) print("\tAppuyez sur la touche 'o' pour 'OUI' et 'n' pour 'NON'") print("\n") time.sleep(4) print("\t1) Avez vous été en contact avec un malade: ") print("\t(o) : OUI") print("\t(n) : NON") if keyboard.read_key() == "o": varExposition = varExposition + 60 print("\tReponse: OUI") time.sleep(3) screeningExposition2() elif keyboard.read_key() == "n": print("\tReponse: NON") time.sleep(3) screeningExposition2() else: time.sleep(4) print("\tOups! Votre choix semble ne pas exister") time.sleep(2) print("\n") print("\tNous allons réessayer, d'accord? C'est parti") time.sleep(3) screeningExposition1()
def image_similarity(): print('waiting for the key press') if keyboard.read_key('q'): print('you pressed q') img1 = pyautogui.screenshot(region=(651, 342, 340, 500)) img1.save(r"U:\Desktop\asdasd\research\tests\img1.jpg") img2 = pyautogui.screenshot(region=(1001, 342, 340, 500)) img2.save(r"U:\Desktop\asdasd\research\tests\img2.jpg") if keyboard.read_key('a'): print('you pressed q') width2 = 687 height2 = 242 img1 = pyautogui.screenshot(region=(653, 347, width2, height2)) img1.save(r"U:\Desktop\asdasd\research\tests\img1.jpg") img2 = pyautogui.screenshot(region=(653, 602, width2, height2)) img2.save(r"U:\Desktop\asdasd\research\tests\img2.jpg") img1 = Image.open("img1.jpg") img2 = Image.open("img2.jpg") diff = ImageChops.difference(img1, img2) print(diff.getbbox()) ImageDraw.Draw(diff) diff = ImageOps.invert(diff) diff = Image.blend(diff, img1, 0.04) diff.save('ok.jpg') os.startfile('ok.jpg')
def get_choice(self, skip_newline=False, return_choice_id=False): choice_num = 0 console = Console() while True: self.print_choices(choice_num, skip_newline=skip_newline) console.flush() keyboard.read_key() if keyboard.is_pressed('down'): choice_num += 1 if choice_num >= len(self.choices): choice_num = len(self.choices) - 1 elif keyboard.is_pressed('up'): choice_num -= 1 if choice_num < 0: choice_num = 0 for i, _ in enumerate(self.choices): if keyboard.is_pressed(str(i + 1)): choice_num = i if return_choice_id: return choice_num return self.choices[choice_num] for _ in self.choices: sys.stdout.write(CURSOR_UP_ONE) sys.stdout.write(ERASE_LINE) if keyboard.is_pressed('enter'): break sys.stdout.flush() if return_choice_id: return choice_num return self.choices[choice_num]
def get_choice(choices, skip_newline = False, return_choice_id = False): choice_num = 0 while True: for i, choice in enumerate(choices): if i == choice_num: print(f" ⇨ {i+1}. {choice}", end='') else: print(f" {i+1}. {choice}", end='') if not skip_newline: print('') console.flush() key = keyboard.read_key() keyboard.read_key() if key == 'down': choice_num += 1 if choice_num == len(choices): choice_num = len(choices) - 1 elif key == 'up': choice_num -= 1 if choice_num < 0: choice_num = 0 for _ in choices: sys.stdout.write(CURSOR_UP_ONE) sys.stdout.write(ERASE_LINE) if key == 'enter': break try: choice_num = int(key) - 1 break except: pass if return_choice_id: return choice_num sys.stdout.flush() return choices[choice_num]
def get_keybinds(self): print("What is your first keybind?") self.first_key = read_key(); print(self.first_key); time.sleep(0.5) print("What is your second keybind?") self.second_key = read_key(); print(self.second_key); time.sleep(0.5) input("|| Press [ENTER] to proceed forward ||"); os.system("cls") return self.get_limitation()
def asker(): while True: if keyboard.read_key() == "x": auto_dodge() elif keyboard.read_key() == "y": auto_accept() elif keyboard.read_key() == "enter": exit() else: asker()
def search_strs(): search_str = "" while True: time.sleep(0.1) key_press = keyboard.read_key() if key_press == "backspace" and search_str: search_str = search_str[:-1] elif len(key_press) == 1 and ('a' <= key_press <= 'z'): search_str += keyboard.read_key() else: continue yield search_str
def navigate(idx): key = keyboard.read_key() key = keyboard.read_key() if key == 'up': idx -= 1 if key == 'down': idx += 1 if key == 'enter': page_fuction(idx) return idx #listens to keyboard inputs and changes the index(idx).
def GameOver(gamesurface, score, highest_score): # 设置提示字体的格式 GameOver_font = pygame.font.SysFont('arial', 30) Score_font = pygame.font.SysFont('arial', 28) h_font = pygame.font.SysFont('arial', 28) Z_font = pygame.font.SysFont('arial', 24) Q_font = pygame.font.SysFont('arial', 24) # 设置提示字体的颜色 GameOver_colour = GameOver_font.render('Game Over', True, grey_colour) Score_colour = Score_font.render('Score: ' + str(score), True, grey_colour) h_colour = h_font.render('Your best score: ' + str(highest_score), True, grey_colour) Z_colour = Z_font.render('Input \'R\' to restart ~', True, (255, 255, 0)) Q_colour = Q_font.render('Input \'Q\' to quit !', True, red_colour) # 设置提示位置 GameOver_location = GameOver_colour.get_rect() GameOver_location.midtop = (300, 10) Score_location = Score_colour.get_rect() Score_location.midtop = (280, 50) h_location = Score_colour.get_rect() h_location.midtop = (280, 90) Z_location = Score_colour.get_rect() Z_location.midtop = (280, 150) Q_location = Score_colour.get_rect() Q_location.midtop = (290, 210) # 绑定以上设置到句柄 gamesurface.blit(GameOver_colour, GameOver_location) gamesurface.blit(Score_colour, Score_location) gamesurface.blit(Z_colour, Z_location) gamesurface.blit(Q_colour, Q_location) gamesurface.blit(h_colour, h_location) # 提示运行信息 pygame.display.flip() while True: if keyboard.read_key() == 'r' or keyboard.read_key() == 'R': break elif keyboard.read_key() == 'q' or keyboard.read_key() == 'Q': # 退出游戏 pygame.quit() # 退出程序 sys.exit()
def inputtest2(): bullet = 10 while (True): key = keyboard.read_key() if (key == 'esc'): break elif (key == 'down'): print("뒤로!!") elif (key == 'up'): print("앞으로!!") elif (key == 'left'): print("좌회전!!") elif (key == 'right'): print("우회전!!") elif (key == 'a'): if (bullet > 0): bullet = bullet - 1 print("사격-탕!!, 남은총알 = ", bullet) else: print("총알이 없습니다.") elif (key == 'space'): print("Jump!!") else: pass print("ESC 키가 입력되어 프로그램을 종료합니다.") pass
def get_key(self): while not self.isover: if self.durum: temp = keyboard.read_key() if (temp == "w" or temp == "up") and (self.cur != "s" and self.cur != "w"): self.cur = "w" self.durum = False if (temp == "a" or temp == "left") and (self.cur != "d" and self.cur != "a"): self.cur = "a" self.durum = False if (temp == "s" or temp == "down") and (self.cur != "w" and self.cur != "s"): self.cur = "s" self.durum = False if (temp == "d" or temp == "right") and (self.cur != "a" and self.cur != "d"): self.cur = "d" self.durum = False if temp == "f3": self.debug = True if temp == "f4": self.debug = False if temp == "esc": self.isover = True
def visualize_bounding_boxes(folder, gt, predictions=None, delay=24): """ use this function to see the ground-truth boxes on the sequence. :param folder: path to the folder containing the frames of the video sequence. :param gt: ground truth box location for each frame (output of read_ground_truth). :param predictions: prediction box location for each frame. :param delay: delay between each frame. :return: void """ frames = get_frames(folder) for i, frame in enumerate(frames): gt_bb = gt[i] pred_bb = predictions[i] frame = cv2.imread(frame, cv2.IMREAD_COLOR) cv2.rectangle(frame, (gt_bb[0], gt_bb[1]), (gt_bb[0] + gt_bb[2], gt_bb[1] + gt_bb[3]), color=(255, 0, 0)) cv2.rectangle(frame, (pred_bb[0], pred_bb[1]), (pred_bb[0] + pred_bb[2], pred_bb[1] + pred_bb[3]), color=(0, 0, 255)) cv2.imshow('sequence', frame) cv2.waitKey(delay=delay) if keyboard.is_pressed("space"): while True: cv2.waitKey(delay=300) if keyboard.read_key() == "space": cv2.waitKey(delay=300) break
def playmusic(): filz = "alertsfx.mp3" mixer.init() mixer.music.load(filz) mixer.music.play() if keyboard.read_key() == 'space': mixer.music.stop()
def record(): mon = {'top': 0, 'left': 0, 'width': 1650, 'height': 1000} screen_data = [] with mss() as sct: # mon = sct.monitors[0] for i in list(range(9))[::-1]: print(i + 1) time.sleep(1) while True: key_pressed = keyboard.read_key(True) if key_pressed == 'q': break print(key_pressed) last_time = time.time() img = sct.grab(mon) print('fps: {0}'.format(1 / (time.time() - last_time))) np_img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY) processed_img = cv2.resize(np_img, (266, 133)) # processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300) # # processed_img = cv2.GaussianBlur(processed_img, (5, 5), 0) # cv2.imshow('test', processed_img) screen_data.append((processed_img, key_pressed)) np.save('screens.npy', screen_data) if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break
def menu (array, name, scroll): global score global trials index = 0 if scroll == True: scrollDisplay(array, index, name) else: staticDisplay(array, index, name) while True: key = keyboard.read_key() if key == "up": index = (index - 1)%len(array) elif key == "down": index = (index + 1)%len(array) elif key == "enter": return index elif key == "esc": if trials == 0: sentence = 'No questions answered?' else: sentence = f'You scored {score}/{trials} or {int(score/trials*100)}%' screen.clear() screen.addstr(sentence) screen.refresh() time.sleep(5) exit(sentence) if scroll == True: scrollDisplay(array, index, name) else: staticDisplay(array, index, name) time.sleep(0.2)
def Pause(self): print('Press [space] to continue...') pressed_key = '' while ((pressed_key != 'space') and (pressed_key != 'esc')): pressed_key = keyboard.read_key() if (pressed_key == 'esc'): self.CloseGame()
def main(): #choice = "" #creates a blank string for user input keyPress = "" #while choice != "3": while keyPress != "3": print("Enter '1' to open Visio AP Naming tool") print("Enter '2' to open Visio AP Coloring tool") print("Enter '3' to quit program\n") #choice = input(">>> ") keyPress = keyboard.read_key() if keyPress == "1": import VisioNameTool as vnt vnt.theGUI() #the GUI function calls these internally: break #vnt.startWorkbook() #vnt.openFiles() #vnt.visioLoop() #vnt.visioGuts() #vnt.saveExcel() elif keyPress == "2": #AutoColor Tool start = Options() start.open_audit_sheet() start.audit_sheet_sorter() start.search_options() root = tkinter.Tk() A_C = AutoColor(master=root) A_C.master.title("Visio AP Coloring Tool") A_C.mainloop() break else: print("Invalid input") pass
def conversion(song): for song in song: # Extension in which file is supposed to be converted mp3_song = os.path.splitext(song)[0] + ".wav" """ Support .mp3, .mp4, .ogg, .aac, .flv, .mkv, .flac, .wav """ sound = pydub.AudioSegment.from_mp3(song) # Change the extension to the desired format sound.export(mp3_song, format="wav") # If you want to keep the old format, Press anything other than [y] print( "Converted", os.path.basename(mp3_song), "Do you want to delete the original files? Press [y] for Yes.\n", ) while True: if keyboard.read_key() == "y": print("Deleting Duplicate File\n") os.remove(song) print("Thank You\n") break else: print("Nothing Deleted!!!\n") break print("Conversion Done")
def main(size, win): gboard = Gameboard(size, win) # object gboard is the game board gboard.clrscr() gboard.printboard() if gboard.size == 1: # edge case for board size of 1*1 if gboard.win == 2: print("You Win") print("Your Score is: ", gboard.score) exit(0) else: print("You Lose") print("Your Score is: ", gboard.score) exit(0) while True: curmove = keyboard.read_key( ) # it reads the key but doesn't display it on screen ans = gboard.gmove(curmove) gboard.clrscr() gboard.printboard() if ans == 2: print("You Lose") print("Your Score is: ", gboard.score) exit(0) elif ans == 3: print("You Win") print("Your Score is: ", gboard.score) exit(0) elif ans == 0: print("Invalid Move") time.sleep( 0.25 ) # sleeps the thread so that too many keypresses aren't captured easily
def getData(queue_raw): for num in range(1000): queue_raw.put(num) print("getData: put " + str(num) + " in queue_raw") while True: if keyboard.read_key() == "s": break
def getKeyForBtn(btn): key = keyboard.read_key() if key != "esc": btn['text'] = key logger.debug( "(settings_menu) detected key '{}' with scancode {}".format( key, keyboard.key_to_scan_codes(key)))
def handle(self): self.send_inst = True while (self.send_inst): #self.key = getkey() self.key=keyboard.read_key() if self.key == "up": self.data='u' print("u") if self.key == "down": self.data='d' if self.key == "right": self.data='r' if self.key == "left": self.data='l' if self.key == 's': self.data='s' if self.key == 'q': break if self.key == 'a': self.data='a' if self.key == 'z': self.data='z' #self.data ='s' self.request.sendall(self.data.encode()) time.sleep(0.5)
def display_students(self): self.helper.display_all_students(0, False) time.sleep(1) curr_order = False curr_sort = 0 while True: selection = keyboard.read_key() time.sleep(1) if selection == '1': curr_sort = 3 elif selection == '2': curr_sort = 4 elif selection == '3': curr_sort = 5 elif selection == 'q': curr_order = False elif selection == "a": curr_order = True elif selection == 'backspace': self.refresh_main_menu() time.sleep(1) break else: continue self.helper.display_all_students(curr_sort, curr_order)
import keyboard import os ans = "" def exit_(): f = open("log.txt","w") f.write(ans) f.close() os._exit(1) while True: try: keyboard.add_hotkey('shift+esc', exit_) if keyboard.read_key(): key = keyboard.read_key() ans += key else: pass except: break
def process(): queue.put(keyboard.read_key(suppress=True))