main.py:

print("2+2") 

bash:

 $ python3.5 main.py | echo 

Error:

 Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> BrokenPipeError: [Errno 32] Broken pipe 

What is the problem?

With the same bc or wc script works:

 $ python3.5 main.py | bc 4 $ python3.5 main.py | wc 1 1 4 

    1 answer 1

    as far as I understand, there is no “problem” here. at least with the python program.

    when executing the “composite” command, команда1 | команда2 команда1 | команда2 shell creates two processes — one to execute command1 , the second to execute command2 , and the stdout of the first process connects with a pipe (pipe, pipeline) to the stdin of the second process.

    if the second process completes earlier than the first, then for the first process the “pipe” is “broken pipe”.


    in your case, this is exactly what happens: the program (or the built-in function) echo “is not at all interested” in the contents of its stdin , prints an empty line to its stdout and ends. and the python program, having gone through a “long and painful” (in comparison with echo ) loading procedure, finally discovers that “the pipe is broken”. what you and reports. This message it gives to stderr , which is not connected with any “pipes” (it is sent directly to the pseudo-terminal created by the shell), and therefore this message safely reaches your eyes.

    • one
      easy way to reproduce the error: python -c "print('a')" | : python -c "print('a')" | : . Although you can expect (erroneously) that the python process will be killed by a SIGPIPE signal before the BrokenPipeError is noticed (as is the case with most command line utilities). If you restore the default signal handler, then the error is not expected to print: python -c "from signal import *; signal(SIGPIPE, SIG_DFL); print('a')" | : python -c "from signal import *; signal(SIGPIPE, SIG_DFL); print('a')" | : Similar problem: 'yes' reporting error with subprocess communicate () - jfs
    • Thanks for the detailed explanation. - pank