代码之家  ›  专栏  ›  技术社区  ›  Václav Pavlíček

如何在Python中读取键盘输入

  •  3
  • Václav Pavlíček  · 技术社区  · 10 年前

    我在Python中的键盘输入有问题。我尝试了raw_input,但只调用了一次。但我希望每次用户按下任何键时都能读取键盘输入。我该怎么做?谢谢回答。

    2 回复  |  直到 10 年前
        1
  •  10
  •   Community Mohan Dere    5 年前

    例如,您有一个Python代码,如下所示:

    文件1.py

    #!/bin/python
    ... do some stuff...
    

    在文档的某一点,您希望始终检查输入:

    while True:
        input = raw_input(">>>")
        ... do something with the input...
    

    这将始终等待输入。您可以将无限循环作为一个单独的进程来执行,同时执行其他任务,这样用户输入就可以对您正在执行的任务产生影响。

    如果您只想在按下某个键时请求输入,并将其作为一个循环执行,则使用以下代码(取自 this ActiveState recipe by Steven D'Aprano )您可以等待按键发生,然后请求输入、执行任务并返回到前一状态。

    import sys
    
    try:
        import tty, termios
    except ImportError:
        # Probably Windows.
        try:
            import msvcrt
        except ImportError:
            # FIXME what to do on other platforms?
            # Just give up here.
            raise ImportError('getch not available')
        else:
            getch = msvcrt.getch
    else:
        def getch():
            """getch() -> key character
    
            Read a single keypress from stdin and return the resulting character. 
            Nothing is echoed to the console. This call will block if a keypress 
            is not already available, but will not wait for Enter to be pressed. 
    
            If the pressed key was a modifier key, nothing will be detected; if
            it were a special function key, it may return the first character of
            of an escape sequence, leaving additional characters in the buffer.
            """
            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
    

    那么如何处理这个问题呢?好吧,现在打电话 getch() 每次你想等待按键时。就像这样:

    while True:
        getch() # this also returns the key pressed, if you want to store it
        input = raw_input("Enter input")
        do_whatever_with_it
    

    你也可以在这段时间内完成其他任务。

    请记住,Python3.x不再使用raw_input,而是简单地使用input()。

        2
  •  1
  •   zhangxaochen    10 年前

    在python2.x中,只需使用无限 while 带条件的循环 break :

    In [11]: while True:
        ...:     k = raw_input('> ')
        ...:     if k == 'q':
        ...:         break;
        ...:     #do-something
    
    
    > test
    
    > q
    
    In [12]: