Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

cmd - 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 , 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On Linux you can do it this way:

#!/usr/bin/python

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

print('Text 1
Text 2
Text 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...