[Python] Python: contextlib.redirect_stdout sometimes doesn't work in real time

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Python3.5 on Ubuntu. The following script creates a file out and fills it with more and more lines of "Hello":

    import contextlib
    with contextlib.redirect_stdout(open('out','w')):
    while True:
    print('Hello')


    However, if I make a tiny modification by adding a call to time.sleep(), the file out stays empty:

    import contextlib
    import time
    with contextlib.redirect_stdout(open('out','w')):
    while True:
    print('Hello')
    time.sleep(1)


    If I further change the code by turning the loop into a finite loop, it fills out but only in a lump at the end of the loop.

    Can anyone reproduce this and explain it?

    Continue reading...

Compartilhe esta Página