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 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...