Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print only prints after functions are finished executing [duplicate]

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?

like image 699
adele dazim Avatar asked Sep 16 '15 19:09

adele dazim


1 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"
like image 71
poke Avatar answered Oct 21 '22 16:10

poke