Last active
January 13, 2018 02:46
-
-
Save yig/f0407c956591be4800ac46d5d4d0b907 to your computer and use it in GitHub Desktop.
How to handle control-C when piping output to tee from Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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