voglio sapere se è possibile prendere un Control-C in pitone nel seguente modo:Capture Control-C in Python
if input != contr-c:
#DO THINGS
else:
#quit
Ho letto su cose con try
e except KeyboardInterrupt
ma' non funziona per me
voglio sapere se è possibile prendere un Control-C in pitone nel seguente modo:Capture Control-C in Python
if input != contr-c:
#DO THINGS
else:
#quit
Ho letto su cose con try
e except KeyboardInterrupt
ma' non funziona per me
Potreste leggere this pagina su gestione delle eccezioni .. E 'dovrebbe aiutare.
Come ha detto @abarnert, fare sys.exit()
dopo except KeyboardInterrupt:
.
Qualcosa di simile
try:
# DO THINGS
except KeyboardInterrupt:
# quit
sys.exit()
È inoltre possibile utilizzare il costruito nel exit()
funzione, ma come @eryksun sottolineato, sys.exit
è più affidabile.
'site.exit' (builtins exit) non verrà definito se Python viene avviato con' -S'. Questo non è comune, ma ancora, 'sys.exit' è più affidabile. Puoi anche usare 'raise SystemExit ([exit_code = 0])'. – eryksun
Dai tuoi commenti, sembra che il tuo unico problema con except KeyboardInterrupt:
è che non sai come farlo uscire quando ricevi quell'interrupt.
Se è così, questo è semplice:
import sys
try:
user_input = input()
except KeyboardInterrupt:
sys.exit(0)
Qualcosa del genere: http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python? –
Sì, ma ho provato a usare 'KeyboardInterrupt' ma invece di uscire, Python esegue le operazioni in' try', che non è quello che voglio. – pauliwago
Di quale piattaforma sei? E quale versione di Python? E stai leggendo l'input tramite 'input' /' stdin.read'/etc., Un 'getch' specifico della piattaforma (se sì, quale?),' Curses', o ...? È generalmente possibile in ogni caso, ma le risposte sono molto diverse tra i casi. – abarnert