0

Currently, I have the following code in a script:

print "Loading... "
html = urllib2.urlopen(url).read()
print "Done"

That works great, it displays loading, pauses while the download completes, and then displays done. The only problem is, the "done" is on the next line.

Ideally, it would be on the same line, so I would get Loading... (pause) done

I tried adding a comma onto the end of the first print statement, but although that achieves the desired output, it doesn't output any of the string until it has loaded the HTML, because the comma tells python to wait until a completing print statement (at least I think it does).

So how can I print the "Loading" and "done" on the same line, while still being able to output them independently?

6 Answers 6

6

Standard output is line buffered, you have to flush it:

sys.stdout.flush()
Sign up to request clarification or add additional context in comments.

Comments

3

use could use the sys module

sys.stdout.write("plop")

1 Comment

nope there is not system file object (stdin, stdout, stderr) in the os odule
3

Calling flush() on sys.stdout seems to have the desired effect, with the 'load' simulated by sleep():

#!/usr/bin/env python

from sys import stdout
from time import sleep

print "Loading... ",
stdout.flush()
sleep(5)
print "Done"

So, while it is printing using ,, which you say you don't want to do in your question, it does solve the problem.

Comments

2

Try this:

import sys
print "Loading... ",
sys.stdout.flush()
html = urllib2.urlopen(url).read()
print "Done"

Comments

2

This way also works, though it has the downside of requiring Python 3 print syntax thereafter...

 from __future__ import print_function

 print("Loading...", end=" ")
 html = urllib2.urlopen(url).read()
 print("Done")

Comments

0

print("stack",end="")
print("overflow")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.