Replace console output in Python

Replace console output in Python

python overwrite multiple lines
python clear console
overwrite print python
python progress bar
how to delete printed text in python
python print replace same line
delete from console python
python console progress bar

I'm wondering how I could create one of those nifty console counters in Python as in certain C/C++-programs.

I've got a loop doing things and the current output is along the lines of:

Doing thing 0
Doing thing 1
Doing thing 2
...

what would be neater would be to just have the last line update;

X things done.

I've seen this in a number of console programs and am wondering if/how I'd do this in Python.


An easy solution is just writing "\r" before the string and not adding a newline; if the string never gets shorter this is sufficient...

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

Slightly more sophisticated is a progress bar... this is something I am using:

def startProgress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def endProgress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

You call startProgress passing the description of the operation, then progress(x) where x is the percentage and finally endProgress()

10.2. Standard input, output, and error, will simply start from where the previous one started. For a Windows terminal try the console module For unix the curses module would do. This is how you do it on Windows. c = Console.getconsole() c.text(0, -1, 'And this is the string at the bottom of the console') By specifying -1 for the second argument, string goes at bottom line. For Linux, a working code which prints at last line.


A more elegant solution could be:

def progressBar(current, total, barLength = 20):
    percent = float(current) * 100 / total
    arrow   = '-' * int(percent/100 * barLength - 1) + '>'
    spaces  = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')

call this function with value and endvalue, result should be

Progress: [------------->      ] 69 %

Note: Python 2.x version here.

How to overwrite the previous print to stdout in python?, Replacing console output. I don't know if this is the right sub, but here goes anyway. I'm looking for a way to replace already outputted text. For example, rather  Writing Output to the Console. In addition to obtaining data from the user, a program will also usually need to present data back to the user. You can display program data to the console in Python with print(). Unformatted Console Output. To display objects to the console, pass them as a comma-separated list of argument to print().


In python 3 you can do this to print on the same line:

print('', end='\r')

Especially useful to keep track of the latest update and progress.

I would also recommend tqdm from here if one wants to see the progress of a loop. It prints the current iteration and total iterations as a progression bar with an expected time of finishing. Super useful and quick. Works for python2 and python3.

How to delete the last printed line in Python language, If you need to edit output you should think about changing your methods, for example, replace text output with logging into a database. Nevertheless, the terminal  Here's 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 ( ) 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.


The other answer may be better, but here's what I was doing. First, I made a function called progress which prints off the backspace character:

def progress(x):
    out = '%s things done' % x  # The output
    bs = '\b' * 1000            # The backspace
    print bs,
    print out,

Then I called it in a loop in my main function like so:

def main():
    for x in range(20):
        progress(x)
    return

This will of course erase the entire line, but you can mess with it to do exactly what you want. I ended up make a progress bar using this method.

Replacing console output : Python, Replace console output in Python. I'm wondering how I could create one of those nifty console counters in Python as in certain C/C++-programs. I've got a loop  Well, there a number of ways to specify a new line in different areas in python. Python New Line Character. For most of the purposes, the newline character can be used to specify a new line. You can put this character within Python Strings. An example of using character in a string to display output to the console screen is given below.


For anyone who stumbles upon this years later (like I did), I tweaked 6502's methods a little bit to allow the progress bar to decrease as well as increase. Useful in slightly more cases. Thanks 6502 for a great tool!

Basically, the only difference is that the whole line of #s and -s is written each time progress(x) is called, and the cursor is always returned to the start of the bar.

def startprogress(title):
    """Creates a progress bar 40 chars long on the console
    and moves cursor back to beginning with BS character"""
    global progress_x
    sys.stdout.write(title + ": [" + "-" * 40 + "]" + chr(8) * 41)
    sys.stdout.flush()
    progress_x = 0


def progress(x):
    """Sets progress bar to a certain percentage x.
    Progress is given as whole percentage, i.e. 50% done
    is given by x = 50"""
    global progress_x
    x = int(x * 40 // 100)                      
    sys.stdout.write("#" * x + "-" * (40 - x) + "]" + chr(8) * 41)
    sys.stdout.flush()
    progress_x = x


def endprogress():
    """End of progress bar;
    Write full bar, then move to next line"""
    sys.stdout.write("#" * 40 + "]\n")
    sys.stdout.flush()

How to overwrite previous printed lines in Python 3.6.5, I'd like to have a function that replaces a line in the output with [ edit ] Unfortunatly, this doesn't work in Sololearn terminal output emulator ^^. Read String from Console as Input using Python. To read a string from console as input to your Python program, you can use input() function. input() can take an argument to print a message to the console, so that you can prompt the user and let him/her know what you are expecting.


Replace console output in Python, Don't allow the printed line length to exceed the Terminal/Command Prompt width. This method breaks if the line wraps. Retrieve the maximum  Following is the syntax for replace() method − str.replace(old, new[, max]) Parameters. old − This is old substring to be replaced. new − This is new substring, which would replace old substring. max − If this optional argument max is given, only the first count occurrences are replaced. Return Value


Python: replacing output lines?, What I would like to do is instead of printing a newline, I want to replace the previous Replacing console output : Python, I could redirect the interpreter's stdout  This course will introduce you to strings and console output in Python. Start Strings & Console Output we used the % operator to replace the %s placeholders with


Python dynamically updating in-place Terminal text, Most often, we print data to console. Be it the result we want to display, or intermediate results that we want to check. To print a string to console output, you can  Python | Output Formatting There are several ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use. Sometimes user often wants more control the formatting of output than simply printing space-separated values.