4

In Jupyter, using python 3, I am trying to run a cell that is supposed to ask for a single character input in a for loop and store the answer in a list. I wanted to avoid the use of input() to avoid having to press enter everytime.

Working in windows, I tried:

import msvcrt

charlist = []

for x in range(10):
    print("Some prompt")
    a = msvcrt.getch()
    charlist.append(a)

but when running the cell, the kernel gets stuck at the first instance of the getch() line without accepting any input. Is there any way to do this in a Jupyter notebook?

msfrn
  • 43
  • 3
  • I think this is what your are looking for. https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user – beka gogaladze Dec 26 '19 at 08:32

1 Answers1

0
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()

for more details look into it. http://code.activestate.com/recipes/134892/

  • Thanks for the answer. In my case, though, this just becomes a wrapper for msvcrt.getch() and in Jupyter it still gives the same issue described at the end of the question. – msfrn Dec 30 '19 at 08:07