简体   繁体   中英

Dynamic single-line printing in Python (time?)

I'd like to make a simple clock (CLI) that prints the time into one line, and updates it every second. Is this even possible? Should I just print a new line every second?

This is what I have at the moment, which functions terribly:

import calendar, time

a = 1
while a == 1:
    print (calendar.timegm(time.gmtime()))

print function print newline ( \\n ) after the string you passed. Specify carriage return ( \\r ) explicitly does what you want.

To print every second, call time.sleep(1) after printing.

import calendar
import time

while 1:
    print(calendar.timegm(time.gmtime()), end='\r')
    time.sleep(1)

UPDATE

To make cursor remains at the end of the line, prepend \\r :

print('\r', calendar.timegm(time.gmtime()), sep='', end='')

If I understand, what you want to do is write the time, then, a second later, overwrite it with the new time, and so on.

On most terminals, printing a carriage return without a newline will take you back to the start of the same line. So, you can almost just do this:

print('\r{}'.format(calendar.timegm(time.gmtime())), end='')

In general, there's a problem with this: the carriage return doesn't erase the existing text, it just lets you overwrite it. So, what happens if the new value is shorter than the old one? Well, in your case, that isn't possible; you're printing a 10-digit number that can never turn into a 9-digit number. But if it were a problem, the easiest solution would be to change that {} to something like {<70} , which will pad a short line with spaces, up to 70 characters. (Of course if your lines could be longer than 70 character, or your terminal could be narrower than 70, don't use that number.)


Meanwhile, if you just do this over and over as fast as possible, you're wasting a lot of CPU and I/O, and possibly screwing up your terminal's scrollback buffer, and who knows what else. If you want to do this once per second, you should sleep for a second in between.

So:

while True:
    print('\r{}'.format(calendar.timegm(time.gmtime())))
    time.sleep(1)

If you want to get fancy, you can take over the whole terminal with curses on most non-Windows platforms, msvcrt console I/O on Windows, or even manually printing out terminal escape sequences. But you probably don't want to get fancy.

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