How to avoid ^C getting printed after handling KeyboardInterrupt

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)