How can I read keyboard input in Python

2019-03-31 01:37发布

问题:

I have problem with keyboard input in Python. I tried raw_input and it is called only once. But I want to read keyboard input every time user press any key. How can I do it? Thanks for answers.

回答1:

So for instance you have a Python code like this:

file1.py

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

And at a certain point of the document you want to always check for input:

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

That will always wait for input. You can thread that infinite loop as a separate process and do other things in the meanwhile, so that the user input can have an effect in the tasks you are doing.

If you instead want to ask for input ONLY when a key is pressed, and do that as a loop, with this code (taken from this ActiveState recipe by Steven D'Aprano) you can wait for the key press to happen, and then ask for an input, execute a task and return back to the previous state.

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

So how to deal with this? Well, now just call getch() every time you want to wait for a key press. Just like this:

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

You can also thread that and do other tasks in the meanwhile.

Remember that Python 3.x does no longer use raw_input, but instead simply input().



回答2:

In python2.x, simply use an infinite while loop with conditional break:

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


> test

> q

In [12]: