話不多說先上一段代碼
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
每次只輸出一行信息,每秒更新一次