Error: BrokenPipeError: [Errno 32] Broken pipe in Python 3

Dung Do Tien Jun 11 2022 515

Hello everyone,  I have a small Python project that needs to run on Linux, it's very simple. I want to read total data from a config file and file what number is odd or even,  It's like this:

main.py

for i in range(1000): # this number will get from Db or config file
    if (i % 2) == 0:
        print( str(i) + " is even")
    else:
        print(str(i) + " is odd")

And from Ubuntu, I run the command:

python3 main.py | head -n3000

But I got an error BrokenPipeError: [Errno 32] Broken pipe.  

0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Traceback (most recent call last)
 File "main.py", line 20, in <module>
   print( str(i) + " is even")
BrokenPipeError: [Errno 32] Broken pipe

Broken pipe error in Python, what is that mean?

I used Linux Ubuntu 20.04 server and Python 3.9.7.

Thank you for any help!!

Have 2 answer(s) found.
  • S

    Seema yadav Solorzano Jun 11 2022

    Sometimes I got the same error. We can handle this type of error by using the functionality of try/catch block which is already approved by the python manual and is advised to follow such procedure to handle the errors. 

    import sys, errno  
    try:  
       # Add your code here
    except IOError as e:  
       if e.errno == errno.EPIPE:  
           # Handling of the error or pass error

    You can see an example here:

    import sys, errno  
    try:  
       for i in range(1000): # this number will get from Db or config file
        if (i % 2) == 0:
            print( str(i) + " is even")
        else:
            print(str(i) + " is odd")
    except IOError as e:  
       if e.errno == errno.EPIPE:  
           pass

    Very simple for you issue!!!

  • A

    Angelo Ribeiro Jun 11 2022

    Hi, to avoid the error we need to make the terminal run the code efficiently without catching the SIGPIPE signal, so for these, we can add the below code at the top of the main.py file.

    from signal import signal, SIGPIPE, SIG_DFL  
    signal(SIGPIPE,SIG_DFL) 

    Full code for you here:

    from signal import signal, SIGPIPE, SIG_DFL  
    signal(SIGPIPE,SIG_DFL) 
    
    for i in range(1000): # this number will get from Db or config file
        if (i % 2) == 0:
            print( str(i) + " is even")
        else:
            print(str(i) + " is odd")

    I hope it is useful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close