在 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