After discussing this issue on github with the creator of the project - magmax (here), I understood that readchar package works only if you try to run it from a terminal but not from any IDE or other non terminal executions. The error is caused because it tries to get the terminal settings which is non existent in this case.

I have been trying to run it from an Wing IDE. The program works great if you try to run it from a terminal.

P.S: magmax suggested to use readchar.keys.ENTER instead of \r . And suggested to have a look at https://github.com/magmax/python-inquirer & its examples

Answer from inblueswithu on Stack Overflow
🌐
PyPI
pypi.org › project › readchar
readchar · PyPI
Library to easily read single chars and key strokes
      » pip install readchar
    
Published   Nov 04, 2024
Version   4.2.1
🌐
GitHub
github.com › magmax › python-readchar
GitHub - magmax/python-readchar: Python library to read characters and key strokes · GitHub
Born as a python-inquirer requirement. ... Or download the source code from PyPi. ... from readchar import readkey, key while True: k = readkey() if k == "a": # do stuff if k == key.DOWN: # do stuff if k == key.ENTER: break
Starred by 176 users
Forked by 52 users
Languages   Python 99.1% | Makefile 0.9%
🌐
Snyk
snyk.io › advisor › readchar › functions › readchar.readkey
https://snyk.io/advisor/python/readchar/functions/...
#Only for Python 2.7 #Very Important!!!!!!!!! import readchar while True: key = readchar.readkey() if key == "w": print("up") elif key == "s": print("down") elif key == "a": print("left") elif key == "d": print("right") elif key == "z": print("exiting") break ·
🌐
Snyk
snyk.io › advisor › readchar › functions › readchar.readchar
How to use the readchar.readchar function in readchar | Snyk
Do this for as many angles as possible.") print() print("When you have done all the angles, press 2.") print("Press 0 to exit at any time.") while True: key = readchar.readchar() if key == "0": return elif key == "1": angle = float(input("Enter the angle: ")) servo_angle_pws.append([angle, pw]) elif key == "2": break elif key=="a": pw = pw - 10 elif key=="s": pw = pw + 10 elif key=="A": pw = pw - 1 elif key=="S": pw = pw + 1
🌐
HotExamples
python.hotexamples.com › examples › readchar › - › readkey › python-readkey-function-examples.html
Python readkey Examples, readchar.readkey Python Examples - HotExamples
# try: while True: # print "l" # for event in pygame.event.get(): # if event.type == pygame.QUIT: # pygame.quit(); #sys.exit() if sys is imported # if event.type == pygame.KEYDOWN: # if event.key == pygame.K_0: # print("Hey, you pressed the key, '0'!") print "" char = readchar.readkey() if char == '\r' or char == ' ' or char == '\x03': controller.remove_listener(listener) sys.exit(0) # the following channel-to-instrument mappings are for my LinuxSampler setup; # yours will probably be different (remember you may need to subtract 1 from the channel shown in Linuxsampler) elif char == '1': setch
🌐
ProgramCreek
programcreek.com › python › example › 127667 › readchar.readkey
Python Examples of readchar.readkey
def select( options: List[str], selected_index: int = 0) -> int: print('\n' * (len(options) - 1)) while True: print(f'\033[{len(options) + 1}A') for i, option in enumerate(options): print('\033[K{}{}'.format( '\033[1m[\033[32;1m x \033[0;1m]\033[0m ' if i == selected_index else '\033[1m[ ]\033[0m ', option)) keypress = readchar.readkey() if keypress == readchar.key.UP: new_index = selected_index while new_index > 0: new_index -= 1 selected_index = new_index break elif keypress == readchar.key.DOWN: new_index = selected_index while new_index < len(options) - 1: new_index += 1 selected_index = new_index break elif keypress == readchar.key.ENTER: break elif keypress == readchar.key.CTRL_C: raise KeyboardInterrupt return selected_index
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-to-read-character-by-character-from-a-file
Python program to read character by character from a file - GeeksforGeeks
September 6, 2024 - Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples.
🌐
GitHub
github.com › magmax › python-readchar › blob › master › README.md
python-readchar/README.md at master · magmax/python-readchar
Born as a python-inquirer requirement. ... Or download the source code from PyPi. ... from readchar import readkey, key while True: k = readkey() if k == "a": # do stuff if k == key.DOWN: # do stuff if k == key.ENTER: break
Author   magmax
Find elsewhere
🌐
GitHub
github.com › magmax › python-readchar › blob › master › readchar › key.py
python-readchar/readchar/key.py at master · magmax/python-readchar
Python library to read characters and key strokes. Contribute to magmax/python-readchar development by creating an account on GitHub.
Author   magmax
🌐
GitHub
github.com › trinketapp › python-readchar
GitHub - trinketapp/python-readchar: Python library to read characters and key strokes
Python library to read characters and key strokes. Contribute to trinketapp/python-readchar development by creating an account on GitHub.
Author   trinketapp
🌐
GitHub
github.com › magmax › python-readchar › blob › master › readchar › _posix_key.py
python-readchar/readchar/_posix_key.py at master · magmax/python-readchar
Python library to read characters and key strokes. Contribute to magmax/python-readchar development by creating an account on GitHub.
Author   magmax
Top answer
1 of 16
244

Here's a link to the ActiveState Recipes site that says how you can read a single character in Windows, Linux and OSX:

    getch()-like unbuffered character reading from stdin on both Windows and Unix

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()
2 of 16
97
sys.stdin.read(1)

will basically read 1 byte from STDIN.

If you must use the method which does not wait for the \n you can use this code as suggested in previous answer:

class _Getch:
    """Gets a single character from standard input.  Does not echo to the screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()

(taken from http://code.activestate.com/recipes/134892/)

🌐
Pyoven
pyoven.org › package › readchar
readchar - Oven
Born as a python-inquirer requirement. ... Or download the source code from PyPi. ... from readchar import readkey, key while True: k = readkey() if k == "a": # do stuff if k == key.DOWN: # do stuff if k == key.ENTER: break
🌐
Pydigger
pydigger.com › pypi › readchar
readchar
September 11, 2022 - [![GitHub Repository](https://img.shields.io/badge/-GitHub-#0D0D0D?logo=github&labelColor=gray)](https://github.com/magmax/python-readchar) [![Latest PyPi version](https://img.shields.io/pypi/v/readchar.svg)](https://pypi.python.org/pypi/readchar) [![supported Python versions](https://img....
🌐
GitHub
github.com › magmax › python-readchar › blob › master › Makefile
python-readchar/Makefile at master · magmax/python-readchar
Python library to read characters and key strokes. Contribute to magmax/python-readchar development by creating an account on GitHub.
Author   magmax
🌐
Snyk
snyk.io › advisor › readchar › functions › readchar.key.ctrl_c
How to use the readchar.key.CTRL_C function in readchar | Snyk
print_call("No", "selected"), (('\x1b[3A\r\x1b[Kfoo (Y/N) ',), {"end": '', "flush": True},), (tuple(),), print_call("Yes"), print_call("No"), (('\x1b[3A\r\x1b[Kfoo (Y/N) f',), {"end": '', "flush": True},), (tuple(),), print_call("Yes"), print_call("No"), (('\x1b[3A\r\x1b[Kfoo (Y/N) fo',), {"end": '', "flush": True},), (tuple(),), print_call("Yes"), print_call("No"), (('\x1b[3A\r\x1b[Kfoo (Y/N) foo',), {"end": '', "flush": True},), ] with InputContext("f", "o", "o", readchar.key.CTRL_C): with self.assertRaises(KeyboardInterrupt): cutie.prompt_yes_or_no("foo") self.assertEqual(mock_print.call_args_list, expected_calls) magmax / python-inquirer / inquirer / render / console / _checkbox.py View on Github ·
🌐
Joinux
python.joinux.com › projects › readchar
A curated list of Python projects, libraries and applications | Joinux Python
Born as a python-inquirer requirement. ... Or download the source code from PyPi. ... from readchar import readkey, key while True: k = readkey() if k == "a": # do stuff if k == key.DOWN: # do stuff if k == key.ENTER: break
🌐
FreshPorts
freshports.org › textproc › py-readchar
FreshPorts -- textproc/py-readchar: Python library to read characters and key strokes
Library to easily read single chars and key strokes. The idea is to have a portable way to read single characters and key-strokes.
🌐
Snyk
snyk.io › advisor › readchar › functions › readchar.key.space
How to use the readchar.key.SPACE function in readchar | Snyk
""" interrupt: List[str] = [readchar.key.CTRL_C, readchar.key.CTRL_D] select: List[str] = [readchar.key.SPACE] confirm: List[str] = [readchar.key.ENTER] delete: List[str] = [readchar.key.BACKSPACE] down: List[str] = [readchar.key.DOWN, 'j'] up: List[str] = [readchar.key.UP, 'k'] def get_number( prompt: str, min_value: Optional[float] = None, max_value: Optional[float] = None, allow_float: bool = True) -> float: """Get a number from user input. If an invalid number is entered the user will be prompted again. Args: prompt (str): The prompt asking the user to input. magmax / python-inquirer / inquirer / render / console / _checkbox.py View on Github ·