Python输入不带enter的单个字符
我想做的是用Python制作一个简单的pi记忆游戏。我需要的是一种从用户那里获取输入的方法,而不必在每个字符后按“回车”。听起来我需要像getch这样的东西,但我无法让它工作。我从这里得到了一个类似getch的函数:。我真的不明白里面有什么。当我执行“Python输入不带enter的单个字符,python,curses,msvcrt,getch,Python,Curses,Msvcrt,Getch,我想做的是用Python制作一个简单的pi记忆游戏。我需要的是一种从用户那里获取输入的方法,而不必在每个字符后按“回车”。听起来我需要像getch这样的东西,但我无法让它工作。我从这里得到了一个类似getch的函数:。我真的不明白里面有什么。当我执行“x=getch.getch()”时,它会显示“AttributeError:“\u getch”对象没有属性“getch””。看起来msvcrt可以在Windows上运行,但我有一台Mac电脑。看起来curses也是一个有getch的东西,但是它说
x=getch.getch()
”时,它会显示“AttributeError:“\u getch”对象没有属性“getch”
”。看起来msvcrt可以在Windows上运行,但我有一台Mac电脑。看起来curses也是一个有getch的东西,但是它说我需要先做initscr,但是在initscr的第30行,我得到了错误“File”/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/curses/_uuinit_uuu.py”
fd=_sys.uuu stdout.uuuu.fileno())
_curses.error:setupterm:找不到终端
”
这是我使用输入的文件,每次都必须按enter键(我实际上输入了1000位数字,而不是省略号)
pi='3.1415926535…'
def main():
打印(“欢迎使用PiGame!”)
pigame()
尽管如此:
yn=输入('再次播放?是/否')
如果yn==“y”:
pigame()
其他:返回
def pigame():
n=0
打印('Go!')
而n您可以使用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()
这是一个经过测试的(在RPi上,Py 3)代码,无需点击回车按钮即可读取指定长度的字符
<强>但<>强>考虑一件事:
这必须在终端上运行,否则会引发错误
import termios, sys , tty
def _getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1) #This number represents the length
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
getch = _getch()
print(getch)
看,是的,我读过那本。这与给我属性错误的代码相同。我是否应该在该线程上添加一个响应或注释,说它不起作用?这样的注释(肯定不是答案!)将提供有关您尝试过的内容以及您的环境(例如通过指向此Q的指针)可能会帮助其他人的全部详细信息,因此这绝非一个坏主意。termios.error:(25,“设备的ioctl不合适”)需要返回_getch()(您忘记了括号)显然termios在Windows系统上不存在。有没有办法从perl中改编Term::ReadKey,它在Windows上可以工作?
import termios, sys , tty
def _getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1) #This number represents the length
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
getch = _getch()
print(getch)