How to see print output from generator before endi

2019-05-23 01:51发布

问题:

I'm trying to print debug information inside a generator working with big list of data. But, I can see the result only when the generator finishes.

I am using python 3 and my code is as follows:

def generator():
    while 1:
        print ('.', end='')
        time.sleep(1)
        yield 1

for a in generator():
    print ('|', end='')

Result:

^C.|.|.|.|.|

Equivalent PHP7 code works as expected:

function generator()
{
    while (1) {
        echo '.';
        sleep(1);
        yield 1;
    }
}

foreach (generator() as $item) {
    echo '|';
}

Result:

.|.|.|.|.|^C

How to print debug information in realtime for each iteration of the generator's cycle?

回答1:

TL;DR:

I believe that you have a similar issue to that question: Print statements not working when serve_forever() is called? (although by the title is not apparent...)

Try to flush your prints:

print ('.', end='', flush=True)

print ('|', end='', flush=True)

flush

The method flush() flushes the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.

It forces the print() function to print whatever have been buffered up to that point to the stdout of your machine.