Print only prints after functions are finished executing

Question:

I have this code:

def get_endpoint(type):
    return "%s/%s.json" % (v2_endpoint,type)

def get_entities(type,endpoint=None,entities=None):
    if not endpoint:
        endpoint=get_endpoint(type)
        entities=[]
    r=requests.get(endpoint,headers=header)
    entities.extend(r.json()[type])
    if not 'next' in r.links:
        return entities
    else:
        return get_entities(type,r.links['next']['url'],entities)

print "Fetching info from New Relic....",
servers = get_entities('servers')
applications = get_entities('applications')
print "Done."

I noticed that it doesn’t print the first and last print statements until it has processed those functions. Expected behaviour, I presume.

So, how do I make it print the first line before it starts processing the function?

Asked By: adele dazim

||

Answers:

print "Fetching info from New Relic....",

The trailing comma means that the print should not add a line break at the end. Most consoles however do not flush the output when there is no line break, so you do not see the output until a line break is also printed.

If you remove the comma, you can see that it will work.

However, you can manually flush the output without printing a new line character. But you need to do that manually:

import sys
print "Fetching info from New Relic....",
sys.stdout.flush()

# do stuff
print "Done"
Answered By: poke
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.