def friendmactch(friend): special_list=[] counter= 0 for person in friends: checker = frndct.get(person, None) if checker is None and person !=friend: print friend print person print "Do they know each other?\n Press the right arrow key if they are connected. Press the left arrow key if they are not connected\n" satisfaction = "no_satisfaction" while satisfaction == "no_satisfaction": response = readchar.readkey() print response if response == "\x1b[C": special_list.append(person) print '\n\n' response = 0 satisfaction = "satisfaction" elif response == "\x1b[D": print '\n' response = 0 satisfaction = "satisfaction" elif person !=friend: counter +=1 return special_list
def test_special_combo_character(self): char = '\x1b\x01' getchar_fn = readchar_fn_factory(char + 'foo') result = readkey(getchar_fn) self.assertEqual(char, result)
def test_special_key_combo(self): char = '\x1b\x5b\x33\x5e' getchar_fn = readchar_fn_factory(char + 'foo') result = readkey(getchar_fn) self.assertEqual(char, result)
def main(): # set up controller and listener listener = SampleListener() controller = Leap.Controller() # Have the sample listener receive events from the controller controller.add_listener(listener) # basically need a thread to do looping here only because of the blocking keyboard input in main() t = threading.Thread(target=looper, args=(record_queue, controller) )#, args = (q,u)) t.daemon = True t.start() # Keep this process running until Enter or space or ctrl+c is pressed print "Press Enter or Ctrl+C to quit." print "Press 1 to 0 to change instruments..." # try: while True: # print "l" # for event in pygame.event.get(): # if event.type == pygame.QUIT: # pygame.quit(); #sys.exit() if sys is imported # if event.type == pygame.KEYDOWN: # if event.key == pygame.K_0: # print("Hey, you pressed the key, '0'!") print "" char = readchar.readkey() if char == '\r' or char == ' ' or char == '\x03': controller.remove_listener(listener) sys.exit(0) # the following channel-to-instrument mappings are for my LinuxSampler setup; # yours will probably be different (remember you may need to subtract 1 from the channel shown in Linuxsampler) elif char == '1': setchan(2, "Piano") elif char == '2': setchan(3, "Harp") elif char == '3': setchan(6, "Violin (fast)") elif char == '4': setchan(5, "Cello (plucked)") elif char == '5': setchan(14, "Clarinet Ensemble (sustained)") elif char == '6': setchan(8, "Acoustic Guitar") elif char == '7': setchan(4, "Strings (sustained)") elif char == '8': setchan(15, "Double Bass piz.") elif char == '9': setchan(1, "Viola sus.") elif char == '0': setchan(0, "Drums") elif char == 'm': setmode(not play_mode)
def start(self): self.switch() self.loop_printer.run() while True: k = readchar.readkey() if k == ' ': self.switch() if k == 'q': raise SystemExit
def drive_spark(spark): max_speed = 65000 dir_l = 0 dir_r = 0 speed = 0 vec = 0 while (1): left = speed + (vec*speed) right = speed - (vec*speed) if (max(left,right)>1): left = left / 2.0 right = right / 2.0 if left < 0: dir_l = 1 left = abs(left) else: dir_l = 0 if right < 0: dir_r = 1 right = abs(right) else: dir_r = 0 lmotor = left * max_speed rmotor = right * max_speed spark.set_motor_speed(6, lmotor) spark.set_motor_speed(5, rmotor) spark.set_motor_direction(6, dir_l) spark.set_motor_direction(5, dir_r) k = readkey() if k == 'w': speed += 0.05 if k == 's': speed -= 0.05 if k == 'a': vec -= 0.1 if k == 'd': vec += 0.1 if k == ' ': speed = 0 vec = 0 dir_l = 0 dir_r = 0 if k == 'X': break vec = max(min(vec,1),-1) speed = max(min(speed,1),-1) spark.set_motor_direction(6, 0) spark.set_motor_direction(5, 0) spark.set_motor_speed(6, 0) spark.set_motor_speed(5, 0)
def keypress(): global char global s_current global s_voltage while True: char = readchar.readkey() if char=='i': s_current=s_current-1 if char=='I': s_current=s_current+1 if char=='v': s_voltage=s_voltage-10 if char=='V': s_voltage=s_voltage+10
def display_menu(targets): # We need at least one target for our UI to make sense num_targets = len(targets) if num_targets <= 0: puts('Whoops, you don\'t have any targets listed in your config!') exit(0) # Determine the longest host length longest_host = -1 for target in targets: length = len(target['host']) if length > longest_host: longest_host = length # Clear screen, give instructions call(['tput', 'clear']) puts(colored.cyan('Select a target (up, down, enter, ctrl+c to exit)')) # Save current cursor position so we can overwrite on list updates call(['tput', 'sc']) # Keep track of currently selected target selected_target = 0 while True: # Return to the saved cursor position call(['tput', 'rc']) # Print items for index, target in enumerate(targets): desc = target['host'].ljust(longest_host) + ' | ' + target['friendly'] if index == selected_target: puts(colored.green(' -> ' + desc)) else: puts(' ' + desc) # Hang until we get a keypress key = readchar.readkey() if key == readchar.key.UP: # Ensure the new selection would be valid if (selected_target - 1) >= 0: selected_target -= 1 elif key == readchar.key.DOWN: # Ensure the new selection would be valid if (selected_target + 1) <= (num_targets - 1): selected_target += 1 elif key == readchar.key.ENTER: # For cleanliness clear the screen call(['tput', 'clear']) # After this line, ssh will replace the python process os.execlp('ssh', 'ssh', targets[selected_target]['host']) elif key == readchar.key.CTRL_C: exit(0)
def key_input(self): while True: # read keyboard input (from SSH or from Raspberry Pi) k = readkey() if k in self.move_keys.keys(): ''' Motor movement''' serial_command = 'jog({},{},{})'.format(self.move_keys[k][0], self.move_keys[k][1], self.move_keys[k][2]) if self.fergboard_connect is True: self.serial_controllers['fergboard'].serial_write(serial_command, parser='fergboard') elif self.fergboard_connect is False: print(serial_command) elif k in ['[', ']', 't', 'y']: if k == ']': serial_command = 'set_speed(increase)' elif k == '[': serial_command = 'set_speed(decrease)' # elif k == 't': # serial_command = 'move(1000,1000,1000)' # elif k == 'y': # serial_command = 'move(-1000,-1000,-1000)' self.serial_controllers['fergboard'].serial_write(serial_command, parser='fergboard') if self.fergboard_connect is False: print(serial_command) # arduino connection for temperature control elif k in ['v', 'b', 'o', 'l']: ''' peltier controlling''' if k == 'v': print('start cooling') serial_command = 'cool' elif k == 'b': print('start heating') serial_command = 'heat' elif k =='o': serial_command = 'led_on' elif k == 'l': serial_command = 'led_off' if self.arduino_connect is True: self.serial_controllers['parabolic'].serial_write(serial_command, parser='parabolic') elif k in ['x']: print('Exiting...') if self.fergboard_connect is True: self.serial_controllers['fergboard'].close() if self.arduino_connect is True: self.serial_controllers['parabolic'].close() break
def key(): if has_r: f=open("c.txt","w") u=readchar.readkey() i=0 while i!=len(u): f.write(str(ord(u[i]))+" ") i+=1 f.close() else: os.system("read -n 1 c; echo $c>temp.txt;echo -e -n '\\b'") f=open("temp.txt","r") u=ord(f.read()[0]) f.close() f=open("c.txt","w") f.write(str(u)) f.close()
def main(): """The main function. """ parser = argparse.ArgumentParser() parser.add_argument("--port", default="/dev/arduino") parser.add_argument("--reset-type", type=int, default=-1) parser.add_argument("--baudrate", "-b", type=int, required=True) args = parser.parse_args() print print "Press CTRL-C to exit the console." print dev_serial = serial.Serial(args.port, baudrate=args.baudrate) if args.reset_type == 0: dev_serial.rts = 0 dev_serial.dtr = 1 time.sleep(0.5) # Let go of the reset. dev_serial.dtr = 0 # Start the serial reader thread. serial_reader_thread = threading.Thread(target=serial_reader_main, args=(dev_serial, )) serial_reader_thread.setDaemon(True) serial_reader_thread.start() # Read user input. while True: key = readchar.readkey() # Break on CTRL-C. if key == readchar.key.CTRL_C: break if key == readchar.key.ENTER: dev_serial.write('\r\n') else: dev_serial.write(key) print
def access_options(self, gtg) -> str: pressed_key = "" while pressed_key != "Enter": self.deactivate_options() self.options[self.active_option].toggle() self.print_box(gtg.scr) pressed_key = readchar.readkey() if pressed_key == "Up": self.active_option -= 1 elif pressed_key == "Down" or pressed_key == "Tab": self.active_option += 1 elif self.abortable and pressed_key == "Escape": return "" if self.active_option == len(self.options): self.active_option = 0 elif self.active_option < 0: self.active_option = len(self.options) - 1 return self.options[self.active_option].text
def get_input(self): """ Retrieve input from user with every keystroke buffered """ while True: keypress = readkey() if keypress == key.CTRL_C: raise KeyboardInterrupt('Ctrl + C combination detected') if keypress in (key.ENTER, key.CR): print('\n\r', end='') break if keypress in (key.UP, key.DOWN, key.LEFT, key.RIGHT): continue if keypress == key.BACKSPACE: self.buffer = self.buffer[:-1] else: self.buffer = self.buffer + keypress print("\r\033[K" + self.buffer, end='', flush=True) result = str(self.buffer) self.buffer = "" return result
def main(): g = ModelGraph(mode="test") with tf.Session() as sess: tf.sg_init(sess) # restore parameters saver = tf.train.Saver() saver.restore(sess, tf.train.latest_checkpoint('asset/train')) print("Restored!") mname = open('asset/train/checkpoint', 'r').read().split('"')[1] # model name char2idx, idx2char = load_char_vocab() word2idx, idx2word = load_word_vocab() previous = [0] * 50 # a stack for previous words para = "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE" ctx = [0] * 50 while True: key = readchar.readkey().lower() if key == readchar.key.BACKSPACE: ctx.insert(0, previous.pop()) ctx.pop() previous.insert(0, 0) elif key == readchar.key.ESC: break else: key_idx = char2idx[key] ctx.append(key_idx) ctx.pop(0) logits = sess.run(g.logits, {g.x: np.expand_dims(ctx, 0)}) preds = logits.argsort()[0][-3:] # pred = np.argmax(logits, -1)[0] predword1, predword2, predword3 = [ idx2word.get(pred) for pred in preds ] print(predword1, ' ', predword2, ' ', predword3)
def menu(self, options, instructions=""): menu_index = 0 while True: self.visualize_menu(options, menu_index, instructions=instructions) try: key = readchar.readkey() if key == 'w' or key == readchar.key.UP: menu_index -= 1 elif key == 's' or key == readchar.key.DOWN: menu_index += 1 elif key == 'q': break elif key == 'e' or key == readchar.key.ENTER: return menu_index menu_index = menu_index % len(options) time.sleep(.1) except KeyboardInterrupt: pass
def display_tasks(task_objects): '''Menu used to show entries to a user''' indexed_tasks = collections.deque( zip(task_objects, range(1, len(task_objects) + 1))) #provides a count of each task in `task_objects` while True: clear_screen() i = indexed_tasks[0][1] # Task #__ of len(task_objects) show_task = indexed_tasks[0][0] by_employee = str( main.Employee.get(main.Employee.id == show_task.employee.id) ).upper() # Employee of task print(f'***Task #{i} of {len(task_objects)}****') print(f''' Employee: {by_employee} Task: {show_task.task} Task Date: {show_task.task_date} Details : {show_task.note} Time: {show_task.time_duration}\n''') print('*' * 20) print( '[C] - Next Task Entry\n[P] - Previous Task Entry\n[B] - Back To Previous Menu' ) while True: print("Please select one of the above options...") user_choice = readchar.readkey().upper() if user_choice not in ['C', 'P', 'B']: print("Invalid selection...") continue break if user_choice == 'C': indexed_tasks.rotate(-1) continue elif user_choice == 'P': indexed_tasks.rotate(1) continue return # exit loop if user input is `B`
def main(): log = get_logger('main') broadcaster = sys.argv[1] if len(sys.argv) >= 2 else '' pipe = Pipe() pipe_comm = pipe.pipe_a pipe_watcher = pipe.pipe_b comm_thread = threading.Thread(target=communicator_runner, args=(pipe_comm, broadcaster)) # target=comm_dummy, args=(pipe_comm, broadcaster)) watcher_thread = threading.Thread(target=chat_watcher_runner, args=(pipe_watcher, broadcaster)) # target=comm_test, args=(pipe_watcher, broadcaster)) comm_thread.start() watcher_thread.start() log.info('started threads') print( 'controls: [q]uit\t[a]/[z] delay\t[c]hange broadcaster\t[l]evels reload' ) try: while True: inp = readkey() if inp == 'q': raise Exception('Quit pressed') elif inp == 'a': pipe_watcher.put(('delay', 0.5)) elif inp == 'z': pipe_watcher.put(('delay', -0.5)) elif inp == 'c': new_broadcaster = input('Enter new broadcaster: ') pipe_comm.put(('broadcaster', new_broadcaster)) pipe_watcher.put(('broadcaster', new_broadcaster)) elif inp == 'l': pipe_comm.put(('levels_reload')) watcher_thread.join() comm_thread.join() except Exception as ex: log.error('main thread error', ex) pipe_comm.put(Exception('main thread error')) pipe_watcher.put(Exception('main thread error')) finally: logging.shutdown()
def read_input(self): key = readchar.readkey() if key == readchar.key.CTRL_C or key in 'qQ': self.handlers['exit']() elif key == readchar.key.LEFT: self.input_buffer = '' self.handlers['prev']() elif key == readchar.key.RIGHT: self.input_buffer = '' self.handlers['next']() elif key == readchar.key.BACKSPACE: self.input_buffer = self.input_buffer[:-1] elif key.isdigit(): if len(self.input_buffer) == 0 and key != '0' or \ len(self.input_buffer) > 0: self.input_buffer += key if len(self.input_buffer) == 3: self.handlers['new_page'](int(self.input_buffer)) self.input_buffer = ''
def do_GET(self): self.send_response(200) self.send_header('Content-type','application/json') self.end_headers() print("Write to stdin") while True: key = readkey() if key == '\x03': break data = {"action": key} print(Time(), 'Sending', data) self.wfile.write( bytes(json.dumps(data), encoding='utf8')) self.wfile.write(b'\n') self.finish() httpd.shutdown()
def interactive_mode(point, vol_mult) : print("entering interactive mode") if args.loop==False : print("q & e control volume") else : print("loop mode is activated, this will only update when position is updated") print("wasd controls location") print("c exits") x=point[0] y=point[1] while True : try : key=readchar.readkey() if key=='s' : #point up y+=1 elif key=='w' : #point down y-=1 elif key=='d' : #point left x-=1 elif key=='a' : #point right x+=1 elif key=='v' : #prints volumes output_volumes() elif key=='c' : break if args.loop==False : if key=='e' :#volume up vol_mult+=.025 elif key=='q' : #volume down vol_mult-=.025 else : base_mult=get_base_mult([x,y]) if base_mult!=vol_mult : vol_mult=base_mult equalize_to_point(vol_mult, [x,y]) print("[{0},{1}]:{2:3f}".format(x,y, vol_mult)) equalize_to_point(vol_mult, [x,y]) time.sleep(.1) except KeyboardInterrupt: pass
def tui_func(actions): increment = .1 try: while 1: print "zero = Z - V faster = Q - R slower = A - F full = W - E full back = S - D exit = X - C" inp = readchar.readkey().upper() print "You pressed {}".format(inp) actions["input_recorded"]() if inp == "Q": actions["set_left_throttle"](actions["get_left_throttle"]() + increment) elif inp == "A": actions["set_left_throttle"](actions["get_left_throttle"]() - increment) elif inp == "Z": actions["set_left_throttle"](0) elif inp == "W": actions["set_left_throttle"](1) elif inp == "S": actions["set_left_throttle"](-1) elif inp == "X" or inp == "C": print "Bye!" actions["terminate"]() elif inp == "R": actions["set_right_throttle"](actions["get_right_throttle"]() + increment) elif inp == "F": actions["set_right_throttle"](actions["get_right_throttle"]() - increment) elif inp == "V": actions["set_right_throttle"](0) elif inp == "E": actions["set_right_throttle"](1) elif inp == "D": actions["set_right_throttle"](-1) else: logging.warning("Unrecognized input {}".format(inp)) logging.info("Key:Throttle: {} - {}".format( actions["get_left_throttle"](), actions["get_right_throttle"]())) except Exception as exc: logging.error("Error: in tui_thread - {0}".format(exc)) traceback.print_exc()
def play(self): """ This method handles the main loop of the game, including procession of player input and everything else. :return: """ playing = True skip_npc_turn = False record = False last_input_time = time.time() if self.log_filename != "": self.log_file = open(self.log_filename, "w") record = True self.prepare_new_map() print(self.colours.clear()) while playing: self.scr.print(record, self) status_effects.remove_status_effects(self) input_delay.apply_delay(self.configurations["input_delay"], last_input_time) last_input_time = time.time() self.user_input = readchar.readkey() # try: # self.user_input = input()[0] # except IndexError: # self.user_input = " " playing, skip_npc_turn = self.player_turn(playing, skip_npc_turn) if playing: if not skip_npc_turn: self.current_level.npc_actions(self) status_effects.apply_status_effects(self) else: skip_npc_turn = False self.current_level.build_map_colour(self) if not self.player.is_alive(): self.scr.print(record, self) playing = False else: pass
def showMenu(message, optionList): # cursors UP = '\x1b\x5b\x41' DOWN = '\x1b\x5b\x42' ENTER = '\x0d' #Checks if there is at least one eelement in the list. if len(optionList) == 0: return EMPTY_OPTION_LIST #Cursor position is an integer initially at the first element cursor = 0 clearScreen() #This is the loop that prints the menu while True: print(message) current = 0 for item in optionList: if cursor == current: print('> ' + item) else: print(item) current += 1 key = readchar.readkey() if key == 'a': break if key == UP: cursor = cursor - 1 if cursor > 1 else 0 if key == DOWN: cursor = cursor + 1 if cursor < len(optionList) - 1 else cursor if key == ENTER: clearScreen() # print('Selected: ' + str(optionList[cursor])) return cursor, optionList[cursor] clearScreen()
def handle_long_output(output_buffer): global rows, columns, display_size original_output = output_buffer output_buffer = output_buffer.replace('\t', 8 * '') output_buffer_split = output_buffer.split('\n') output_buffer = '' for line in output_buffer_split: output_buffer += line + ' ' * (columns - (len(line) % columns)) cmd = '_' current_display_ptr = 0 while cmd != 'q': if cmd == ' ' or cmd == '\x1b[B': current_display_ptr += columns if cmd == '\x1b[A': current_display_ptr -= columns if cmd == 's': path = input('specify the file path') try: f = open(path, 'w') f.write(original_output) f.close() except: print( "Request could not be completed please check the file path" ) continue os.system('clear') print(output_buffer[current_display_ptr:current_display_ptr + display_size] + '\n\n') if current_display_ptr + display_size >= len(output_buffer): break print( 'Press space or down arrow: to move down, up arrow: to move up, and q: quit viewing output' ) sys.stdout.write(':') sys.stdout.flush() cmd = readchar.readkey() if cmd != '_': os.system('clear')
def showMenu( message, optionList ): # cursors UP = '\x1b\x5b\x41' DOWN = '\x1b\x5b\x42' ENTER = '\x0d' #Checks if there is at least one eelement in the list. if len(optionList) == 0 : return EMPTY_OPTION_LIST #Cursor position is an integer initially at the first element cursor = 0; clearScreen() #This is the loop that prints the menu while True: print( message ) current = 0; for item in optionList: if cursor == current: print('> ' + item) else: print(item) current += 1 key = readchar.readkey() if key == 'a': break if key == UP: cursor = cursor-1 if cursor > 1 else 0 if key == DOWN: cursor = cursor+1 if cursor < len(optionList)-1 else cursor if key == ENTER: clearScreen() # print('Selected: ' + str(optionList[cursor])) return cursor, optionList[cursor] clearScreen()
def run(self): while True: self.draw_main_page() if self.test_mode: self.mainwin.close() logging.info("Test finished. Bye bye") break pressed_key = readchar.readkey() if pressed_key not in COMMANDS: logging.warn("key %s can not be recognized" % repr(pressed_key)) continue # else cmd = COMMANDS[pressed_key] if cmd == 'ABORT': self.mainwin.close() raise KeyboardInterrupt elif cmd == 'QUIT': self.mainwin.close() logging.info("Bye bye") break elif cmd == 'PREVIOUS': self.selected_list_idx -= 1 self.selected_list_idx %= self.list_num self.draw_main_page() elif cmd == 'NEXT': self.selected_list_idx += 1 self.selected_list_idx %= self.list_num self.draw_main_page() elif cmd == 'CONFIRM': self.learn_wordlist() elif cmd == 'RELOAD': self.reload_wordbook() self.selected_list_idx = 0 self.draw_main_page()
def stock_search(): query = [] while 1: clear() print("Search by ticker: ", end="") print("".join(query), end="\n\n") if len(query): for result in search("".join(query)): print(search_result(result)) key = readchar.readkey() if key == "\r": # Enter break elif key == "\x7f": # Backspace try: query.pop(-1) except: pass else: query.append(key) return "".join(query)
def main(): # cursor pos cursor_x = 0 cursor_y = 0 last_cursor_x = 0 last_cursor_y = 0 temp = ' ' BRUSH = u"\u2588" # woop while True: os.system('cls') temp = CANVAS[cursor_y * WIDTH + cursor_x] plot(cursor_x, cursor_y, CURSOR) display_canvas() ch = readchar.readkey() # exit :) if ch == 'c': exit(0) if ch == 'p': BRUSH = u"\u2591" if ch == 'l': BRUSH = u"\u2592" if ch == 'm': BRUSH = u"\u2588" last_cursor_x = cursor_x last_cursor_y = cursor_y cursor_x, cursor_y = move_cursor(ch, cursor_x, cursor_y) plot(last_cursor_x, last_cursor_y, temp) if ch == ' ': plot(cursor_x, cursor_y, BRUSH)
def play(self, test_mode=True, shuffle=False): self.test_mode = test_mode self.shuffle = shuffle self.start() while True: pressed_key = readchar.readkey() if pressed_key not in COMMANDS: logging.warn("key '%s' can not be recognized" % repr(pressed_key)) continue # else cmd = COMMANDS[pressed_key] if cmd == 'ABORT': self.abort() elif cmd == 'QUIT': logging.info("quit current play") break elif cmd == 'PREVIOUS': self.previous() elif cmd == 'NEXT': self.next() elif cmd == 'REPEAT': self.start() elif cmd == 'TEST': self.test_mode = not self.test_mode if self.test_mode and self.header: self.next() logging.info("mode: %s" % self.get_mode()) self.refresh_page() elif cmd == 'SHUFFLE': self.shuffle = not self.shuffle logging.info("word order: %s" % self.get_order()) self.start()
def playable_game(): ticks = 0 cursor = [0, 0] board = new_board() for i in range(5): board = add_line_below(board) board = update_board(board) while True: if ticks % 20 == 0: board = add_line_below(board) board = remove_line_above(board) pressed_key = readchar.readkey() if (pressed_key == readchar.key.CTRL_C or pressed_key == readchar.key.CTRL_D): break cursor = move_cursor(pressed_key, cursor) swap(board, pressed_key, cursor) update_screen(board, cursor) ticks += 1
def talker(): pub = rospy.Publisher('pet_roomba300', Int8, queue_size=10) rospy.init_node('RoombaWASD', anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): key = readchar.readkey() key = key.lower() if key in ('wasd'): if key == 'w': # Forward pub.publish(1) elif key == 'a' # Left pub.publish(4) elif key == 'd' # Right pub.publish(5) elif key == 's' # stand still pub.publish(6) elif key == 'p': print "stop" break rate.sleep()
def main_menu(self, config: Config): self.__spacer(self.middle - 4) print(crayons.green("The Game of Frupal!".center(self.width))) print() print() print(crayons.yellow("(Press S) Start Game!".center(self.width))) print() print(crayons.yellow("(Press C) Configuration?".center(self.width))) print() print(crayons.yellow("(Press Q) Exit Game!".center(self.width))) self.__spacer(self.middle - 4) key = readchar.readkey() if key == 's' or key == '\n': return True if key == 'c': self.config_menu(config) return self.main_menu(config) if key == 'q' or key == '\033': return False else: return self.main_menu(config)
def select_square(self, target, i=0, j=0): os.system('cls') # if target == 1: # print("O turn") # else: # print("X turn") self.print_boad(i, j, target) while True: input_key = readchar.readkey() if input_key == " ": return [i, j] if not ("0" <= input_key <= "9"): continue input_num = int(input_key) if input_num == 9: input_key = input("finish?(y/n)") if input_key == "y": return -1, -1 else: continue if input_num == 6: j += 1 if input_num == 4: j -= 1 if input_num == 2: i += 1 if input_num == 8: i -= 1 if i < 0: i = 0 if self.boad_size <= i: i = self.boad_size - 1 if j < 0: j = 0 if self.boad_size <= j: j = self.boad_size - 1 os.system('cls') self.print_boad(i, j, target)
def select( options, deselected_prefix: str = '\033[1m[ ]\033[0m ', selected_prefix: str = '\033[1m[\033[32;1mx\033[0;1m]\033[0m ', selected_index: int = 0) -> int: """Select an option from a list. Args: options (List[str]): The options to select from. deselected_prefix (str, optional): Prefix for deselected option ([ ]). selected_prefix (str, optional): Prefix for selected option ([x]). selected_index (int, optional): The index to be selected at first. Returns: int: The index that has been selected. """ print('\n' * (len(options) - 1)) while 1: print(f'\033[{len(options) + 1}A') for i, option in enumerate(options): print('\033[K{}{}'.format( selected_prefix if i == selected_index else deselected_prefix, option)) keypress = readchar.readkey() if keypress == readchar.key.UP: if selected_index == 0: selected_index = len(options) - 1 else: selected_index -= 1 elif keypress == readchar.key.DOWN: if selected_index == len(options) - 1: selected_index = 0 else: selected_index += 1 elif keypress == None: print("Keypress = None type.") else: '''this will execute when ANY button is pressed other than the up or down arrow.''' break return selected_index
def talker(): pub = rospy.Publisher('pet_roomba3000', Int8, queue_size=10) rospy.init_node('RoombaWASD', anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): key = readchar.readkey() key = key.lower() if key in ('wasdujn'): if key == 'w': # Forward print "w" pub.publish(1) elif key == 'a': # Left print "a" pub.publish(4) elif key == 'd': # Right print "d" pub.publish(5) elif key == 's': # stand still print "s" pub.publish(6) elif key == 'u': print "u" driveMotorForwards() pub.publish(8) elif key == 'j': print "j" driveMotorBackwards() pub.publish(9) elif key == 'n': print "n" stopMotor() pub.publish(10) elif key == 'p': print "stop" break rate.sleep() GPIO.cleanup()
def toggle_solenoids(self): """ Open and close the water reward solenoids individually. """ print( "Press the left or right keys to open and close the corresponding solenoid." ) print("Press space key to stop.") left_open = False right_open = False while True: key = readchar.readkey() if key == LEFT_KEY: left_open = not left_open GPIO.output(self.spouts[Targets.LEFT].reward_pin, left_open) elif key == RIGHT_KEY: right_open = not right_open GPIO.output(self.spouts[Targets.RIGHT].reward_pin, right_open) elif key == EXIT: break
def change_input_speed(self, gtg): delay = gtg.configurations["input_delay"] self.change_input_speed_box.lines[len(self.change_input_speed_box.lines) - 1] = f"{delay}s". \ ljust(self.change_input_speed_box.width) self.change_input_speed_box.colour = gtg.colours.get_random_colour( gtg.rng, True) key = "" while key != "Enter" and key != "Escape": self.change_input_speed_box.print_box(gtg.scr) key = readchar.readkey() if key == "Up": delay += 0.0125 elif key == "Down": delay -= 0.0125 delay = delay.__round__(4) if delay < 0 or delay == 0.0: delay = 0 self.change_input_speed_box.lines[len(self.change_input_speed_box.lines) - 1] = f"{delay}s".\ ljust(self.change_input_speed_box.width) if key == "Enter": gtg.configurations["input_delay"] = delay
def toggle_spout_leds(self): """ Toggle the two target spout LEDs. """ print("Press the left or right keys to toggle the corresponding LED.") print("Press space key to stop.") left_on = False right_on = False while True: key = readchar.readkey() if key == LEFT_KEY: left_on = not left_on GPIO.output(self.spouts[Targets.LEFT].cue_pin, left_on) elif key == RIGHT_KEY: right_on = not right_on GPIO.output(self.spouts[Targets.RIGHT].cue_pin, right_on) elif key == EXIT: break if self._sync_signal: GPIO.output(self._sync_signal, left_on or right_on)
def loop_input(cast): mc = cast.media_controller actions = { readchar.key.UP: lambda: cast.volume_up(), readchar.key.DOWN: lambda: cast.volume_down(), readchar.key.RIGHT: lambda: [mc.update_status(), mc.seek(mc.status.current_time + 30)], readchar.key.LEFT: lambda: [mc.update_status(), mc.seek(mc.status.current_time - 30)], "p": lambda: mc.pause() if mc.status.player_is_playing else mc.play(), } while True: key = readchar.readkey() if key == readchar.key.CTRL_C or key == "q": mc.stop() break actions.get(key, lambda: None)()
def final_screen(self, playing: int): lose = list() lose.append("▓██ ██▓ ▒█████ █ ██ ██▓ ▒█████ ██████ ▓█████ ▐██▌ ") lose.append(" ▒██ ██▒▒██▒ ██▒ ██ ▓██▒ ▓██▒ ▒██▒ ██▒▒██ ▒ ▓█ ▀ ▐██▌ ") lose.append(" ▒██ ██░▒██░ ██▒▓██ ▒██░ ▒██░ ▒██░ ██▒░ ▓██▄ ▒███ ▐██▌ ") lose.append(" ░ ▐██▓░▒██ ██░▓▓█ ░██░ ▒██░ ▒██ ██░ ▒ ██▒▒▓█ ▄ ▓██▒ ") lose.append(" ░ ██▒▓░░ ████▓▒░▒▒█████▓ ░██████▒░ ████▓▒░▒██████▒▒░▒████▒ ▒▄▄ ") lose.append(" ██▒▒▒ ░ ▒░▒░▒░ ░▒▓▒ ▒ ▒ ░ ▒░▓ ░░ ▒░▒░▒░ ▒ ▒▓▒ ▒ ░░░ ▒░ ░ ░▀▀▒ ") lose.append(" ▓██ ░▒░ ░ ▒ ▒░ ░░▒░ ░ ░ ░ ░ ▒ ░ ░ ▒ ▒░ ░ ░▒ ░ ░ ░ ░ ░ ░ ░ ") lose.append(" ▒ ▒ ░░ ░ ░ ░ ▒ ░░░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ") lose.append(" ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ") lose.append(" ░ ░ ") win = list() win.append("▓██ ██▓ ▒█████ █ ██ █ █░ ██▓ ███▄ █ ▐██▌ ") win.append(" ▒██ ██▒▒██▒ ██▒ ██ ▓██▒ ▓█░ █ ░█░▓██▒ ██ ▀█ █ ▐██▌ ") win.append(" ▒██ ██░▒██░ ██▒▓██ ▒██░ ▒█░ █ ░█ ▒██▒▓██ ▀█ ██▒ ▐██▌ ") win.append(" ░ ▐██▓░▒██ ██░▓▓█ ░██░ ░█░ █ ░█ ░██░▓██▒ ▐▌██▒ ▓██▒ ") win.append(" ░ ██▒▓░░ ████▓▒░▒▒█████▓ ░░██▒██▓ ░██░▒██░ ▓██░ ▒▄▄ ") win.append(" ██▒▒▒ ░ ▒░▒░▒░ ░▒▓▒ ▒ ▒ ░ ▓░▒ ▒ ░▓ ░ ▒░ ▒ ▒ ░▀▀▒ ") win.append(" ▓██ ░▒░ ░ ▒ ▒░ ░░▒░ ░ ░ ▒ ░ ░ ▒ ░░ ░░ ░ ▒░ ░ ░ ") win.append(" ▒ ▒ ░░ ░ ░ ░ ▒ ░░░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ") win.append(" ░ ░ ░ ░ ░ ░ ░ ░ ░ ") win.append(" ░ ░ ") buffer = 0 if playing == 2: buffer = (self.height - len(lose)) // 2 if playing == 3: buffer = (self.height - len(win)) // 2 self.__spacer(buffer) if playing == 2: for line in lose: print(crayons.green(line.center(self.width))) if playing == 3: for line in win: print(crayons.green(line.center(self.width))) self.__spacer(buffer - 1) choice = readchar.readkey()
def read_input(self): while True: key = readchar.readkey() tv_page = self.current_page if key == readchar.key.CTRL_C: break elif key == readchar.key.LEFT: tv_page = self.pages[self.current_page]['prev'] self.input_buffer = '' elif key == readchar.key.RIGHT: tv_page = self.pages[self.current_page]['next'] self.input_buffer = '' elif key == readchar.key.BACKSPACE: self.input_buffer = self.input_buffer[:-1] elif key.isdigit(): if len(self.input_buffer) == 0 and key != '0' or \ len(self.input_buffer) > 0: self.input_buffer += key if len(self.input_buffer) == 3: tv_page = self.input_buffer self.input_buffer = '' self.display(tv_page)
def yn(*prompt, default=True): """ Prompts the user to answer a yes/no question. Args: *prompt: List of arguments that form a prompt. Passed on to `print`. default (bool): Yes or no when the user hits enter? Returns: (bool) The user's choice. Raises: `KeyboardInterrupt` when the user has pressed Ctrl+C """ if default: options = " [Y/n]? " else: options = " [y/N]? " accept = "yYjJ" reject = "nN\x1b\x07" # Esc, ^G default_keys = " \r" # Space, Return print(*prompt, end=options, flush=True) while True: inp = readkey() key = inp[0] if inp else default_keys[0] if key in accept or default and key in default_keys: print(accept[0]) return True elif key in reject or not default and key in default_keys: print(reject[0]) return False elif key == "\x03": # ^C raise KeyboardInterrupt() else: print(key, "\x08", sep="", end="", flush=True)
step_idx[axis] = (step_idx[axis] - 1) % len(STEPS) sleep(0.001) try: for gpio in MOTOR_X + MOTOR_Y: RPIO.setup(gpio, RPIO.OUT, initial=RPIO.LOW) for gpio in ENDSTOPS: RPIO.setup(gpio, RPIO.IN, pull_up_down=RPIO.PUD_DOWN) RPIO.add_interrupt_callback(gpio, endstop_hit, pull_up_down=RPIO.PUD_DOWN, debounce_timeout_ms=10, threaded_callback=True) RPIO.wait_for_interrupts(threaded=True) while(True): k = readchar.readkey() if k == '\x03': break elif k == readchar.key.UP: for i in range(0,8*100): step(Y,UP) elif k == readchar.key.DOWN: for i in range(0,8*100): step(Y,DOWN) elif k == readchar.key.LEFT: for i in range(0,8*100): step(X,LEFT) elif k == readchar.key.RIGHT: for i in range(0,8*100): step(X,RIGHT) # else:
def get_key_stroke(): return readchar.readkey()
# how to install readchar, pip install readchar import readchar print("Reading a char:") print(repr(readchar.readchar())) print("Reading a key:") print(repr(readchar.readkey()))
gpio.setwarnings(False) gpio.setmode(gpio.BOARD) gpio.setup(35, gpio.OUT) gpio.setup(36, gpio.OUT) gpio.setup(37, gpio.OUT) gpio.setup(38, gpio.OUT) try: while True: gpio.output(35, 1) gpio.output(36, 1) gpio.output(37, 1) gpio.output(38, 1) input = readchar.readkey(); if input == '\x1b[D': #left gpio.output(35, 1) gpio.output(36, 0) gpio.output(37, 0) gpio.output(38, 1) time.sleep(1) if input == '\x1b[C': #right gpio.output(35, 0) gpio.output(36, 1) gpio.output(37, 1) gpio.output(38, 0) time.sleep(1)
def process_secv(s): if secv == 'bye': power_off() elif secv == 'time': for w in strftime("%I %M %p", localtime()).split(" "): show_word(w) else: show_word(s) if __name__ == "__main__": set_trigger() secv = "" print("Started") if MODE == "local": while True: key = readkey() if ord(key) == 13: process_secv(secv) secv = "" else: if show_letter(key) == 0: secv = secv + key else: dev = InputDevice('/dev/input/event0') if DEBUG: print(dev) for event in dev.read_loop(): if event.type == ecodes.EV_KEY: c = categorize(event) if c.keystate == c.key_down: if event.code == ecodes.ecodes['KEY_ENTER']:
def read_keys(): SHUTDOWN = False while not SHUTDOWN: if USE_READCHAR: # get the next pressed character # This is a blocking call pressed_key = readchar.readkey() #long link commands if pressed_key == 'q': print('long link forward rotation') if pressed_key == 'a': print('long link backward rotation') #short link commmands if pressed_key == 'w': print('short link forward rotation') if pressed_key == 's': print('short link backward rotation') # gripper commands if pressed_key == 'e': print('gripper forward rotation') if pressed_key == 'd': print('gripper backward rotation') if pressed_key == 'f': print('Shutting down...') SHUTDOWN = True else: # Use pygame for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: print('long link forward rotation') if event.key == pygame.K_a: print('long link backward rotation') if event.key == pygame.K_w: print('short link forward rotation') if event.key == pygame.K_s: print('short link backward rotation') if event.key == pygame.K_e: print('gripper forward rotation') if event.key == pygame.K_d: print('gripper backward rotation') if event.key == pygame.K_f: print('Shutting down...') SHUTDOWN = True clock.tick(60) # 60 fps
def test_basic_character(self): getchar_fn = readchar_fn_factory('a') result = readkey(getchar_fn) self.assertEqual('a', result)
def input_thread(my_queue): while True: x = readchar.readkey() if x in ['q', u'\x03']: # q or ctl c my_queue.append('q') break
for l in ls: scorekeeper[l] = 0 comb = combinations(ls, 2) num_comb = len(list(comb)) clear_screen() print("") print("") print("You will do", num_comb, "comparisons"); print("Estimated time to complete:", num_comb*3, "seconds"); print("") print("") print("Press any key to continue or Ctrl+C to quit.") readchar.readkey(); clear_screen() comb_ls = list(combinations(ls,2)) random.shuffle(comb_ls) for c in comb_ls: print(c) a = 2 while a != 'q' and a != 'p': a = readchar.readkey(); print(a); if a == 'q': scorekeeper[c[0]] += 1; else:
def get_current_command(cls): return cls.KEY_MAPPINGS.get(readchar.readkey(), None)
for i in range(1, len(hashstr))][:16]) passwd = calculate_password(input("Alias: "), getpass(prompt="Secret: ")) if ask("Copy to clipboard?", default="no"): try: import pyperclip pyperclip.copy(passwd) print("The password is now in your clipboard. Be careful!") except ImportError: print("Module pyperclip not found. Try running 'pip install pyperclip'.") if ask("Show password?", default="no"): prepwd = "Password: "******" "*4 try: from readchar import readkey print("Pressing any key will hide your password.") print(prepwd + passwd, end="\r") readkey() print(prepwd + " "*4 + len(passwd)*"*") except ImportError: print("Module readchar not found. Try running 'pip install readchar'.") ask("Secrets cannot be removed. Continue?", default="yes") print(prepwd + passwd)
def test_string_instead_of_char(self): char = 'a' getchar_fn = readchar_fn_factory(char + 'bcde') result = readkey(getchar_fn) self.assertEqual(char, result)