python输入单个字符,Python输入单个字符而不输入

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".

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!')

解决方案

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值