如何在同一时间得到一个按键?
对于Unix变体:有几个 解决方案。使用curses做 很简单,但诅咒是一个 相当大的模块来学习。这里有一个 解决方案,而诅咒:
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", `c`
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
您需要的termios和任何的当前工作中的fcntl 模块,并 我只试过在Linux上,虽然它 应该工作别处。在此代码中, 字符每次都会被读取并打印在 之一。
termios.tcsetattr()关闭stdin的 回显并禁用规范模式。 fcntl.fnctl()用于获取 stdin的文件描述符标志和 将它们修改为非阻塞模式。 由于读取标准输入时为空 导致IOError,此错误为 被捕获并被忽略。
使用这个,你可以抓住角色,检查它是否是一个数字,然后显示它。虽然我没有尝试过。