0

I have a non-blocking read from sys.stdin using select which alternates handlers for my socket and user input:

while True:
    input_ready, _, _ = select.select([my_socket, sys.stdin], [], [])
    for sender in input_ready:
        if sender == sys.stdin:
            process_user_input()
        elif sender == my_socket:
            process_socket_reply()

in process_user_input() I have:

command = input()

to get and handle user input.

I want to show a prompt to give a terminal-like view to my users; just like what when using input('> ') in a blocking stdin input we can achieve.

But, if I use input('> ') in my process_user_input(), > will be printed after user entered his command (as expected!)

some_command
> Invalid command. 

How can I do that?

NOTE: As I have another events happening in my code, there may be some prints in stdout (thus, print('> ', end='') will fail). So I want my > to be present whenever I'm waiting for inputs, even after some prints in terminal.

1 Answer 1

1

When you write output to a terminal, it generally won't appear on the terminal immediately. Instead, it waits in a buffer somewhere, to be "flushed" to the terminal display at some opportune time. On most systems, that time is when your code writes a newline.

Since you want the '> ' prompt to appear on the same line as your user's input, you can't write a newline after it to flush the buffer. Instead, you must add the flush argument to your print function call:

print(end='> ', flush=True)

If you want the prompt to appear after other output is printed on the screen, you could:

  • Add print(end='> ', flush=True) to the end of any other code that produces output while your program waits for user input.

  • Create your own implementation of Python's standard output stream sys.stdout, which would add print(end='> ', flush=True) whenever other parts of your program print a newline.

  • Use an advanced terminal toolkit such as Python Prompt Toolkit or Curses to always keep your '> ' prompt at the bottom of the terminal window.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for my very late reply. Actually I read your reply on time and used your first solution. But other solutions you proposed are interesting to me and I wish I can make my hands dirty with them later. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.