输出到同一行覆盖以前的 [英] Output to the same line overwriting previous
问题描述
如何通过覆盖 NTP 服务器先前接收到的计时(倒计时)来将输出输出到同一行.如下图所示,每秒钟接收下一行后.
how to get output to the same line by overwriting previous received Timing(countdown) by NTP server. As shown below after each second timing is receiving in next row.
13:35:01
13:35:00
13:34:59
13:34:58
13:34:57
13:34:56
我希望时间应该在清除前一个的同一行中接收.
I want timing should be received in same row clearing previous one.
推荐答案
您可以使用返回"字符\r
返回到行首.在 Python 2.x 中,您必须使用 sys.stdout.write
和 sys.stdout.flush
而不是 print
.>
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)
在 Python 3.3 中,您可以使用 print
函数,带有 end
和 flush
参数:
In Python 3.3, you can use the print
function, with end
and flush
parameters:
print(time.ctime(), end="\r", flush=True)
但是请注意,这种方式只能替换屏幕上的最后一行.如果您想在更复杂的仅限控制台的 UI 中使用实时"时钟,您应该查看 诅咒
.
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)
这篇关于输出到同一行覆盖以前的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!