I'm trying to write a (command line) python program that will accept input from the user while still printing data above it. I am trying to make a chat program.
Example:
[stuff prints here]
hello
warning: the time is 27:64
Please enter your input: asdf
So I have typed the asdf, but while I am typing, the output above continues to update. If I want, I can continue to type while the output is being generated. Then if I press enter, something else happens. The input field should always stay below the the outputted text; if more text is displayed, the input field gets pushed down (but its contents remain in place).
My thoughts were:
This needs to be some sort of non-blocking read...
...or maybe threading? One thread for input, one for output.
Might I need to do some cursor manipulation (i.e. moving the cursor upwards, printing output, returning cursor to user input area)?
I realize that a GUI would be much easier to do. I'll probably end up just doing this with tkinter. But I was nevertheless wondering if this sort of thing is possible in python on the command line.
Thanks.
EDIT: I forgot to mention that I do know how to erase text with carriage returns (\r). The problem really is making sure that when I erase the line, I don't clear the user input: So if a new line comes up while I am typing, I don't want the input I have so far to be erased.
Yes, it is possible to achieve this type of functionality in a command line python program. One way to accomplish this is by using the curses library, which allows you to control the terminal window and cursor position. You can use the curses.newwin() function to create a new window and curses.stdscr.move() function to move the cursor to the desired position.
Another approach could be using the readline library, which allows you to read input from the user without blocking the execution of the program. You can use the readline.get_line_buffer() function to get the current input buffer and the readline.redisplay() function to redraw the input line.
Alternatively, you can use a thread for input and another for output, as you mentioned. The input thread could use the input() function to get input from the user and the output thread could use print() to output text to the screen. You can use a queue to share information between the threads.
It's worth noting that the input() function is blocking, which means it will wait for the user to enter something before returning. To avoid this you could use input() inside a non-blocking thread or use curses.getch() to accept input.
Regarding your edit, you can use the \r character to move the cursor back to the start of the current line, and then use print() to write the new text. This way the current input will not be cleared.
It's a complex task, I recommend you to use a library like urwid or prompt-toolkit to help you with this task.