First of all, I know there are some people who had the same question, for example this one and this one, but the answers didn't really give a good solution that did the right thing, and a bunch of the solutions only worked on Linux (as well as not doing the right thing).
Lets say, for example, I have a simple web server running using the socketserver module, and I want the user to be able to control the server while it's running, but I also want to print requests. I would have something like this:
Request from 127.0.0.1 - GET /index.html
Request from 127.0.0.1 - GET /login.html
Input command:
The problem is, I can't print more information while the user is getting input. Let's say a new request came in during user input:
Request from 127.0.0.1 - GET /index.html
Request from 127.0.0.1 - GET /login.html
Input command: asdfasdfasRequest from 127.0.0.1 - GET /login.htmldf
Here is a simple python program you can run to see this:
import threading
from time import sleep
def foo():
sleep(2)
i = 0
while True:
i += 1
print(f"Request {i}")
sleep(1)
t = threading.Thread(target=foo)
t.start()
while True:
x = input("Enter: ")
I can print the information below the input line, and that would work okay, but it could confuse the order that things happened in, since the user didn't actually enter the command until after the request came in. I can always add a timestamp, and that's what I might do if there's no other good option, but it still wouldn't be great.
I can use ansi escape codes to print above the line, but it would overwrite old requests. I can't use ansi escape codes to print a newline and move the line down, but I could always just clear the line and rewrite the prompt a line down. This seems like a good solution, but the problem is, if the user has already typed something, it would get cleared. Is there a way to get the letters a user has typed so far? Capturing keyboard input could work, but isn't as good, and wouldn't work, for example, over SSH.
I'm not really sure what to do here, so any assistance would be greatly appreciated. Thanks in advance!