Skip to content Skip to sidebar Skip to footer

Need Character-by-character Keyboard Input That Interacts Well With Paste And ANSI Escape Sequences

My program (a 'TRAC Processor') uses character-by-character input. I am implementing readline-like input features for strings which are terminated with characters other than enter

Solution 1:

The "no-parameter read" is often cited as a way to read all available bytes, which sounds perfect for this application. Unfortunately, when you look at the documentation, read() is the same as readall(), which blocks until EOF. So you need to set stdin to non-blocking mode.

Once you do this, you start getting:

IOError: [Errno 35] Resource temporarily unavailable

When you google this, the vast majority of responses say that the solution to this problem is to get rid of non-blocking mode... so that's not helpful here. However, this post explains that this is simply what the non-blocking read() does when there are no characters to return.

Here is my flush() function, much of which copied from that post:

def flush():
    import sys, tty, termios, fcntl, os
    fd = sys.stdin.fileno()
    old_attr = termios.tcgetattr(fd)
    old_fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    try:
        tty.setraw(fd)
        fcntl.fcntl(fd, fcntl.F_SETFL, old_fl | os.O_NONBLOCK)
        inp = sys.stdin.read()
    except IOError, ex1:  #if no chars available generates exception
        try: #need to catch correct exception
            errno = ex1.args[0] #if args not sequence get TypeError
            if errno == 35:
                return '' #No characters available
            else:
                raise #re-raise exception ex1
        except TypeError, ex2:  #catch args[0] mismatch above
            raise ex1 #ignore TypeError, re-raise exception ex1
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_attr)
        fcntl.fcntl(fd, fcntl.F_SETFL, old_fl)
    return inp

Hope it's helpful to someone!


Post a Comment for "Need Character-by-character Keyboard Input That Interacts Well With Paste And ANSI Escape Sequences"