Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Read User Input while Printing Output

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.

like image 967
baum Avatar asked Apr 11 '26 23:04

baum


1 Answers

The classic approach to such problem would be:

  • Have a server module listening to incoming requests, and printing the input
  • Have a threaded client module(forked in to 2 threads, in our example).
  • The clients will use be able to behave simultaneously, by using the threading library of Python.
like image 91
py_script Avatar answered Apr 13 '26 13:04

py_script



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!