2011-10-01 28 views
9

Questa mattina ho deciso di gestire l'interrupt di tastiera nel mio programma server e di uscire con garbo. So come farlo, ma il mio pignolo non l'ha trovato abbastanza grazioso che lo ^C venga ancora stampato. Come evitare di stampare ^C?Come evitare che^C venga stampato dopo aver gestito KeyboardInterrupt

import sys 
from time import sleep 
try: 
    sleep(5) 
except KeyboardInterrupt, ke: 
    sys.exit(0) 

Premere Ctrl + C per uscire del programma di cui sopra e vediamo ^C sempre stampate. C'è qualche magia sys.stdout o sys.stdin che posso usare?

+0

Si potrebbe provare a utilizzare qualcosa nel [ 'pacchetto curses'] (http://docs.python.org/library/curses .html), ma non penso che sia banale (se è possibile a tutti). –

+0

su Windows Non vedo^C. – akonsu

+1

Vedo^C stampato su bash e csh, o coerente con shell o qualcosa a un livello inferiore (kernel). –

risposta

0

Questo farà il trucco, almeno 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) 
7

È la tua shell che lo fa, Python non ha nulla a che fare con esso.

Se metti la seguente riga in ~/.inputrc, sarà sopprimere quel comportamento:

set echo-control-characters off 

Naturalmente, sto supponendo che si sta utilizzando bash che non può essere il caso.

0
try: 
    while True: 
     pass 
except KeyboardInterrupt: 
    print "\r " 
Problemi correlati