有时我们希望 python 程序在执行下一步之前等待特定的时间。我们可以用时间模块 sleep()函数将我们的程序暂停指定的秒数。
让我们看一个简单的示例,在执行进一步的语句之前,我们将暂停程序 5 秒钟。
import time
print('Hello There, next message will be printed after 5 seconds.')
time.sleep(5)
print('Sleep time is over.')
当我们运行这个程序时,第一个打印语句和第二个打印语句之间会有 5 秒的延迟。
有时我们想通过控制台获取用户的一些输入。我们可以使用 input() 函数来实现这一点。在这种情况下,程序将无限期地等待用户输入。一旦用户提供输入数据并按下回车键,程序将开始执行接下来的语句。
sec = input('Let us wait for user input. Let me know how many seconds to sleep now.\n')
print('Going to sleep for', sec, 'seconds.')
time.sleep(int(sec))
print('Enough of sleeping, I Quit!')
Below short screen capture shows the complete program execution.
Surprising, there is no easy way to wait for user input with a timeout or default value when empty user input is provided. I hope these useful features come in future Python releases.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)