This morning I decided to handle keyboard interrupt in my server program and exit gracefully. I know how to do it, but my finicky self didn't find it graceful enough that ^C
still gets printed. How do I avoid ^C
getting printed?
import sys
from time import sleep
try:
sleep(5)
except KeyboardInterrupt, ke:
sys.exit(0)
Press Ctrl+C to get out of above program and see ^C
getting printed. Is there some sys.stdout
or sys.stdin
magic I can use?
It's your shell doing that, python has nothing to do with it.
If you put the following line into ~/.inputrc
, it will suppress that behavior:
set echo-control-characters off
Of course, I'm assuming you're using bash which may not be the case.
try:
while True:
pass
except KeyboardInterrupt:
print "\r "
This will do the trick, at least in Linux
#! /usr/bin/env python
import sys
import termios
import copy
from time import sleep
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = copy.deepcopy(old)
new[3] = new[3] & ~termios.ECHO
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
sleep(5)
except KeyboardInterrupt, ke:
pass
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
sys.exit(0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With