程式扎記: [ Python 常見問題 ] How do I capture SIGINT in Python?

標籤

2015年5月26日 星期二

[ Python 常見問題 ] How do I capture SIGINT in Python?

Source From Here 
Question 
I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C signal, and I'd like to do some cleanup. In Perl I'd do this: 
  1. $SIG{'INT'} = 'exit_gracefully';  
  2.   
  3. sub exit_gracefully {  
  4.     print "Caught ^C \n";  
  5.     exit (0);  
  6. }  
How do I do the analogue of this in Python? 

How-To 
Register your handler with signal.signal like this: 
  1. #!/usr/bin/env python  
  2. import signal  
  3. import sys  
  4. def signal_handler(signal, frame):  
  5.         print('You pressed Ctrl+C!')  
  6.         sys.exit(0)  
  7. signal.signal(signal.SIGINT, signal_handler)  
  8. print('Press Ctrl+C')  
  9. signal.pause()  
Code adapted from here

More documentation on module signal can be found here

Supplement 
Tutorialspoint - Unix - Signals and Traps 

沒有留言:

張貼留言

網誌存檔