tutorial pynput instalar python keylistener

pynput - ¿Oyentes clave en python?



pynput tutorial (6)

teclado

Toma el control total de tu teclado con esta pequeña biblioteca de Python. Enganche eventos globales, registre teclas de acceso rápido, simule pulsaciones de teclas y mucho más.

Evento global enganchado en todos los teclados (captura las teclas independientemente del enfoque). Escucha y envía eventos de teclado. Funciona con Windows y Linux (requiere sudo), con soporte experimental de OS X (gracias @glitchassassin!). Pure Python, no hay módulos C para compilar. Cero dependencias. Trivial para instalar y desplegar, simplemente copie los archivos. Python 2 y 3. Compatibilidad con teclas de acceso rápido complejas (por ejemplo, Ctrl + Shift + M, Ctrl + Space) con tiempo de espera controlable. Incluye API de alto nivel (por ejemplo, grabar y reproducir, add_abbreviation). Asigna las claves tal como están realmente en tu diseño, con total compatibilidad con la internacionalización (por ejemplo, Ctrl + ç). Los eventos capturados automáticamente en un hilo separado, no bloquean el programa principal. Probado y documentado. No rompe las teclas muertas acentuadas (te estoy mirando, pyHook). Soporte de mouse disponible a través del mouse del proyecto (pip install mouse).

De README.md :

import keyboard keyboard.press_and_release(''shift+s, space'') keyboard.write(''The quick brown fox jumps over the lazy dog.'') # Press PAGE UP then PAGE DOWN to type "foobar". keyboard.add_hotkey(''page up, page down'', lambda: keyboard.write(''foobar'')) # Blocks until you press esc. keyboard.wait(''esc'') # Record events until ''esc'' is pressed. recorded = keyboard.record(until=''esc'') # Then replay back at three times the speed. keyboard.play(recorded, speed_factor=3) # Type @@ then press space to replace with abbreviation. keyboard.add_abbreviation(''@@'', ''[email protected]'') # Block forever. keyboard.wait()

¿Hay una manera de hacer escuchas clave en python sin un módulo hinchado tan pygame como pygame ?

Un ejemplo sería, cuando presioné la tecla a que se imprimiría en la consola

La tecla a fue presionada!

También debe escuchar las teclas de flecha / barra espaciadora / tecla de cambio.


Aquí está cómo hacerlo en Windows:

""" Display series of numbers in infinite loop Listen to key "s" to stop Only works on Windows because listening to keys is platform dependent """ # msvcrt is a windows specific native module import msvcrt import time # asks whether a key has been acquired def kbfunc(): #this is boolean for whether the keyboard has bene hit x = msvcrt.kbhit() if x: #getch acquires the character encoded in binary ASCII ret = msvcrt.getch() else: ret = False return ret #begin the counter number = 1 #infinite loop while True: #acquire the keyboard hit if exists x = kbfunc() #if we got a keyboard hit if x != False and x.decode() == ''s'': #we got the key! #because x is a binary, we need to decode to string #use the decode() which is part of the binary object #by default, decodes via utf8 #concatenation auto adds a space in between print ("STOPPING, KEY:", x.decode()) #break loop break else: #prints the number print (number) #increment, there''s no ++ in python number += 1 #wait half a second time.sleep(0.5)


Aunque me gusta usar el módulo de teclado para capturar eventos de teclado, no me gusta su función de record() porque devuelve una matriz como [KeyboardEvent("A"), KeyboardEvent("~")] , que me parece un poco difícil leer. Entonces, para grabar eventos de teclado, me gusta usar el módulo de teclado y el módulo de subprocesamiento simultáneamente, como esto:

import keyboard import string from threading import * # I can''t find a complete list of keyboard keys, so this will have to do: keys = list(string.ascii_lowercase) """ Optional code(extra keys): keys.append("space_bar") keys.append("backspace") keys.append("shift") keys.append("esc") """ def listen(key): while True: keyboard.wait(key) print("[+] Pressed",key) threads = [Thread(target=listen, kwargs={"key":key}) for key in keys] for thread in threads: thread.start()


Estaba buscando una solución simple sin ventana de enfoque. La respuesta de Jayk, pynput, funciona perfectamente para mí. Aquí está el ejemplo de cómo lo uso.

from pynput import keyboard def on_press(key): try: k = key.char # single-char keys except: k = key.name # other keys if key == keyboard.Key.esc: return False # stop listener if k in [''1'', ''2'', ''left'', ''right'']: # keys interested # self.keys.append(k) # store it in global-like variable print(''Key pressed: '' + k) return False # remove this if want more keys lis = keyboard.Listener(on_press=on_press) lis.start() # start to listen on a separate thread lis.join() # no this if main thread is polling self.keys


Hay una manera de hacer oyentes clave en python. Esta funcionalidad está disponible a través de pynput .

Línea de comando:

> pip install pynput

Código Python:

from pynput import ket,listener # your code here


Lamentablemente no es tan fácil hacer eso. Si está tratando de hacer algún tipo de interfaz de usuario de texto, es posible que desee ver en curses . Si quieres mostrar cosas como lo harías normalmente en una terminal, pero quieres una entrada así, entonces tendrás que trabajar con termios , que desafortunadamente parece estar mal documentado en Python. Sin embargo, ninguna de estas opciones es tan simple, desafortunadamente. Además, no funcionan bajo Windows; Si necesita que funcionen en Windows, tendrá que usar PDCurses como reemplazo de curses o pywin32 lugar de termios .

Pude conseguir que esto funcione decentemente. Imprime la representación hexadecimal de las teclas que escribe. Como dije en los comentarios de tu pregunta, las flechas son difíciles; Creo que estarás de acuerdo.

#!/usr/bin/env python import sys import termios import contextlib @contextlib.contextmanager def raw_mode(file): old_attrs = termios.tcgetattr(file.fileno()) new_attrs = old_attrs[:] new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON) try: termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs) yield finally: termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs) def main(): print ''exit with ^C or ^D'' with raw_mode(sys.stdin): try: while True: ch = sys.stdin.read(1) if not ch or ch == chr(4): break print ''%02x'' % ord(ch), except (KeyboardInterrupt, EOFError): pass if __name__ == ''__main__'': main()