Python输入单个字符不用回车

标签 python curses msvcrt getch

我想做的是用 Python 制作一个简单的圆周率内存游戏。我需要的是一种无需在每个字符后按“输入”即可从用户那里获取输入的方法。听起来我需要像 getch 这样的东西,但我无法让它工作。我从这里得到了一个类似 getch 的函数:https://gist.github.com/chao787/2652257#file-getch-py .我真的不明白里面的任何东西。当我执行“x = getch.getch()”时,它显示“AttributeError:‘_Getch’对象没有属性‘getch’”。看起来 msvcrt 可以为 Windows 做到这一点,但我有一台 Mac。看起来 curses 是一个有 getch 的东西,但它说我需要先执行 initscr,但随后我收到错误“File”/Library/Frameworks/Python.framework/Versions/3.4/lib/python3 .4/curses/__init__.py”,第 30 行,在 initscr 中 fd=_sys.__stdout__.fileno()) _curses.error: setupterm: 找不到终端"。

这是我的文件,只使用输入,你每次都必须按回车键(我实际上输入了 1000 位数字,而不是省略号)。

pi = '3.1415926535...'


def main():
    print('Welcome to PiGame!')
    pigame()
    while True:
        yn = input('Play again? y/n ')
        if yn == 'y':
            pigame()
        else: return


def pigame():

    n=0

    print('Go!')


    while n<=1000:
        x = input()
        if x == pi[n]:
            n += 1
        else:
            print('I\'m sorry. The next digit was '+pi[n]+'.')
            print('You got to '+str(n)+' digits!')
            return
    print('You got to 1000! Hooray!')

最佳答案

您可以使用 termiossystty 包定义您自己的 getch 版本:

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

关于Python输入单个字符不用回车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27750536/

相关文章:

python - 查看不工作/如何在 shell 中测试它?

python - 在使用 curses 将字符串绘制到屏幕之前,如何为字符串的某些部分着色?

winapi - 我如何告诉 MS CRT 在 Windows XP 上使用低碎片堆?

php - 如何在php-fpm shell_exec中激活anaconda环境?

python - 分析 MIPS 二进制文件 : is there a Python library for parsing binary data?

visual-studio-2017 - 在 Visual Studio 2017 上安装 pdcurses

javascript - vt100 应用程序的 Node.js/Angular 包装器

c++ - MinGW 是如何实现 C++ 库支持的?

c - 样板 CRT 函数 matherr 有什么意义?

python - psycopg2 中带有标识符的动态 SQL?