Python getch() - 多个字符

时间:2014-03-12 07:16:29

标签: python python-2.7 python-3.x

我知道python getch()适合检测单击键。

是否有任何方法,我可以使用相同的功能来检测多个击键。,

此外,是否可以在打印输出之前使程序等待。

例如:When I press 'w', the program must wait for another keystroke, 'a', before it prints the output for 'w'. I know this is workaround, but I think, as of now, this should do.

示例代码:

try:
    from msvcrt import getch
    print "I am Here"
except ImportError:
    print "Hi"
    def getch():
    print "I am here!"
        import sys, tty, termios            
        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
def getchs():
    while True:
        yield getch()
for choice in getchs():  
        if choice == 'w':
            print (80 * '-')
            print ("You have chosen Orange...")
            print ("Here's the nutritional fact of the Orange:")
            print ("'One medium orange contains 1.23 grams of protein, 62 calories and 3.1 grams of dietary fiber.'")
            print (80 * '-')
        elif choice == 'a':
            print (80 * '-')
            print ("You have chosen Banana...")
            print ("Here's the nutritional fact of the Banana:")
            print ( "'One medium banana contains 1.29 grams of protein, 105 calories and 3.1 grams of dietary fiber")
            print (80 * '-')

现在这非常适合检测' w'和'a'

我如何使用'wa',而不是getch()

合并该功能以进行组合:raw_input

我搜索过这个,找不到。

另外,curses模块会帮助实现这个目标吗?

由于

1 个答案:

答案 0 :(得分:2)

pykeylogger可能会对您有所帮助。根据pykeylogger docs

  

目前可用于Windows(NT / 2000及更高版本)和Linux   (使用Xlib,因此无法在控制台上工作)。

仅限Windows,请检查keyboard hooks

中的pyhook