Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 sleep() problem

I was writing a simple program on Python 3.1 and I stumbled upon this:

If I run this on the IDLE it works as intended - prints "Initializing." and then adds two dots, one after each second, and waits for input.

from time import sleep

def initialize():
    print('Initializing.', end='')
    sleep(1)
    print(" .", end='')
    sleep(1)
    print(" .", end='')
    input()

initialize()

The problem is that when I double-click the .py to execute the file, it runs on python.exe instead of pythonw.exe, and strange things happen: it joins all the sleep() times i.e. makes me wait for 2 seconds, and then prints the whole string Initializing. . . at once. Why does this happen? Is there a way to avoid that happening in the terminal? It works fine if I use the IDLE in both windows and linux.

like image 412
roddds Avatar asked Dec 16 '10 01:12

roddds


People also ask

What does sleep () do in Python?

The sleep() function in python's time module is used to suspend the execution of a program for the given number of seconds. This means that the program is paused for the given time and after that time has passed, the program gets executed automatically.

Is time sleep blocking Python?

The reason you'd want to use wait() here is because wait() is non-blocking, whereas time.sleep() is blocking. What this means is that when you use time.sleep() , you'll block the main thread from continuing to run while it waits for the sleep() call to end. wait() solves this problem.

What is an alternative to sleep in Python?

The Timer is another method available with Threading, and it helps to get the same functionality as Python time sleep. The working of the Timer is shown in the example below: Example: A Timer takes in input as the delay time in Python in seconds, along with a task that needs to be started.


2 Answers

This is because the output is being buffered.

You should add a sys.stdout.flush() after each write

like image 156
John La Rooy Avatar answered Sep 22 '22 05:09

John La Rooy


It sounds like the difference is that stdout is automatically being flushed in IDLE. For efficiency, programming languages often save up a bunch of print calls before writing to the screen, which is a slow process.

Here's another question that has the answer you need: How to flush output of Python print?

like image 32
leoger Avatar answered Sep 21 '22 05:09

leoger