如何在Jupyter中获得单字符输入?

2024-03-29 14:50:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在Jupyter中,使用python3,我尝试运行一个单元格,该单元格要求在for循环中输入一个字符,并将答案存储在一个列表中。我想避免使用input()来避免每次都要按enter键。你知道吗

在windows中工作时,我尝试:

import msvcrt

charlist = []

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

但是当运行这个单元时,内核会被困在getch()行的第一个实例上,而不接受任何输入。有没有什么办法可以在电脑笔记本上做到这一点?你知道吗


Tags: 答案inimport列表forinputwindowsjupyter
1条回答
网友
1楼 · 发布于 2024-03-29 14:50:47
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/

相关问题 更多 >