Skip to content

Instantly share code, notes, and snippets.

@rtfpessoa
Created March 19, 2016 11:28
Show Gist options
  • Save rtfpessoa/e3b1fe0bbfcd8ac853bf to your computer and use it in GitHub Desktop.
Save rtfpessoa/e3b1fe0bbfcd8ac853bf to your computer and use it in GitHub Desktop.
Handle CTRL+C in Python
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
@erickinho1bra
Copy link

Thank you for having the simplest solution to handing ctrl+c. People out there complicate things so much! haha

@dematom
Copy link

dematom commented Mar 11, 2020

cool

@leviethung2103
Copy link

Thank you for your code. It works perfectly.

However, I would like to ask you about the function signal_handler. Do we need to define the parameters signal and frame into that function?

What are the meanings of signal and frame in the function?

Thank you in advance.

@rtfpessoa
Copy link
Author

signal_handler is just the fuction you are passing to signal.signal(..) in line 9.
This was done a long time ago, but those are just the parameters that the runtime give you so you can have more context about the signal.

@leviethung2103
Copy link

Yes. I got your points. Thank you so much for this solution.

@mDeram
Copy link

mDeram commented Nov 1, 2020

Perfect solution, still working with python 3.8, thanks.

Copy link

ghost commented Jul 4, 2022

Can confirm, still works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment