Jayesh
Jayesh

Reputation: 53345

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?

Upvotes: 9

Views: 2631

Answers (4)

Avneesh Mishra
Avneesh Mishra

Reputation: 558

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")

Upvotes: 0

Valery Mochichuk
Valery Mochichuk

Reputation: 81

try:
    while True:
        pass
except KeyboardInterrupt:
    print "\r  "

Upvotes: 8

Diego Torres Milano
Diego Torres Milano

Reputation: 69396

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)

Upvotes: 1

Chris Eberle
Chris Eberle

Reputation: 48795

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.

Upvotes: 9

Related Questions