Python输入单个字符而不输入 [英] Python input single character without enter
问题描述
我想做的是用Python创建一个简单的pi记忆游戏.我需要的是一种从用户那里获得输入的方法,而不必在每个字符后都按"Enter"键.听起来好像我需要类似getch的东西,但我无法使其正常工作.我从这里得到了类似getch的函数: https://gist.github.com/chao787/2652257#file-getch-py .我真的不明白里面有什么.当我执行"x = getch.getch()
"时,它会显示"AttributeError: '_Getch' object has no attribute 'getch'
".看起来msvcrt可以在Windows上运行,但是我有Mac.看来curses是一件容易犯错的事情,但是它说我需要先执行initscr,然后我会收到错误"File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/curses/__init__.py", line 30, in initscr
fd=_sys.__stdout__.fileno())
_curses.error: setupterm: could not find terminal
".
What I am trying to do is make a simple pi memorization game in Python. What I need is a way to get input from the user without having to press 'enter' after every character. It sounds like I need something like getch, but I can't get it to work. I got a getch-like function from here: https://gist.github.com/chao787/2652257#file-getch-py. I don't really understand anything that's in there. When I do 'x = getch.getch()
' it says "AttributeError: '_Getch' object has no attribute 'getch'
". It looks like msvcrt can do it for Windows, but I have a Mac. It also looks like curses is a thing that has getch, but it says I need to do initscr first, but then I get the error "File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/curses/__init__.py", line 30, in initscr
fd=_sys.__stdout__.fileno())
_curses.error: setupterm: could not find terminal
".
这是我仅使用输入的文件,您每次都必须按Enter键(我实际上输入了1000位数字,而不是省略号).
This is my file just using input, where you would have to press enter every time (I actually put in 1000 digits, not an ellipsis).
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
版本:
You can define your own version of getch
using the termios
, sys
and tty
packages:
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输入单个字符而不输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!