如何在处理SIGINT时避免python异常

时间:2018-02-16 08:47:15

标签: python python-2.7 sigint

import signal
import time

def sigint_handler(signum, frame):
    print 'User pressed CTRL+C!'

signal.signal(signal.SIGINT, sigint_handler)

def main():
    while True:
       print 'Script to handle SIGINT'
       time.sleep(2)

##########

if __name__ == "__main__":
    main()

如何在执行代码时阻止python本身抛出的异常:

File "D:\Documents\scripts\ctrlc handler.py", line 19, in <module> main() 
File "D:\Documents\scripts\ctrlc handler.py", line 14, in main 
time.sleep(2) OError: [Errno 4] Interrupted function call

1 个答案:

答案 0 :(得分:0)

问题似乎与收到的不同信号和抛出的不同错误有关。另请参阅this以供参考。我可以想到的工作是捕获并忽略抛出的OSError / IOError:

import signal
import time

def sigint_handler(signum, frame):
    print 'User pressed CTRL+C!'

signal.signal(signal.SIGINT, sigint_handler)

def main():
    while True:
       print 'Script to handle SIGINT'
       try:
           time.sleep(2)
       except IOError:
           pass

##########

if __name__ == "__main__":
    main()

完美无缺。

Script to handle SIGINT
User pressed CTRL+C!
Script to handle SIGINT
User pressed CTRL+C!
Script to handle SIGINT
User pressed CTRL+C!
Script to handle SIGINT
User pressed CTRL+C!
Script to handle SIGINT
User pressed CTRL+C!
Script to handle SIGINT
User pressed CTRL+C!
Script to handle SIGINT
User pressed CTRL+C!
Script to handle SIGINT
User pressed CTRL+C!