问题描述
我在 Head First Programming 的帮助下自学 Python.
I'm teaching myself python with the aid of Head First Programming.
我想我可以根据自己的喜好调整他们的例子,但我想我错过了一些关于 time.sleep 的东西.
I thought I might tweak their example more to my liking, but I think I'm missing something about time.sleep.
我的代码是
print("Welcome to SuperBeans!")
time.sleep(3)
answer = input("Do you need a price now? y/n: ")
但不是在欢迎消息后暂停三秒钟,而是等待 3 分钟,然后显示消息和输入请求.我错过了什么?
But rather than pausing for three seconds after the welcome message, it waits 3 minutes, then displays both the message and the input request. What am I missing?
此外,在运行我定义的轮询"功能时,程序似乎无限期挂起,而从未显示轮询..."通知.我知道 get_price() 正在工作,因为它在另一部分打印...
Additionally, the program seems to hang indefinitely when running the "poll" function I defined, without ever displaying the "polling..." notice. I know get_price() is working because it prints it in another section ...
def poll():
price = 99.99
print(price)
while price > 4.74:
print("Polling...")
price = get_price()
time.sleep(5)
print("Buy!")
那么为什么在我认为应该暂停之前欢迎暂停,为什么 poll() 函数挂了?
So why is the welcome pausing before I think it should be, and why is the poll() function hanging?
推荐答案
正如在上面的评论中所讨论的,Python 输出被缓冲,因此程序运行(并在正确的时间休眠等)但您看不到输出一会儿.
As discussed in comments above, Python output is being buffered, so the programs run (and sleeps for the right time etc) but you don't see the output for a while.
如果您从非标准控制台运行 Python,则需要将-u"选项传递给 Python 以禁用缓冲.即:
If you're running Python from a nonstandard console, you need to pass the "-u" option to Python to disable the buffering. I.e.:
python -u foo.py
这篇关于为什么 time.sleep 提前暂停?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!