Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script avoid quitting when Ctrl-C is pressed

Tags:

python

I'm trying to run WifiPhisher for educational purposes. At one step it says Press Ctrl-C to input a number. Now when I press Ctrl-c the script exits as I described it in this issue on github. Whereas ideally, the script shouldn't exit rather it should continue the logic after Ctrl-C is pressed. I'm not familiar with Python, can anyone help me get past this?

like image 764
user3677331 Avatar asked Aug 13 '15 08:08

user3677331


People also ask

How do you Ctrl-C in Python script?

Python allows us to set up signal -handlers so when a particular signal arrives to our program we can have a behavior different from the default. For example when you run a program on the terminal and press Ctrl-C the default behavior is to quit the program.

Why does Ctrl-C not kill Python running in terminal?

It's because of the design of the Python interpreter and interactive session. Ctrl + C sends a signal, SIGINT, to the Python process, which the Python interpreter handles by raising the KeyboardInterrupt exception in the currently-running scope.

How do you exit a Python script gracefully?

To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program running. It is the most reliable, cross-platform way of stopping code execution.


1 Answers

You can set a signal handler to CTRL-C signal to shutdown the default signal handler which raises a KeyboardInterrupt exception.

import signal, os

def handler(signum, frame):
    print 'Signal handler called with signal', signum

# Set the signal handler
signal.signal(signal.SIGINT, handler)

Ctrl-C (in older Unixes, DEL) sends an INT signal (SIGINT); by default, this causes the process to terminate

SIGINT The SIGINT signal is sent to a process by its controlling terminal when a user wishes to interrupt the process. This is typically initiated by pressing Control-C, but on some systems, the "delete" character or "break" key can be used.[6]

https://docs.python.org/2/library/signal.html

like image 163
luoluo Avatar answered Oct 05 '22 04:10

luoluo