话不多说先上一段代码
import time from datetime import datetime as dt for i in range(5): print(dt.now()) time.sleep(1)
输出结果为:
2019-07-31 11:40:00.334841 2019-07-31 11:40:01.335235 2019-07-31 11:40:02.335700 2019-07-31 11:40:03.335846 2019-07-31 11:40:04.336174
可见每打印一条时间信息都会另起一行打印下一条,这是为什么呢?
让我们在代码中执行help(print)语句得到如下信息
Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
可见每次执行print函数,结尾都会执行换行。如果我们想每次输出新的时间信息的同时覆盖原时间信息该怎么做呢?
这时我们可以用sys.stdout.write函数:
import time from datetime import datetime as dt import sys while True: sys.stdout.write('\r{0}'.format(dt.now())) sys.stdout.flush() time.sleep(1)
效果:
2019-07-31 13:45:15.537898
每次只输出一行信息,每秒更新一次