Python 讓程式 sleep 延遲暫停時間

本篇 ShengYu 將介紹如何使用 Python 讓程式 sleep 延遲暫停時間。

time.sleep 函式會延遲暫停當前的執行緒,延遲暫停多久取決於帶入的參數,
設定單位是秒,可以接受浮點數,也就是說我想要延遲暫停 1.5 秒的話是可以的,範例如下:

1
2
3
4
5
6
7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time

print("sleep 1.5 seconds.")
time.sleep(1.5)
print("printed after 1.5 seconds.")

輸出如下:

1
2
sleep 1.5 seconds.
printed after 1.5 seconds.

以上就是如何使用 Python 讓程式延遲 / 暫停 / 睡眠的方法。

參考
[1] How can I make a time delay in Python? - Stack Overflow
https://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 計算程式執行時間
Python 取得系統當前時間
Python 新手入門教學懶人包
Python str 字串用法與範例
Python list 串列用法與範例
Python set 集合用法與範例
Python dict 字典用法與範例
Python tuple 元組用法與範例