Print without a newline in Python

blue-chart-green-arrow-125x125

With python 3 you can override the print function’s delimiter value to make it null or whatever else you want. But if you’re stuck with 2.5 or 2.6 like the rest of us, you can still print without a newline using sys or print with a coma. Try this on for size:

import sys
sys.stdout.write("x")

The only problem with this is when you want to use it like a progress bar. If you do this in a loop over time, you will get the expected output, but over time it won’t be the way you expected.

import os, time, sys
while not os.path.exists(path):
            time.sleep(1)
            sys.stdout.write(".")
print("Finally there!")

What you might expect is a dot to appear once every second until the path does exist at which time “Finally there!” would append to the dot’s, ending with a newline character.

Wrong.

What you’ll actually find is no output at all until the loop exits. You’ll just pause for awhile, then all the dots and the printed message show up all at once. Hmm I guess stdout is buffered. So to fix this, just flush each time you want to make sure the display is updated.

import os, time, sys
while not os.path.exists(path):
            time.sleep(1)
            sys.stdout.write(".")
            sys.stdout.flush()
print("Finally there!")

………….Finally there!

Yet another way would be to use a coma at the end of a normal print function! I love & hate this method because it’s easily forgotten or overlooked when you’re looking at code later, but it is simpler and cleaner looking.

#!/usr/bin/env python
x = "derp"
print("herp "),
print(x),
print "herpidy ",
print x,
herp derp herpidy derp

Why use ugly system calls when you don’t really need to, right?

Posted by admica   @   24 February 2011

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional