LuukV
LuukV

Reputation: 203

time.sleep() working differently in python shell than in command window

I have this code:

print(nextaction + ' ', end="")
time.sleep(2)
print(nextplayer+"'s ", end="")
time.sleep(1)
print(nextitem + '!')
time.sleep(3) 

When I run this with F5 in the shell, it works properly and pauzes the given amount of seconds. But when I run in the command window, by just double clicking the PGM in the folder, it only does the first pauze (before printing the line) and then prints everything at once.

For clarity, the resulting line is always something like "Kill Mike's dog!". but I want a pauze between each word.

I have no clue why this happens.

Upvotes: 0

Views: 422

Answers (3)

Scorpion_God
Scorpion_God

Reputation: 1499

You need to flush the output, because the command line doesn't automatically do it for you (unless there's a newline, or a certain amount of characters have been written to sys.stdout). The print() function has an optional argument that lets you specify whether to flush it or not.

print(nextaction, end=' ', flush=True)
time.sleep(2)
print(nextplayer, end="'s", flush=True)
time.sleep(1)
print(nextitem+'!', flush=True) # there is a newline, so no need to flush it
time.sleep(3)

Upvotes: 1

Maxime Lorant
Maxime Lorant

Reputation: 36151

The command window has a buffer which is flushed after a certain amount of characters or at each new line. Here you don't have enough character or new line to execute it, so you need to force it:

import sys
print(nextaction + ' ', end="")
sys.stdout.flush()
time.sleep(2)
# Also possible inline through the print function (Python 3 only)
print(nextplayer+"'s ", end="", flush=True)
time.sleep(1)
print(nextitem + '!')  # Should not be useful there, since there is the \n
time.sleep(3) 

See also: How to flush output of Python print?

Upvotes: 2

cadrian
cadrian

Reputation: 7376

You need to flush the output. In the REPL the output is automatically flushed to allow the printing of the prompt.

Upvotes: 1

Related Questions