How can i delete input question in console?

Viewed 177

I want to overwrite the input with a new output. I want to do the same thing (https://stackoverflow.com/a/8436827/14079038) but I need to overwrite the input.

My code returns:

while not addIp.__eq__(''):
    ignoredIp.append(addIp)
    print(addIp)
    addIp = input('Would you like to add ip ? (None = no): ')
Would you like to add ip ? (None = no): 1.1.1.1
1.1.1.1
Would you like to add ip ? (None = no): 1.1.1.2
1.1.1.2
Would you like to add ip ? (None = no):

But i want something like this:

10.11.100.66
10.11.100.67
10.11.100.68
10.11.100.69
10.11.100.70
Would you like to add ip ? (None = no):
1 Answers

If you write in the same line then use end='\r' in print() and it will not move to next line.

But it will not work with input() which sends \n to console/terminal and you can't stop it. Maybe if you will use modules like curses which can use special codes in some consoles/terminals to move cursor in any place then you could move back to previous line.


On Linux terminal you can use code \033[nA to move n lines up.

This way you can use \033[1A to move to previous line and print text in place of question.

It needs also some spaces at the end to remove text from longer question.

addIp = '?'
while addIp:
    addIp = input('Would you like to add ip ? (None = no): ')
    print('\033[1A' + addIp + ' '*40)

See other codes. Linux uses similar codes to colorize text.


There are also modules which should work with Windows, Linux,

and they are used to draw widgets in text mode (TUI - Text User Interface)


Not all consoles/terminals can respect these codes - often consoles in IDEs/editors don't respect these code.

Related