Update console line

Asked

Viewed 407 times

1

I have a python loop, and would like to inform the value of a variable each time it is updated, however I don’t want to dirty the console printing every time and or clean the whole console.

There is a way I can get this result?

print("Executando processo:")
while True:
    a = a +1
    print a

The result at the end of 3 interactions is:

Interaction 1:

$ - Executando processo: 
$ - 1 

Interaction 2:

$ - Executando processo:
$ - 1 
$ - 2

Interaction 3:

$ - Executando processo:
$ - 1 
$ - 2
$ - 3

And I would like to get the following result:

Interaction 1:

$ - Executando processo:
$ - 1 

Interaction 2:

$ - Executando processo:
$ - 2

Interaction 3:

$ - Executando processo:
$ - 3 

1 answer

1


Uses the car return character \r.

import time

print('=== Executando ===')

for i in range(1, 11):
    print('- Processo:', i, end='\r')
    time.sleep(1)  # só para dar tempo de ver a mudança no console

print('=== Encerrado ===')

https://pt.wikipedia.org/wiki/Carriage_return

...causes a printer or output device (usually the monitor) to move the cursor position to the first position of the line it is on.

  • 1

    It is important to stress that this process only works if the new text is larger or equal to the previous one. If it is not, characters from the last text will remain displayed as \r just returns the cursor to the beginning of the line, but does not delete its contents. If there is no such guarantee in the system, the best solution is to use the one I have presented here.

  • I was going to add blanks to avoid this, but I thought it would unnecessarily complicate the understanding.

  • As soon as I arrive on the PC I edit the response to cover that case

Browser other questions tagged

You are not signed in. Login or sign up in order to post.