Skip to content

Instantly share code, notes, and snippets.

@yig
Last active January 13, 2018 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yig/f0407c956591be4800ac46d5d4d0b907 to your computer and use it in GitHub Desktop.
Save yig/f0407c956591be4800ac46d5d4d0b907 to your computer and use it in GitHub Desktop.
How to handle control-C when piping output to tee from Python.
# Run with
## python -u controlc_pipeline.py | tee foo.out
# Then press control-C.
## You never see the output without an IOError handler,
## because an IOError is generated (stdout went away) before a KeyboardInterrupt.
## You could catch the IOError and redirect stdout manually. UPDATE: That doesn't seem to work.
## Or you could tell `tee` to ignore SIGINT and exit this program gracefully:
# python -u controlc_pipeline.py | tee -i foo.out
from __future__ import print_function, division
from time import sleep
while True:
try:
print( "Awake" )
sleep(1)
## Without this, you'll never catch KeyboardInterrupt
## in a pipeline that's control-C'd.
## UPDATE: This doesn't seem to work either.
except IOError:
import sys
sys.stdout = open( "controlc_pipeline.out", 'a' )
except KeyboardInterrupt:
print( "Control-C" )
break
print( "Goodbye" )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment