magmax / python-readchar

Python library to read characters and key strokes
MIT License
143 stars 43 forks source link

Contexmanager #96

Open Cube707 opened 1 year ago

Cube707 commented 1 year ago

This implements and closes #92.

The new contextmanager can be used to ensure consisten terminal-behavior while inside the context, even when outside of readchar functions. This allows for fully non-blocking and timing independent usage.

Cube707 commented 1 year ago
Cube707 commented 1 year ago

Here ist a example of how this can be used:

from readchar import ReadChar
from time import sleep

# construct an inverted code -> key-name mapping
# we need to revese the items so that aliases won't overrive the original name later on
known_keys = {v: k for k, v in reversed(vars(key).items()) if not k.startswith("__")}

with ReadChar() as read:
    while True:
        if read.key_waiting:
            c = read.key()

            if c in known_keys:
                print(known_keys[c])
            else:
                print(c)

        sleep(0.5)
Cube707 commented 1 year ago

This should be working now.

@Eboubaker, @petereon as you work with this new feature befor, it would be great to get some testing/feedback from you. Use the code snippet above (or whatever else comes to mind, it also needs to be usabel witout example 😆). The class is also now public inside __init__.py

Cube707 commented 1 year ago

out now as pre-release