mathestar mathestar - 1 year ago 95
Python Question

Print text before input() prompt in python

In Python, is it possible to request user input with input() in the console while simultaneously printing out text in the line BEFORE the prompt?
It should look something like this:

Text 1
Text 2
Text 3
Please enter something: abc

Whenever new text is printed, it should be printed after the previous text and before the input() prompt. Also, it should not interrupt the user entering the text.

Therefore, after printing "Text 4" the console should look like this:

Text 1
Text 2
Text 3
Text 4
Please enter something: abc

Is that possible to do in Python without using any external libraries?

I have already tried using \r, \b and similar codes as well as threading.
I also know that I will probably need to have one thread printing out the text while I have another one requesting the user input.

Answer Source

On Linux you can do it this way:


CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'

print('Text 1\nText 2\nText 3')

inp = ''
while inp != 'END':
    inp = raw_input('Please enter something:')
    print(CURSOR_UP_ONE + ERASE_LINE + inp)

The point is in moving the cursor one line up every time and erasing the line Please enter something:. Then you can write the input on its place and write the notice about input again, if needed.

Special strings:

CURSOR_UP_ONE and ERASE_LINE are strings with special meaning. The complete list if those Terminal escape control sequences you can find HERE.

Use of ANSI Terminal escape control sequences on Windows:

To some extent it's possible to use this sequences on Windows too. E.g. those questions deals with this topic:

Workflow of this script

enter image description here enter image description here enter image description here enter image description here