How to skip to the next input if time is out in python
我有一个输入列表,比如
我有一个
1 2 3 | for f in fruits: mix(f) print"Finish mixing f" |
我的问题是,如果当前输入时间太长,如何跳到下一个输入。例如,mix()正在与苹果合作,但是10分钟过去了,它没有到达打印行。我想让它放弃苹果,如果时间不多就吃香蕉。我该怎么做?
一般化一点,您希望在一段时间内执行一些操作极限。如果操作在达到时间限制之前完成,则很好。如果没有,您希望操作被中断,并执行传递给接下来发生的一切。
这表明我们希望建立一个
此问题未指定平台。我不能提供代码窗户。这个问题和另一个问题似乎对那。
在Unix下,我们设置了一个信号处理函数,它将异常;告诉python在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #!/usr/bin/env python2 import signal from time import sleep # only needed for testing timelimit_seconds = 3 # Must be an integer # Custom exception for the timeout class TimeoutException(Exception): pass # Handler function to be called when SIGALRM is received def sigalrm_handler(signum, frame): # We get signal! raise TimeoutException() # Function that takes too long for bananas and oranges def mix(f): if 'n' in f: sleep(20) else: sleep(0.5) fruits = ['apple', 'banana', 'grape', 'strawberry', 'orange'] for f in fruits: # Set up signal handler for SIGALRM, saving previous value old_handler = signal.signal(signal.SIGALRM, sigalrm_handler) # Start timer signal.alarm(timelimit_seconds) try: mix(f) print f, 'was mixed' except TimeoutException: print f, 'took too long to mix' finally: # Turn off timer signal.alarm(0) # Restore handler to previous value signal.signal(signal.SIGALRM, old_handler) |