4

I have just learned about SIGPIPE, and then read about how to handle these in Python.

Among other sources, I have read: How to handle a broken pipe (SIGPIPE) in python?

Let's say that the pipe reading script exits, then all the answers suggest that the writing script wrappes its write calls in a try clause.

However, I can not make this work. This is my code:

# printer.py
import time
try:
    for i in range(10):
        time.sleep(1)
        print i
except:
    print 'We caught the problem'

and

#nonreader.py
#read nothing, but stay alive for 5 sec
import time, sys
time.sleep(5)
sys.exit(0)

And in the shell:

$ python printer.py | python nonreader.py 
close failed in file object destructor:
Error in sys.excepthook:

Original exception was:

Obviously, nothing was caught. And furthermore, it looks really wrong, when it prints 'Original exception was:' and then no more.

What is wrong / what have I misunderstood?

Thomas

Community
  • 1
  • 1
Mads Skjern
  • 5,648
  • 6
  • 36
  • 40

1 Answers1

5

Since you are writing such a small amount of data, it is all buffered and nothing is actually written to the pipe until the file is closed. During the close, an attempt is made to write data to the pipe, which fails, but your try/except clause is already done. If you flush stdout during your try/except, you should catch the error. (Although, since you are writing to the pipe in the except clause, you won't see it!)

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • That makes sense, thanks :) But I don't like the concept, that an exception can sort of "occur after the code". That way I have no way of catching that exception. Let's say I didn't know about the flush-thing and I just wanted to catch whatever problem in this script, and write it to a log. – Mads Skjern Jul 01 '11 at 08:35
  • The problem is actually related to failing to close the file explicitly. If you close the file (rather than just exiting and letting the system close it for you) you will catch the error at that point. – William Pursell Jul 01 '11 at 17:56
  • Thanks for your answer, in my problem all I had to do was flush the write end of the pipe, then the close worked fine. – ihatecache Jun 11 '14 at 14:04