Sese Schneider Sese Schneider - 2 months ago 22
Python Question

Python print on same line after delay

This is my code:

def get(url):
print 'GET: ' + url,
r = requests.get(url)
print 'DONE'
return r

get('https://www.###.com/getfoo')


The output:


GET: https://www.###.com/getfoo DONE




request.get
needs about 5 seconds to get a result. However the output displays after those 5 sec, not the first imedeately and the DONE after 5 seconds.

Why?

Answer

Its bcs print() doen not flush to stdout;

You can do it like this

import requests

from sys import stdout

def get(url):
    stdout.write( 'GET: ' + url+"\n");
    stdout.flush(); # this func() will flush all to stdout
    r = requests.get(url);
    print("DONE");
    return r;

get("http://programmersforum.ru/");