2

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?

John Moutafis
  • 22,254
  • 11
  • 68
  • 112
kivagant
  • 1,849
  • 2
  • 24
  • 33

1 Answers1

4

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.

John Moutafis
  • 22,254
  • 11
  • 68
  • 112