【问题标题】:How to get single character input in Jupyter?如何在 Jupyter 中获取单个字符输入?
【发布时间】:2020-04-16 12:57:56
【问题描述】:

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

在windows中工作,我试过了:

import msvcrt

charlist = []

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

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

【问题讨论】:

标签: python python-3.x jupyter-notebook msvcrt getch


【解决方案1】:
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/

【讨论】:

  • 感谢您的回答。不过,就我而言,这只是 msvcrt.getch() 的包装,在 Jupyter 中,它仍然给出问题末尾描述的相同问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 2018-12-10
  • 2023-03-29
  • 2012-06-14
  • 1970-01-01
  • 2018-10-18
相关资源
最近更新 更多