我们可以使用 time module sleep()函数来暂停我们的程序在指定的秒钟。
Python 等待时间
让我们来看看一个快速的例子,在执行进一步的陈述之前,我们会暂停我们的程序5秒。
1import time
2
3print('Hello There, next message will be printed after 5 seconds.')
4
5time.sleep(5)
6
7print('Sleep time is over.')
当我们运行此程序时,在第一个打印声明和第二个打印声明之间会出现5秒的延迟。
Python 等待用户输入
有时我们希望通过控制台从用户那里获得一些输入。我们可以使用 input() 函数来实现这一点。在这种情况下,程序会无限期地等待用户输入。
1sec = input('Let us wait for user input. Let me know how many seconds to sleep now.\n')
2
3print('Going to sleep for', sec, 'seconds.')
4
5time.sleep(int(sec))
6
7print('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.