Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid ^C getting printed after handling KeyboardInterrupt

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?

like image 406
Jayesh Avatar asked Oct 01 '11 02:10

Jayesh


3 Answers

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.

like image 150
Chris Eberle Avatar answered Nov 04 '22 15:11

Chris Eberle


try:
    while True:
        pass
except KeyboardInterrupt:
    print "\r  "
like image 29
Valery Mochichuk Avatar answered Nov 04 '22 15:11

Valery Mochichuk


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)
like image 21
Diego Torres Milano Avatar answered Nov 04 '22 13:11

Diego Torres Milano