Search code examples
pythonttyansi-escape

Move still-buffered stdin line down by one when there is output


I have written a simple chat program in python. You just have a simple input() prompt (using readline) which should always be on the bottom.

partner: hey
you > (stdin)

Now, I am trying this without using curses and I have had success by defining these two constants

CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2M'

which I use like this whenever a message from 'partner' is received:

print(ERASE_LINE + CURSOR_UP_ONE)
print('partner > ' + msg)
print('you > ')

This works fine, however, there is one problem: When I start typing just as a message from 'partner' comes in, it erases the line including what I typed (which I am then no more able to access) and the erased characters are obviously still part of what input() returns.

So, is there a way of moving down the input prompt without curses or a way to buffer the typed in characters to be able to access, display and manipulate them?


Solution

  • Ok, I solved my problem. I discovered the module rl. I use it this way:

    import rl.readline as readline
    
    # code
    
    print(ERASE_LINE + CURSOR_UP_ONE)
    print('partner > ' + msg)
    
    readline.redisplay(True)
    

    This just redisplays the prompt including what I typed (just what I wanted).