You're Reading a Free Preview 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 File: test_readkey.py Project: wuwx/simba def test_special_combo_character(self): char = '\x1b\x01' getchar_fn = readchar_fn_factory(char + 'foo') result = readkey(getchar_fn) self.assertEqual(char, result) File: test_readkey.py Project: wuwx/simba 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) File: pytimer.py Project: GjjvdBurg/PyTimer def start(self): self.switch() self.loop_printer.run() while True: k = readchar.readkey() if k == ' ': self.switch() if k == 'q': raise SystemExit File: drive_spark.py Project: CoroBot/Spark_Firmware 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) File: kcontrol.py Project: vb0/korad 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 File: sshmenu.py Project: RealJTG/sshmenu 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 File: py.py Project: JoinRajuncraftNow/Projects 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() File: console.py Project: eerimoq/simba 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 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() File: motorcontrol.py Project: ahmedak/caw 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 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 File: readkeys.py Project: amitesh-singh/algorithms # 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())) File: gimbal.py Project: jabbrwcky/picam-gimbal 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: File: morsepi_pleasefixit.py Project: slaash/scripts 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']: File: test_readkey.py Project: wuwx/simba def test_basic_character(self): getchar_fn = readchar_fn_factory('a') result = readkey(getchar_fn) self.assertEqual('a', result) File: paspy.py Project: R13N/paspy 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) File: pairwise.py Project: mjeung/mjeung-sandbox 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: File: test_readkey.py Project: wuwx/simba def test_string_instead_of_char(self): char = 'a' getchar_fn = readchar_fn_factory(char + 'bcde') result = readkey(getchar_fn) self.assertEqual(char, result) |