简体   繁体   中英

How to rewrite output in terminal

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?

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",

This doesn't clear the line, so if you try to, say, print decreasing numbers using this methods, you'll see leftover text from previous prints. You can work around this by padding out your output with spaces, or using some of the control codes in the other answers.

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.

Using the blessings package - clear your screen (clear/cls) and enter:

import sys
from blessings import Terminal
from time import sleep # <- boy, does this sound tempting a.t.m.

term = Terminal()
for i in range(6):
    with term.location(term.width - 3, term.height - 3):        
        print('{}'.format(i))
    sleep(2)
    if (i == 3):
        print('what was I doing, again?')
print('done')

To install it from CheeseShop, just...

pip install blessings

Based on this answer , but without the terminal controller:

import time
import sys
for i in range(100):
    sys.stdout.write("Downloading ... %s%%\r" % (i))
    sys.stdout.flush()
    time.sleep(1)

Tested on GNOME terminal (Linux) and Windows console.

Tip: Don't run this example in IDLE editor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM