Output to the same line as overwriting the previous one

how to get output in one line by overwriting the previous received time (countdown) by the NTP server. As shown below after every second time selection in the next line.

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

I want the time to be taken in the same clear the previous line.

+11
source share
3 answers

You can use "return" -character \r to return to the beginning of the line . In Python 2.x, you will need 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 the end and flush options:

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

Please note that this way you can replace only the last line on the screen. If you want to have a live clock in a more complex console-only user interface, you should check 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) 
+21
source

I am using python 2.7

 python --version Python 2.7.12 :: Anaconda 4.1.1 (64-bit) 

and I use this function as a hook to display the loading process using urllib.urlretrieve

 def hook(bcount , bsize, tsize ): str = "[ %3d%% of %10d] \r" % (bcount * bsize * 100/tsize , tsize) print str, urllib.urlretrieve (url, file_name, hook) 

Explanation: \ r places the cursor at the beginning of the line, and the comma does not print on a new line, if you have the same number of characters for each print, this will do the trick

if you are interested in learning about urllib and the hook I use, you will find the document https://docs.python.org/2/library/urllib.html

0
source

This will work as a champion:

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

output:

The same output of the Tirumalai line from the first line

0
source

Source: https://habr.com/ru/post/977270/


All Articles