IT Ninja
IT Ninja

Reputation: 6430

How to update a number without changing lines or placement of output

I would like to update a number without changing its placement in the output of a program. How would i go about doing this using only what is included in the standard library for python 2.7.2 ?

For example i want output like:

working on: 9

and change to:

working on: 10

without changing the line that it is displayed on. How would i go about doing this? I would also prefer that you not use cls as to prevent "flashing".

Upvotes: 1

Views: 161

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601529

How to do this depends on your terminal type (and possibly on your platform). An easy way that works on many platforms and terminals is to use a \r character to move the cursor back to the beginning of the line:

import time
import sys
for i in range(10):
    print "\rworking on:", i,
    sys.stdout.flush()
    time.sleep(1)

To make the line actually appear, you might need the call to sys.stdout.flush().

Upvotes: 5

Wilduck
Wilduck

Reputation: 14096

There isn't any easy way to do this without resorting to a GUI of some type. The standard way to create a GUI using the terminal is python's curses module. For an explanation of how to use curses in your application see: Curses Programming with Python.

Upvotes: 1

Related Questions