在 Python 中暫停程式執行
Muhammad Waiz Khan
2023年1月30日
Python
Python Pause

本教程將演示 Python 中暫停程式的各種方法。
暫停程式的執行或應用在不同的場景下使用,比如當一個程式需要輸入使用者時。我們也可能需要暫停程式幾秒鐘,讓使用者閱讀一些重要的資訊或指令,然後再進行程式。當我們需要確保使用者在選擇他/她希望程式採取的動作之前閱讀指令時,暫停程式也是很有用的。
我們可以使用不同的方法為一些特定的時間長度或一些輸入暫停程式,下面將對這些方法進行解釋。
在 Python 中使用 time.sleep()
方法暫停程式
time.sleep(secs)
方法在提供的秒數 secs
內暫停給定執行緒的執行。
因此,如果我們需要暫停程式的執行,可以通過向 time.sleep()
方法提供以秒為單位的時長來實現。下面的示例程式碼演示瞭如何使用 time.sleep()
方法來暫停一個 Python 程式。
import time
time_duration = 3.5
time.sleep(time_duration)
在 Python 中使用 input()
函式暫停程式
Python 3 中的 input()
函式和舊版本中的 raw_input()
函式,從 sys.stdin
中以行的形式接收輸入,並在附加\n
後返回輸入。
如果我們想暫停一個程式以從使用者那裡獲得一些輸入,我們可以使用 input()
或 raw_input()
函式來實現,這取決於 Python 的版本。
示例程式碼 (Python 3):
name = input("Please enter your name: ")
print("Name:", name)
示例程式碼 (Python 2):
name = raw_input("Please enter your name: ")
print("Name:", name)
我們也可以使用這個方法來暫停程式,直到按下Enter鍵。下面的示例程式碼演示瞭如何使用 raw_input()
和 input()
函式來實現這一目的。
示例程式碼 (Python 3):
input("Please press the Enter key to proceed")
示例程式碼 (舊版本):
raw_input("Please press the Enter key to proceed")
在 Python 中使用 os.system("pause")
方法暫停程式
os.system("pause")
方法暫停程式的執行,直到使用者不按任何鍵。下面的示例程式碼演示瞭如何使用 os.system("pause")
方法來暫停一個 Python 程式。
import os
os.system("pause")
注意
此方法只適用於 Windows,不適用於任何其他作業系統。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe