Python中的动态单行打印(时间?) [英] Dynamic single-line printing in Python (time?)

查看:394
本文介绍了Python中的动态单行打印(时间?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个简单的时钟(CLI),将时间打印成一行,并每秒更新一次。这是甚么可能吗?我应该每秒打印一个新的行吗?

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()))


推荐答案

如果我明白,你想要什么做是写时间,然后一秒钟,用新的时间覆盖它,等等。

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='')

,这是一个问题:回车不会删除现有的文本,它只是让你覆盖它。那么,如果新值比旧的更短,会发生什么?那么,在你的情况下,这是不可能的;您正在打印一个10位数字,不能变成9位数字。但如果 是一个问题,最简单的解决方案是将 {} 更改为 {< 70 } ,它将用空格填充短行,最多70个字符。 (当然,如果你的线路可能超过70个字符,或者你的终端可能比70更窄,不要使用该号码。)

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.)

同时,如果您尽可能快地做到这一点,您会浪费大量的CPU和I / O,并且可能会拧紧终端的滚动缓冲区,还有谁知道还有什么。如果你想每秒钟这样做一次,你应该在 sleep 之间的一秒钟。

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.

所以: / p>

So:

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






如果你想得到喜好,你可以通过 <$大多数非Windows平台上的c $ c> curses msvcrt 控制台I / O,甚至手动打印终端转义序列。但是你可能不希望看到。


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.

这篇关于Python中的动态单行打印(时间?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆