How can I read keyboard input in Python

I have a 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 the user presses any key. How can I do it? Thanks for answers.

+4
source share
2 answers

So, for example, you have Python code, for example:

file1.py

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

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

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

It will always wait for input. You can sink this endless loop as a separate process and do other things at the same time, so user input can have an effect on the tasks you perform.

, ( ActiveState 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

.

, Python 3.x raw_input, ().

+10

python2.x while break:

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


> test

> q

In [12]: 
0

Source: https://habr.com/ru/post/1608159/


All Articles