首页 > 解决方案 > 如何在 Jupyter 中获取单个字符输入?

问题描述

在 Jupyter 中,使用 python 3,我正在尝试运行一个单元格,该单元格应该在 for 循环中要求输入单个字符并将答案存储在列表中。我想避免使用 input() 以避免每次都按回车键。

在 Windows 中工作,我尝试过:

import msvcrt

charlist = []

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

但是在运行单元时,内核会卡在 getch() 行的第一个实例而不接受任何输入。有没有办法在 Jupyter 笔记本中做到这一点?

标签: pythonpython-3.xjupyter-notebookmsvcrtgetch

解决方案


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

有关更多详细信息,请查看它。 http://code.activestate.com/recipes/134892/


推荐阅读