4

In my python code having:

print "Hello" time.sleep(20) print "world" 

I am expecting output as

Hello 

and then after 20 seconds

world 

But Hello and world are printing simultaneously in the console.

5
  • 3
    By "at the same time", do you mean without any delay at all, or are they both delayed together? Also, please provide an exact and complete example (this is not a complete example, because it's missing an import), and verify that that example reproduces the issue. Commented May 13, 2013 at 12:03
  • Is time.sleep() expecting seconds or milliseconds? Commented May 13, 2013 at 12:04
  • Maybe you have not imported time, so instead of waiting 20 seconds there is a NameError. Commented May 13, 2013 at 12:07
  • 3
    @Patashu Then why would it ever print "world" at all? Why doesn't it error out at the call to time.sleep(20) with a NameError? I don't think that's the problem. Commented May 13, 2013 at 12:10
  • python code imported with sys,os and time module.time.sleep(20) it is in 20 seconds.First am expecting "Hello" and after 20 seconds "world" in the console. Commented May 14, 2013 at 4:27

3 Answers 3

5

print operator effectively uses sys.stdout stream for output which is buffered. For real-time output you'll want to use sys.stderr stream which is not buffered:

import sys, time sys.stderr.write("Hello ") time.sleep(20) sys.stderr.write("world\n") 

Alternatively, you can flush stream buffer manually by calling sys.stdout.flush() each time you want to get output but I suggest you not to do it in such way unless you know what you're doing.

For more details there is an article in Wikipedia on standard streams (stdin, stdout and stderr).

Sign up to request clarification or add additional context in comments.

Comments

1

Your code works in my computer. You can try to flush the stdout directly after printing hello

import sys sys.stdout.flush() 

1 Comment

My code has so many print commands.So I have to give "sys.stdout.flush()" after every print command.Is there any other way ??
-1

Make sure you've imported the time library from python, and try it on both versions of python to see if you can experience the same error. I've tried it on my end and it works.

1 Comment

It would throw an error when trying to run time.sleep() if it was not imported.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.