简体   繁体   中英

Stop the program execution after some time interval

I have the following code and I want to stop the program if the condition is not true for a certain period of time. Suppose the condition (sum>99999) is false for a period of 10 seconds, then this program stops and gives present sum values. I am on Windows. Any idea how to do it in Windows.

for j in i:            
        sum=sum+A[j]          

    if(sum>99999):
        print("Current sum is",sum)

This should accomplish what you're describing.

import time
import sys

start_time = time.time()
for j in i:            
    sum = sum + A[j]          

    if sum > 99999:
        print("Current sum is ", sum)
        start_time = time.time() # reset timer if the condition becomes true
    elif time.time() - start_time >= 10:
        print("Current sum is ", sum)
        sys.exit()

Try this:

import time
import sys

start = time.time()
for j in i:
    sum += A[j]
    if sum > 99999:
        print(sum)
    elif time.time() - start > 10:
        print(sum)
        break # if you just want to exit the loop or sys.exit() if you want to exit the program

Sometimes an iteration is heavy enough to render technique proposed by other answers pretty useless. If you don't have access to break execution upon condition, this or that recipes would be helpful.

I will copy the simpler one (and the one I prefer in my code):

import threading
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    class InterruptableThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.result = None

        def run(self):
            try:
                self.result = func(*args, **kwargs)
            except:
                self.result = default

    it = InterruptableThread()
    it.start()
    it.join(timeout_duration)
    if it.isAlive():
        return default
    else:
        return it.result
import sys
import time

start_time = time.time()
time_limit = 2

if (comdition):
    if((time.time() - start_time) > time_limit):
        sys.exit()
else:
    #more stuff here

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM