How to avoid ^C getting printed after handling KeyboardInterrupt
This morning I decided to handle keyboard 开发者_C百科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)
I don't know if this is the best way of doing this, but I fix that problem by printing two \b
(backspace escape sequence) and then a space or a series of characters. This might work fine
if __name__ == "__main__":
try:
# Your main code goes here
except KeyboardInterrupt:
print("\b\bProgram Ended")
精彩评论