Daniel B.
Daniel B.

Reputation: 1273

Why is time.sleep pausing early?

I'm teaching myself python with the aid of Head First Programming.

I thought I might tweak their example more to my liking, but I think I'm missing something about time.sleep.

My code is

print("Welcome to SuperBeans!")
time.sleep(3)
answer = input("Do you need a price now? y/n: ")

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?

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!")

So why is the welcome pausing before I think it should be, and why is the poll() function hanging?

Upvotes: 2

Views: 673

Answers (2)

user9876
user9876

Reputation: 11102

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.

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

Upvotes: 3

Joël
Joël

Reputation: 2822

About why is poll() function hanging, this may be because it stays in the while loop.

So question: is get_price() ever returning something strictly greater than 4.74 ? (hint: print the value returned)

Upvotes: 0

Related Questions