9

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?

adele dazim
  • 527
  • 9
  • 20
  • it should print the first line, show us more code. – taesu Sep 16 '15 at 19:36
  • more code added @taesu – adele dazim Sep 16 '15 at 19:38
  • The coma at the end of the first `print` makes it so stdout is not flushed. – 301_Moved_Permanently Sep 16 '15 at 19:39
  • @Community: Not a duplicate of [How to flush output of Python print](http://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print) because that one is about flushing and this one about having a `,` at the end of the print in Python2 and no final `print` with a newline. While flushing would solve the issue here by working on the symptoms, the root cause is different. I'd expect Qs on the topic of that comma already, but couldn't find any. – cfi Sep 16 '15 at 21:40

1 Answers1

11
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"
poke
  • 369,085
  • 72
  • 557
  • 602