sleep()函數(shù)在給定的秒數(shù)內掛起(等待)當前線程的執(zhí)行。
Python有一個名為time的模塊,該模塊提供了一些有用的功能來處理與時間有關的任務。其中一種常用的函數(shù)是sleep()。
sleep()函數(shù)將當前線程的執(zhí)行暫停給定的秒數(shù)。
import time print("立即打印") time.sleep(2.4) print("2.4秒后打印")
該程序的工作原理如下:
"立即打印" 被輸出
暫停(延遲)執(zhí)行2.4秒后。
打印輸出"2.4秒后打印" 。
從上面的示例中可以看到,sleep()以浮點數(shù)作為參數(shù)。
在Python 3.5之前,實際的暫停時間可能小于為time()函數(shù)指定的參數(shù)。
從Python 3.5開始,暫停時間將至少為指定的秒數(shù)。
import time while True: localtime = time.localtime() result = time.strftime("%I:%M:%S %p", localtime) print(result) time.sleep(1)
在上面的程序中,我們計算并打印了無限while循環(huán)內的當前本地時間 。然后,程序等待1秒鐘。同樣,將計算并打印當前的本地時間。這個過程繼續(xù)進行。
當您運行程序時,輸出將類似于:
02:10:50 PM 02:10:51 PM 02:10:52 PM 02:10:53 PM 02:10:54 PM ... .. ...
這是上述程序的稍作修改的更好的版本。
import time while True: localtime = time.localtime() result = time.strftime("%I:%M:%S %p", localtime) print(result, end="", flush=True) print("\r", end="", flush=True) time.sleep(1)
在討論sleep()多線程程序之前,讓我們談談進程和線程。
計算機程序是指令的集合。進程就是這些指令的執(zhí)行。
線程是進程的子集。一個進程可以具有一個或多個線程。
本文上面的所有程序都是單線程程序。這是一個多線程Python程序的示例。
import threading def print_hello_three_times(): for i in range(3): print("Hello") def print_hi_three_times(): for i in range(3): print("Hi") t1 = threading.Thread(target=print_hello_three_times) t2 = threading.Thread(target=print_hi_three_times) t1.start() t2.start()
當您運行程序時,輸出將類似于:
Hello Hello Hi Hello Hi Hi
上面的程序有兩個線程t1和t2。這些線程使用t1.start()和t2.start()語句運行。
請注意,t1和t2同時運行,您可能會獲得不同的輸出。
sleep()函數(shù)將當前線程的執(zhí)行暫停給定的秒數(shù)。
如果是單線程程序,sleep()會中止線程和進程的執(zhí)行。 但是,該函數(shù)在多線程程序中掛起線程而不是整個進程。
import threading import time def print_hello(): for i in range(4): time.sleep(0.5) print("Hello") def print_hi(): for i in range(4): time.sleep(0.7) print("Hi") t1 = threading.Thread(target=print_hello) t2 = threading.Thread(target=print_hi) t1.start() t2.start()
上面的程序有兩個線程。我們已經(jīng)使用了這兩個線程time.sleep(0.5)和time.sleep(0.75)其暫停執(zhí)行的時間分別為0.5秒和0.7秒。