Cross platform keyboard input

I couldn’t find a cross platform library for keyboard input that doesn’t also need special priviliges:

  • curses: doesn’t work on Windows and emposes arbitrary restrictions on output
  • pip install keyboard: requires root on macOS, can’t be included with your code and acts like a keylogger on Windows
  • pip install pynput: not trusted on macOS and can’t be included with your code

So, I wrote my own, AnsI/O, providing a low-level interface for input & output. Whenever the program is terminated or suspended (Unix only), it restores the terminal back to the default settings.

But because it’s so early, I’m currently looking for feedback.

Example usage

Keyboard input

from ansio import application_keypad, mouse_input, raw_input
from ansio.input import InputEvent, get_input_event

with raw_input, application_keypad, mouse_input:
    while True:
        event: InputEvent = get_input_event()
        print(event.pressed, repr(event.shortcut))

Example output:

True 'alt+shift+a'
True 'ctrl+a'
True 'tab'
True 'shift+up'
True 'a'
True 'primary_click'
False 'primary_click'
True 'ctrl+primary_click'
False 'ctrl+primary_click'

Colored output

from ansio import colored_output
from ansio.colors import blue_bg, invert, italic, yellow

with colored_output:
    print(f'Print in {yellow(blue_bg("color"))} and with {italic(invert("styles"))}')

Example output:

colored_output

2 Likes

Nice work. I like a simple, well thought out pure Python library.

It’s fairly large, but does PyGame require root, trust, or impose restrictions etc.?
https://www.pygame.org/docs/ref/key.html

  1. It can’t be included with my code (must be installed because it’s partially written in C).
  2. It must be used without a window (not in the command line)
1 Like