I'm using Python's cmd
module to handle a terminal input loop.
I have a thread running in the background, which prints out some stuff in the terminal when it receives a message. These messages break the visual user input:
> writing a com
@@@ message generated from a thread and printing during user input @@@
mand
I ask a related question here and was basically told that one way to avoid breaking the user's input would be to keep track of user input, so that when a message comes in I can print the message and the reprint the user input. When I asked that question I wasn't using the cmd
module.
When using the cmd
module, how would I keep track of what the user has currently typed, so that I can reprint it after?
I discovered the readline
module and it's get_line_buffer()
method.
Here's how I solved it, in the thread that wants to print out data while I'm reading user input in the main:
import readline
# Save the current buffer
current_buffer = readline.get_line_buffer()
# Print our stuff, note the \r is important to overwrite the current buffer
print("\rladida interruption\nsome more interruption\n")
# Reprint our buffer
print('> ' + current_buffer, end='', flush=True)
Here's an example, before:
$ ./main.py
> help
and after:
$ ./main.py
ladida interruption
some more interruption
> help
Note how the command prompt cleanly moved down, with the users current command input in place. The cursor is also in the right position to continue typing, backspace works fine too.