Catch Broken Pipe in Python 2 AND Python 3
You can try using BrokenPipeError
and if it throws a NameError
, then fall back to socket.error
, like this
import socket
try:
expected_error = BrokenPipeError
except NameError:
expected_error = socket.error
And then use it like this
try:
1 == 2
except expected_error as ex:
# Handle the actual exception here
If all you care about are broken pipe errors, then you might want to catch socket.error
and simply check whether it's indeed a broken pipe error.
You can do so using the exception's errno
attribute, which is present in both Python 2 and Python 3, which means, you don't need different Python 2 vs. 3 logic (I'd argue the intent is a little clearer this way):
import socket
import errno
try:
do_something()
except socket.error as e:
if e.errno != errno.EPIPE:
# Not a broken pipe
raise
do_something_about_the_broken_pipe()
If you do care about more than broken pipes, thefourtheye's answer is appropriate and idiomatic.