如果每次都像这样打印固定长度的输出,那么只要不打印换行符,就可以使用回车字符倒带到行的开头。示例:# Note trailing comma, that suppresses the newline in Python
print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now.second)),
# Now rewind back to the start of the line. Again, not trailing comma
print("\r"),
现在,您可能还注意到屏幕上从未打印过任何内容。这是因为标准输出是缓冲的,所以您可以用它刷新:# At the top...
import sys
# In the loop, after the first print
sys.stdout.flush()
这一切工作如下。假设屏幕上有一个光标。首先用第一次打印(和刷新)打印出时间,然后用print("\r"),将光标移回行的开头。这实际上并没有删除任何字符,只是移动光标。你下次再写一遍。因为它恰好是完全相同的长度,所以时间会再次被写出来,替换旧字符。
结果脚本如下:import time
import sys
while True:
from datetime import datetime
now = datetime.now()
print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now.second)),
sys.stdout.flush()
print("\r"),
time.sleep(1)
如果你想对正在发生的事情进行更细粒度的控制,你可以开始使用curses库,但我认为这对于你在这里所做的工作来说是过分了。
编辑:正如注释中提到的@padraicunningham,在Python 3中禁止换行打印并强制内容刷新到屏幕的正确语法如下:print("hello", flush=True, end="")
另外,正如@AlexHall所提到的,print语句实际上并不打印固定宽度的语句;因此,为此,我们应该使用strftime()。
因此,正确的程序是:import time
while True:
from datetime import datetime,strftime
now = datetime.now()
print (strftime("%m/%d/%Y %H:%M:%S"), end="", flush=True)
print("\r", end="", flush=True)
time.sleep(1)