views:

151

answers:

2

I have a python script and I want to make it display a increasing number from 0 to 100% in the terminal, I know how to print the numbers on the terminal but how can I "rewrite" them so 0 turns into 1, 1 into 2, and so on until 100?

+3  A: 

This recipe here should prove useful. Using that module as tc, the following code does what you want:

from tc import TerminalController
from time import sleep
import sys

term = TerminalController()

for i in range(10):
    sys.stdout.write("%3d" % i)
    sys.stdout.flush()
    sleep(2)
    sys.stdout.write(term.BOL + term.CLEAR_EOL)

The recipe uses terminfo to get information about the terminal and works in Linux and OS X for a number of terminals. It does not work on Windows, though. (Thanks to piquadrat for testing, as per the comment below).

Edit: The recipe also gives capabilities for using colours and rewriting part of the line. It also has a ready made text progress bar.

Muhammad Alkarouri
@Muhammad: as requested, I tried your code on Windows (Windows 7, Python 2.7). Output is " 0 1 2 3 4 5 6 7 8 9".
piquadrat
@piquadrat: thanks a lot.
Muhammad Alkarouri
+6  A: 

Printing a carriage return (\r) without a newline resets the cursor to the beginning of the line, making the next print overwriting what's already printed:

import time
import sys
for i in range(100):
    print i,
    sys.stdout.flush()
    time.sleep(1)
    print "\r",
piquadrat
is this platform independent?
klez
@klez: probably not for all terminals. It works for typewriters. Is that platform independent enough for you? :)
Muhammad Alkarouri
On the two platforms at my disposal (Linux and Windows), it works.
piquadrat
@piquadrat: I don't have access to Windows at the moment. Can you please test if the recipe in my answer works there? If you don't have the time don't bother, I am sure I will come across a Windows machine soon.
Muhammad Alkarouri
@Muhammad Alkarouri LOL :D
klez