编程语言
首页 > 编程语言> > Python输入单个字符没有输入

Python输入单个字符没有输入

作者:互联网

我想要做的是在Python中制作一个简单的pi记忆游戏.我需要的是一种从用户那里获得输入的方法,而不必在每个角色后按“输入”.听起来我需要像getch这样的东西,但我无法让它工作.我从这里得到了类似于getch的函数:https://gist.github.com/chao787/2652257#file-getch-py.我真的不明白那里的任何东西.当我执行’x = getch.getch()’时,它说“AttributeError:’_ Get’对象没有属性’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 .__标准输出__.的fileno())
_curses.error:setupterm:找不到终端“.

这是我的文件只是使用输入,你必须每次按Enter键(我实际上输入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!')

解决方法:

您可以使用termios,sys和tty包定义自己的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,curses,getch,msvcrt
来源: https://codeday.me/bug/20190624/1276050.html