Python pynput.keyboard.Listener() Examples

The following are 24 code examples of pynput.keyboard.Listener(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pynput.keyboard , or try the search function .
Example #1
Source File: telloCV.py    From telloCV with Apache License 2.0 7 votes vote down vote up
def init_controls(self):
        """Define keys and add listener"""
        self.controls = {
            'w': 'forward',
            's': 'backward',
            'a': 'left',
            'd': 'right',
            'Key.space': 'up',
            'Key.shift': 'down',
            'Key.shift_r': 'down',
            'q': 'counter_clockwise',
            'e': 'clockwise',
            'i': lambda speed: self.drone.flip_forward(),
            'k': lambda speed: self.drone.flip_back(),
            'j': lambda speed: self.drone.flip_left(),
            'l': lambda speed: self.drone.flip_right(),
            # arrow keys for fast turns and altitude adjustments
            'Key.left': lambda speed: self.drone.counter_clockwise(speed),
            'Key.right': lambda speed: self.drone.clockwise(speed),
            'Key.up': lambda speed: self.drone.up(speed),
            'Key.down': lambda speed: self.drone.down(speed),
            'Key.tab': lambda speed: self.drone.takeoff(),
            'Key.backspace': lambda speed: self.drone.land(),
            'p': lambda speed: self.palm_land(speed),
            't': lambda speed: self.toggle_tracking(speed),
            'r': lambda speed: self.toggle_recording(speed),
            'z': lambda speed: self.toggle_zoom(speed),
            'Key.enter': lambda speed: self.take_picture(speed)
        }
        self.key_listener = keyboard.Listener(on_press=self.on_press,
                                              on_release=self.on_release)
        self.key_listener.start()
        # self.key_listener.join() 
Example #2
Source File: test.py    From kinto with GNU General Public License v2.0 6 votes vote down vote up
def mac_keys_gui():
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Command" + color.END + " key to confirm the new keymapping to Ctrl..")
    with Listener(
        # on_press=on_press,
        on_release=is_ctrl_mac) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Alt" + color.END + " key to confirm it remains Alt..")
    with Listener(
        # on_press=on_press,
        on_release=is_alt_mac) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Ctrl" + color.END + " key to confirm the new keymapping to Win/Super..")
    with Listener(
        # on_press=on_press,
        on_release=is_super_winmac) as listener:
            listener.join() 
Example #3
Source File: test.py    From kinto with GNU General Public License v2.0 6 votes vote down vote up
def windows_keys_terminal():
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Alt" + color.END + " key to confirm the new keymapping to Super/Win..")
    with Listener(
        # on_press=on_press,
        on_release=is_super_terminal) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Win/Super" + color.END + " key to confirm the new keymapping to Alt..")
    with Listener(
        # on_press=on_press,
        on_release=is_alt_windows) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Ctrl" + color.END + " key to confirm the new keymapping to Ctrl..")
    with Listener(
        # on_press=on_press,
        on_release=is_ctrl_terminal) as listener:
            listener.join() 
Example #4
Source File: test.py    From kinto with GNU General Public License v2.0 6 votes vote down vote up
def windows_keys_gui():
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Alt" + color.END + " key to confirm the new keymapping to Ctrl..")
    with Listener(
        # on_press=on_press,
        on_release=is_ctrl_winchrome) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Win/Super" + color.END + " key to confirm the new keymapping to Alt..")
    with Listener(
        # on_press=on_press,
        on_release=is_alt_windows) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Ctrl" + color.END + " key to confirm the new keymapping to Win/Super..")
    with Listener(
        # on_press=on_press,
        on_release=is_super_winmac) as listener:
            listener.join() 
Example #5
Source File: test.py    From kinto with GNU General Public License v2.0 6 votes vote down vote up
def chromebook_keys_terminal():
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Alt" + color.END + " key to confirm the new keymapping to Super/Win..")
    with Listener(
        # on_press=on_press,
        on_release=is_super_terminal) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Ctrl" + color.END + " key to confirm the new keymapping to Ctrl..")
    with Listener(
        # on_press=on_press,
        on_release=is_ctrl_terminal) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Search" + color.END + " key to confirm the new keymapping to Alt..")
    with Listener(
        # on_press=on_press,
        on_release=is_alt_chromebook_terminal) as listener:
            listener.join() 
Example #6
Source File: test.py    From kinto with GNU General Public License v2.0 6 votes vote down vote up
def chromebook_keys_gui():
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Alt" + color.END + " key to confirm the new keymapping to Ctrl..")
    with Listener(
        # on_press=on_press,
        on_release=is_ctrl_winchrome) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Ctrl" + color.END + " key to confirm the new keymapping to Alt..")
    with Listener(
        # on_press=on_press,
        on_release=is_alt_chromebook) as listener:
            listener.join()
    print()
    print(color.UNDERLINE + color.YELLOW + "Press the physical Search" + color.END + " key to confirm the new keymapping to Super/Win..")
    with Listener(
        # on_press=on_press,
        on_release=is_super_chromebook) as listener:
            listener.join() 
Example #7
Source File: switch-layout.py    From switch-layout with MIT License 6 votes vote down vote up
def main():
    switcher = Switcher()

    with keyboard.Listener(
            on_press=switcher.on_press,
            on_release=switcher.on_release) as listener:
        listener.join() 
Example #8
Source File: demo_client.py    From ZASR_tensorflow with Apache License 2.0 6 votes vote down vote up
def main():
    # prepare audio recorder
    p = pyaudio.PyAudio()
    stream = p.open(
        format=pyaudio.paInt16,
        channels=1,
        rate=16000,
        input=True,
        stream_callback=callback)
    stream.start_stream()

    # prepare keyboard listener
    with keyboard.Listener(
            on_press=on_press, on_release=on_release) as listener:
        listener.join()

    # close up
    stream.stop_stream()
    stream.close()
    p.terminate() 
Example #9
Source File: tello_openpose.py    From tello-openpose with MIT License 5 votes vote down vote up
def log_data_handler(self, event, sender, data):
        """
            Listener to log data from the drone.
        """  
        pos_x = -data.mvo.pos_x
        pos_y = -data.mvo.pos_y
        pos_z = -data.mvo.pos_z
        if abs(pos_x)+abs(pos_y)+abs(pos_z) > 0.07:
            if self.ref_pos_x == -1: # First time we have meaningful values, we store them as reference
                self.ref_pos_x = pos_x
                self.ref_pos_y = pos_y
                self.ref_pos_z = pos_z
            else:
                self.pos_x = pos_x - self.ref_pos_x
                self.pos_y = pos_y - self.ref_pos_y
                self.pos_z = pos_z - self.ref_pos_z
        
        qx = data.imu.q1
        qy = data.imu.q2
        qz = data.imu.q3
        qw = data.imu.q0
        self.yaw = quat_to_yaw_deg(qx,qy,qz,qw)
        
        if self.write_log_data:
            if self.write_header:
                self.log_file.write('%s\n' % data.format_cvs_header())
                self.write_header = False
            self.log_file.write('%s\n' % data.format_cvs()) 
Example #10
Source File: telloCV.py    From telloCV with Apache License 2.0 5 votes vote down vote up
def flight_data_handler(self, event, sender, data):
        """Listener to flight data from the drone."""
        text = str(data)
        if self.prev_flight_data != text:
            self.prev_flight_data = text 
Example #11
Source File: main.py    From SupervisedChromeTrex with MIT License 5 votes vote down vote up
def listen():
    listener = keyboard.Listener(on_press = on_press,
                                 on_release = on_release)
    listener.start() 
Example #12
Source File: clix.py    From clix with MIT License 5 votes vote down vote up
def run(self):
        with keyboard.Listener(
                on_press=self.on_press,
                ) as listener:
            listener.join() 
Example #13
Source File: mapper.py    From guiscrcpy with GNU General Public License v3.0 5 votes vote down vote up
def listen_keypress(key_a):
    print(
        "[SERVER] LISTENING VALUES: Your keys are being listened by server. ")
    print(key_a)

    def on_press0(key):
        try:
            if key.char in key_a.keys():
                print(key.char)
                print("running cmd")
                finalpos0 = key_a[key.char]
                c = adb.command(
                    adb.path,
                    'shell input tap {} {}'.format(*finalpos0),
                    device_id=mapper_device_id
                )
                print(c.stdout.read().decode('utf-8'))
                print("COMPLETED")
        except AttributeError as e:
            print("E: {}".format(e))

    with keyboard.Listener(on_press=on_press0) as listener:
        listener.join()

        # ...or, in a non-blocking fashion:
    listener = keyboard.Listener(on_press=on_press0)
    listener.start() 
Example #14
Source File: main-punput-1.py    From python-examples with MIT License 5 votes vote down vote up
def wait_for_user_input():
    listener = keyboard.Listener(on_press=on_press, on_release=on_release)
    listener.start()
    listener.join() # wait for listener stop 
Example #15
Source File: main-punput-2.py    From python-examples with MIT License 5 votes vote down vote up
def wait_for_user_input():
    listener = keyboard.Listener(on_press=on_press, on_release=on_release)
    listener.start()
    listener.join() # wait till listener stops

    if key_pressed == 'c':    
        # do something
    elif key_pressed == "v":
        # do something else
    elif key_pressed == keyboard.Key.esc:
        print('You pressed ESC') 
Example #16
Source File: cozmo_voice_commands.py    From Cozmo-Voice-Commands with GNU General Public License v3.0 5 votes vote down vote up
def run(robot: cozmo.robot.Robot):
    '''The run method runs once the Cozmo SDK is connected.'''
    global vc

    vc = voice_commands.VoiceCommands(robot,log)

    def on_press(key):
        #print('{0} pressed'.format(key))
        if key == Key.shift_l or key == Key.shift_r:
            listen(robot)

    def on_release(key):
        #print('{0} release'.format(key))
        if key == Key.shift_l or key == Key.shift_r:
            #listen(robot)
            pass

    if robot:
        vc.check_charger(robot)
        robot.play_anim("anim_cozmosays_getout_short_01")

    try:
        load_jsons()
        set_language()
        set_data()
        printSupportedCommands()
        prompt()

        if wait_for_shift:
            with Listener(on_press=on_press, on_release=on_release) as listener:
                listener.join()
        else:
            while 1:
                listen(robot)

    except KeyboardInterrupt:
        print("")
        cprint("Exit requested by user", "yellow") 
Example #17
Source File: control.py    From atbswp with GNU General Public License v3.0 5 votes vote down vote up
def action(self, event):
        """Triggered when the recording button is clicked on the GUI."""
        listener_mouse = mouse.Listener(
            on_move=self.on_move,
            on_click=self.on_click,
            on_scroll=self.on_scroll)
        listener_keyboard = keyboard.Listener(
            on_press=self.on_press,
            on_release=self.on_release)

        if event.GetEventObject().GetValue():
            listener_keyboard.start()
            listener_mouse.start()
            self.last_time = time.perf_counter()
            self.recording = True
            recording_state = wx.Icon(os.path.join(self.path, "img", "icon-recording.png"))
        else:
            self.recording = False
            with open(TMP_PATH, 'w') as f:
                # Remove the recording trigger event
                self._capture.pop()
                # If it's the mouse remove the previous also
                if "mouseDown" in self._capture[-1]:
                    self._capture.pop()
                f.seek(0)
                f.write("\n".join(self._capture))
                f.truncate()
            self._capture = [self._header]
            recording_state = wx.Icon(os.path.join(self.path, "img", "icon.png"))
        event.GetEventObject().GetParent().taskbar.SetIcon(recording_state) 
Example #18
Source File: controller.py    From terminal_dungeon with MIT License 5 votes vote down vote up
def __init__(self, renderer):
        self.player = renderer.player
        self.renderer = renderer
        signal.signal(signal.SIGWINCH, self.resize) # Our solution to curses resize bug
        self.listener = keyboard.Listener(on_press=self.pressed,
                                          on_release=self.released)
        self.listener.start() 
Example #19
Source File: workers.py    From TensorMouse with MIT License 5 votes vote down vote up
def key_listener():
    """ Ket listener thread """
    from pynput.keyboard import Listener
    return Listener(on_press=keypress_listener, on_release=keyrelease_listener) 
Example #20
Source File: keylogger.py    From vault with MIT License 5 votes vote down vote up
def start_keylogger(self):
        try:
            self.t1 = time.time()

            colors.info("Capturing keystrokes...")

            with Listener(on_press=self.log_keypress) as listener:
                listener.join()

        except KeyboardInterrupt:
            colors.success('Stopping keylogger...') 
Example #21
Source File: keylogger.py    From Loki with MIT License 5 votes vote down vote up
def _start(self):
        with Listener(on_press=self.on_press, on_release=self.on_release) as self.listener:
            self.listener.join() 
Example #22
Source File: create_dataset.py    From Game-Bot with Apache License 2.0 5 votes vote down vote up
def listen_keyboard():
    data_path = 'Data/Train_Data/Keyboard'
    if not os.path.exists(data_path):
        os.makedirs(data_path)

    def on_press(key):
        save_event_keyboard(data_path, 1, key)

    def on_release(key):
        save_event_keyboard(data_path, 2, key)

    with key_listener(on_press=on_press, on_release=on_release) as listener:
        listener.join() 
Example #23
Source File: tello_openpose.py    From tello-openpose with MIT License 5 votes vote down vote up
def flight_data_handler(self, event, sender, data):
        """
            Listener to flight data from the drone.
        """
        self.battery = data.battery_percentage
        self.fly_mode = data.fly_mode
        self.throw_fly_timer = data.throw_fly_timer
        self.throw_ongoing = data.throw_fly_timer > 0

        # print("fly_mode",data.fly_mode)
        # print("throw_fly_timer",data.throw_fly_timer)
        # print("em_ground",data.em_ground)
        # print("em_sky",data.em_sky)
        # print("electrical_machinery_state",data.electrical_machinery_state)
        #print("em_sky",data.em_sky,"em_ground",data.em_ground,"em_open",data.em_open)
        #print("height",data.height,"imu_state",data.imu_state,"down_visual_state",data.down_visual_state)
        if self.is_flying != data.em_sky:            
            self.is_flying = data.em_sky
            log.debug(f"FLYING : {self.is_flying}")
            if not self.is_flying:
                self.reset()
            else:
                if self.tracking_after_takeoff:
                    log.info("Tracking on after takeoff")
                    self.toggle_tracking(True)
                    
        log.debug(f"MODE: {self.fly_mode} - Throw fly timer: {self.throw_fly_timer}") 
Example #24
Source File: run_atari.py    From DRL_DeliveryDuel with MIT License 4 votes vote down vote up
def main():
    global abort_training
    global q_pressed
    
    abort_training = False
    q_pressed = False
    
    listener = keyboard.Listener(on_press=on_press, on_release=on_release)
    listener.start()
    
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID', default='BreakoutNoFrameskip-v4')
    parser.add_argument('--seed', help='RNG seed', type=int, default=0)
    parser.add_argument('--prioritized', type=int, default=1)
    parser.add_argument('--dueling', type=int, default=1)
    parser.add_argument('--num-timesteps', type=int, default=int(10e6))
    args = parser.parse_args()
    logger.configure()
    set_global_seeds(args.seed)
    env = make_atari(args.env)
    env = bench.Monitor(env, logger.get_dir())
    env = deepq.wrap_atari_dqn(env)
    model = deepq.models.cnn_to_mlp(
        convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)],
        hiddens=[256],
        dueling=bool(args.dueling),
    )
    act = deepq.learn(
        env,
        q_func=model,
        lr=1e-4,
        max_timesteps=args.num_timesteps,
        buffer_size=10000,
        exploration_fraction=0.1,
        exploration_final_eps=0.01,
        train_freq=4,
        learning_starts=10000,
        target_network_update_freq=1000,
        gamma=0.99,
        print_freq=1,
        prioritized_replay=bool(args.prioritized),
        callback=callback
    )    
    print("Saving model to pong_model.pkl")
    act.save("pong_model.pkl")
    env.close()