10

I have a python script which receives values in real-time. My script prints the values as they are received and currently, each update is printed to the screen and the output scrolls down e.g.

Update 1
Update 2
Update 3
...

Is it possible to have each new value overwrite the previous value on the output screen so that the values don't scroll? e.g.

Update 1

When Update 2 is received the print statement would update the output screen to:

Update 2

and so on...

Thanks in advance for any pointers.

Mark Smith
  • 757
  • 2
  • 16
  • 27

3 Answers3

17

You can pass end='\r' to the print() function. '\r' represents a carriage return in Python. In Python 3 for example:

import time
for i in range(10):
    print('Update %d' % i, end='\r')
    time.sleep(5)

Here time.sleep(5) is just used to force a delay between prints. Otherwise, even though everything is being printed and then overwritten, it will happen so fast that you will only see the final value 'Update 9'. In your code, it sounds like there is a natural delay while some processes is running, using time.sleep() will not be necessary.

elethan
  • 16,408
  • 8
  • 64
  • 87
  • 1
    this will not work on Linux environments, you need to update print statement as shown here on consoles/Linux `print('', end=f'\rUpdate {i}')` – sahil panindre Feb 15 '22 at 04:12
  • Would this work if subthread print additional values into the terminal? – alper Mar 12 '23 at 13:18
6

In python 2.7, the print function will not allow an end parameter, and print 'Update %d\r' will also print a newline character.

Here is the same example @elethan gave for python2.7. Note it uses the sys.stdout output stream:

import sys
import time
output_stream = sys.stdout

for i in xrange(10):
    output_stream.write('Update %s\r' % i)
    output_stream.flush()
    time.sleep(5)
# Optionally add a newline if you want to keep the last update.
output_stream.write('\n')
Bamcclur
  • 1,949
  • 2
  • 15
  • 19
1

Assuming you have your code which prints the updated list in write_num function, You can have a function called show_updated_list(). Hoping the clear() every time should resolve this issue:

def show_updated_list():
    self.clear()
    write_num()
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Py_love
  • 11
  • 1