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()
How can I block this below exception thrown by python itself when executing the code:
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
The issue seems to have something to do with different signals being received and different errors being thrown. See also this maybe for reference. The work around I could come up with was to catch and ignore the OSError/IOError that is being thrown like so:
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()
Which works perfectly.
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.