The problem is due to SIGPIPE handling. You can solve this problem using the following code:
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
Update: As pointed out in the comments, python docs already have a good answer.
See here for background on this solution. Better answer here.