Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python stdout flush and tee

Tags:

python

tee

The following code ends with broken pipe when piped into tee, but behave correctly when not piped :

#!/usr/bin/python
import sys
def testfun():
    while 1:
        try :
            s = sys.stdin.readline()
        except(KeyboardInterrupt) :
            print('Ctrl-C pressed')
            sys.stdout.flush()
            return
        print s

if __name__ == "__main__":
    testfun()
    sys.exit()

Expected output :

./bug.py 
Ctrl-C pressed

What is observed when piped into tee is either a broken pipe or no output at all, ie nothing on tee stdout, and nothing in bug.log :

./bug.py | tee bug.log
Traceback (most recent call last):
  File "./bug.py", line 14, in <module>
    sys.stdout.flush()
IOError: [Errno 32] Broken pipe

What can be the reason for this ?

like image 476
shodanex Avatar asked Jun 29 '26 23:06

shodanex


1 Answers

Nope, hitting Ctrl-C does NOT terminate both processes. It terminates the tee process only, the end of the tee process close the pipe between your script and tee, and hence your script dies with the broken pipe message.

To fix that, tee has an option to pass the Ctrl-C to its previous process in the pipe: -i

try: man tee

./bug.py
^CCtrl-C pressed
./bug.py | tee log
^CTraceback (most recent call last):
  File "./bug.py", line 14, in <module>
    testfun()
  File "./bug.py", line 9, in testfun
    sys.stdout.flush()
IOError: [Errno 32] Broken pipe

./bug.py | tee -i log
^CCtrl-C pressed
like image 149
GED Avatar answered Jul 02 '26 13:07

GED



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!