Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output to the same line overwriting previous

Tags:

python

How to print the output on the same line by overwriting the previously printed Timing(countdown) value?

As shown below, after each second, the timing value is printed on the next row.

13:35:01  13:35:00  13:34:59  13:34:58  13:34:57  13:34:56 

I want the timing value to be printed on the same row clearing the previous one.

like image 623
Prashant sharma Avatar asked Oct 27 '14 08:10

Prashant sharma


People also ask

How do I display output on the same line?

Modify print() method to print on the same line The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.

How do you overwrite output in Python?

Approach. By default, Python's print statement ends each string that is passed into the function with a newline character, \n . This behavior can be overridden with the function's end parameter, which is the core of this method. Rather than ending the output with a newline, we use a carriage return.

How do you print overwrite on the same line in Python?

Summary: The most straightforward way to overwrite the previous print to stdout is to set the carriage return ( '\r' ) character within the print statement as print(string, end = "\r") . This returns the next stdout line to the beginning of the line without proceeding to the next line.

How do you overwrite the previous print to stdout in Python?

Simple Version. One way is to use the carriage return ( '\r' ) character to return to the start of the line without advancing to the next line.


2 Answers

You can use the "return"-character \r to return to the beginning of the line. In Python 2.x, you'll have to use sys.stdout.write and sys.stdout.flush instead of print.

import time, sys while True:     sys.stdout.write("\r" + time.ctime())     sys.stdout.flush()     time.sleep(1) 

In Python 3.3, you can use the print function, with end and flush parameters:

    print(time.ctime(), end="\r", flush=True) 

Note, however, that this way you can only replace the last line on the screen. If you want to have a "live" clock in a more complex console-only UI, you should check out curses.

import time, curses scr = curses.initscr() scr.addstr(0, 0, "Current Time:") scr.addstr(2, 0, "Hello World!") while True:     scr.addstr(0, 20, time.ctime())     scr.refresh()     time.sleep(1) curses.endwin() 
like image 80
tobias_k Avatar answered Oct 11 '22 14:10

tobias_k


This will work like a champ:

print("This text is about to vanish - from first line", end='') print("\rSame line output by Thirumalai") 

output:

Same line output by Thirumalai from first line

like image 44
Thirumalai Parthasarathy Avatar answered Oct 11 '22 13:10

Thirumalai Parthasarathy