python – Output to the same line overwriting previous output?

python – Output to the same line overwriting previous output?

Heres code for Python 3.x:

print(os.path.getsize(file_name)/1024+KB / +size+ KB downloaded!, end=r)

The end= keyword is what does the work here — by default, print() ends in a newline (n) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, theres no need to import the sys module for this sort of simple usage. print() actually has a number of keyword arguments which can be used to greatly simplify code.

To use the same code on Python 2.6+, put the following line at the top of the file:

from __future__ import print_function

If all you want to do is change a single line, use r. r means carriage return. Its effect is solely to put the caret back at the start of the current line. It does not erase anything. Similarly, b can be used to go one character backward. (some terminals may not support all those features)

import sys

def process(data):
    size_str = os.path.getsize(file_name)/1024, KB / , size, KB downloaded!
    sys.stdout.write(%sr % size_str)
    sys.stdout.flush()
    file.write(data)

python – Output to the same line overwriting previous output?

Have a look at the curses module documentation and the curses module HOWTO.

Really basic example:

import time
import curses

stdscr = curses.initscr()

stdscr.addstr(0, 0, Hello)
stdscr.refresh()

time.sleep(1)

stdscr.addstr(0, 0, World! (with curses))
stdscr.refresh()

Leave a Reply

Your email address will not be published. Required fields are marked *