Library to easily read single chars and keystrokes.
Born as a python-inquirer requirement.
simply install it via pip:
pip install readcharOr download the source code from PyPi.
Simply read a character or keystroke:
import readchar
key = readchar.readkey()React to different kinds of keypresses:
from readchar import readkey, key
while True:
k = readkey()
if k == "a":
# do stuff
if k == key.DOWN:
# do stuff
if k == key.ENTER:
breakThere are just two methods:
Reads one character from stdin, returning it as a string with length 1. Waits until a character is available.
As only ASCII characters are actually a single character, you usually want to use the next function, that also handles longer keys.
Reads the next keystroke from stdin, returning it as a string. Waits until a keystroke is available.
A keystroke can be:
- single characters as returned by
readchar(). These include:- character for normal keys: 'a', 'Z', '9',...
- special characters like 'ENTER', 'BACKSPACE', 'TAB',...
- combinations with 'CTRL': 'CTRL'+'A',...
- keys that are made up of multiple characters:
- characters for cursors/arrows: 🡩, 🡪, 🡫, 🡨
- navigation keys: 'INSERT', 'HOME',...
- function keys: 'F1' to 'F12'
- combinations with 'ALT': 'ALT'+'A',...
- combinations with 'CTRL' and 'ALT': 'CTRL'+'ALT'+'SUPR',...
Attention!
'CTRL'+'C' will not be returned by readkey(), but instead raise a KeyboardInterupt. If you what to handle it yourself,
use readchar().
This submodule contains a list of available keys to compare against. The constants are defined depending on your operating system, so it should be
fully portable. If a key is listed here for your platform, readkey() can read it, and you can compare against it.
This library actively supports these operating systems:
- Linux
- Windows
Some operating systems are enabled, but not actively tested or supported:
- macOS
- FreeBSD
Theoretically every Unix based system should work, but they will not be actively tested. It is also required that somebody provides initial test results before the OS is enabled and added to the list. Feel free to open a PR for that.
Thank you!
You have an issue problem or found a bug? You have a great new idea or just want to fix a typo? Great 👍. We are happy to accept your issue or pull request, but first, please read our contribution guidelines. They will also tell you how to write code for this repo and how to properly prepare an issue or a pull request.
Copyright (c) 2014-2022 Miguel Ángel García