Home > Backend Development > Python Tutorial > How to Detect Keyboard Input from the Terminal in a Script?

How to Detect Keyboard Input from the Terminal in a Script?

Mary-Kate Olsen
Release: 2024-10-29 22:00:29
Original
469 people have browsed it

How to Detect Keyboard Input from the Terminal in a Script?

How to detect keyboard input in a script from the terminal

There are several ways to detect keyboard input in a script from the terminal, depending on your needs and operating system.

Synchronous/Blocking key capture

This approach blocks the script until a key is pressed, and then returns the key that was pressed.

  • For simple input or raw_input, a blocking function which returns text typed by a user once they press a newline.
  • For a simple blocking function that waits for the user to press a single key, then returns that key, use the following code.
<code class="python">class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen. From http://code.activestate.com/recipes/134892/"""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            try:
                self.impl = _GetchMacCarbon()
            except(AttributeError, ImportError):
                self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

class _GetchMacCarbon:
        """
        A function which returns the current ASCII key that is down;
        if no ASCII key is down, the null string is returned.  The
        page http://www.mactech.com/macintosh-c/chap02-1.html was
        very helpful in figuring out how to do this.
        """
        def __init__(self):
            import Carbon
            Carbon.Evt #see if it has this (in Unix, it doesn't)

        def __call__(self):
            import Carbon
            if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
                return ''
            else:
                #
                # The event contains the following info:
                # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
                #
                # The message (msg) contains the ASCII char which is
                # extracted with the 0x000000FF charCodeMask; this
                # number is converted to an ASCII character with chr() and
                # returned
                #
                (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
                return chr(msg &amp; 0x000000FF)


def getKey():
    inkey = _Getch()
    import sys
    for i in xrange(sys.maxint):
        k=inkey()
        if k<>'':break

    return k</code>
Copy after login

Asynchronous key capture

  • A callback that is called with the pressed key whenever the user types a key into the command prompt, even when typing things into an interpreter (a keylogger)
  • A callback that is called with the typed text after the user presses enter (a less realtime keylogger)

Polling

  • The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).
  • The same as above, except that poll only returns something once the user presses a newline.

Robots

  • These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user

The above is the detailed content of How to Detect Keyboard Input from the Terminal in a Script?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template