Printing Stdout In Command Line App Without Overwriting Pending User Input

Posted by Chris S on Stack Overflow See other posts from Stack Overflow or by Chris S
Published on 2010-03-13T23:01:46Z Indexed on 2010/03/13 23:05 UTC
Read the original article Hit count: 556

Filed under:
|
|
|
|

In a basic Unix-shell app, how would you print to stdout without disturbing any pending user input.

e.g. Below is a simple Python app that echos user input. A thread running in the background prints a counter every 1 second.

import threading, time

class MyThread( threading.Thread ):
    running = False
    def run(self):
        self.running = True
        i = 0
        while self.running:
            i += 1
            time.sleep(1)
            print i

t = MyThread()
t.daemon = True
t.start()
try:
    while 1:
        inp = raw_input('command> ')
        print inp
finally:
    t.running = False

Note how the thread mangles the displayed user input as they type it (e.g. hell1o wo2rld3). How would you work around that, so that the shell writes a new line while preserving the line the user's currently typing on?

© Stack Overflow or respective owner

Related posts about python

Related posts about bash