There is a known issue in Python, where "close failed in file object destructor" when "Broken pipe" happens on stdout - Python tracker Issue 11380; also seen in python - Why does my Python3 script balk at piping its output to head or tail (sys module)? - Stack Overflow.

What I want to do, is printout the same custom message when this problem happens, in both Python 2.7 and Python 3+. So I prepare a test script, testprint.py and run it (snippets shown done in bash, Ubuntu 11.04):

$ cat > testprint.py <<"EOF"
import sys

def main():
  teststr = "Hello " * 5
  sys.stdout.write(teststr + "\n")

if __name__ == "__main__":
  main()
EOF

$ python2.7 testprint.py 
Hello Hello Hello Hello Hello 

$ python2.7 testprint.py | echo

close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr

$ python3.2 testprint.py | echo

Exception IOError: (32, 'Broken pipe') in <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> ignored

As expected from above links, there are two different messages. In Help with a piping error (velocityreviews.com), it is recommended to use sys.stdout.flush() to force Python 2 to register an IOError instead of that message; with that, we have:

$ cat > testprint.py <<"EOF"
import sys

def main():
  teststr = "Hello " * 5
  sys.stdout.write(teststr + "\n")
  sys.stdout.flush()

if __name__ == "__main__":
  main()
EOF

$ python2.7 testprint.py | echo

Traceback (most recent call last):
  File "testprint.py", line 9, in <module>
    main()
  File "testprint.py", line 6, in main
Edit
Report