Keeping the user's input intact when outputing to terminal at the same time
<p>To simplify, let's say I'm trying to write a command line two-way chat in Python. I would like the user to input his message with <code>input()</code> at the command prompt, but a listening thread could print a message at any moment. By default, this would "break" the user's input. Visually something like this:</p>

<pre><code>userB&gt;Stop interuserA wrote:Hey check this out!
rupting me!
</code></pre>

<p>The closest I was able to find was <a href="http://stackoverflow.com/questions/27304078/how-to-print-over-raw-inputs-line-in-python">this answer here</a> which is almost, but not exactly, what I'm looking for, but it did point me towards the <code>blessings</code> package which seems to be what I need (although I'm happy with an answer for any package, or even pure ANSII).</p>

<p>What I'm trying to achieve is to print incoming output from a Thread <em>above</em> the user's input, so that his text doesn't break. Let's say the user is typing:</p>

<pre><code>userB&gt;Stop inter
</code></pre>

<p>Suddenly a message comes in from the thread, but our user's input doesn't brake:</p>

<pre><code>userA says: Ok I won't interrupt you
userB&gt;Stop inter
</code></pre>

<p>What should my threads theoretical <code>print_incoming_message()</code> method look like to achieve this?</p>

<p>NB: I'm using Linux and am not interested in cross-platform compatibility.</p>

<p>There are two ways of doing this.</p>

<p>One is to use <code>ncurses</code>. There are python bindings for this. With <code>ncurses</code>, the terminal screen is under your complete control, and you can print characters at any point.</p>

<p>Without <code>ncurses</code>, you can't write above the current line. What you <em>can</em> do, however, is print a <code>\r</code> character and go back to the beginning of the line.</p>

<p>If you save the user's input (say he wrote <code>foo</code>), and you want to print the line <code>bar</code> above that, you can output:</p>

<pre><code>\rbar\nfoo
</code></pre>

<p>This will overwrite the current line, and introduce a newline, moving the user's input down. The effect is similar, but it won't be as tamper-proof as <code>ncurses</code>.</p>

python multithreading python-3.x output