[Python] How to prevent BrokenPipeError when doing a flush in Python?

Discussão em 'Python' iniciado por Stack, Março 6, 2025.

  1. Stack

    Stack Membro Participativo

    Question: Is there a way to use flush=True for the print() function without getting the BrokenPipeError?

    I have a script pipe.py:

    for i in range(4000):
    print(i)


    I call it like this from a Unix command line:

    python3 pipe.py | head -n3000


    And it returns:

    0
    1
    2


    So does this script:

    import sys
    for i in range(4000):
    print(i)
    sys.stdout.flush()


    However, when I run this script and pipe it to head -n3000:

    for i in range(4000):
    print(i, flush=True)


    Then I get this error:

    print(i, flush=True)
    BrokenPipeError: [Errno 32] Broken pipe
    Exception BrokenPipeError: BrokenPipeError(32, 'Broken pipe') in <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> ignored


    I have also tried the solution below, but I still get the BrokenPipeError:

    import sys
    for i in range(4000):
    try:
    print(i, flush=True)
    except BrokenPipeError:
    sys.exit()

    Continue reading...

Compartilhe esta Página