简体   繁体   English

如何在给定时间后终止程序在Python中的运行

[英]How to end program running after given time in Python

I'd like my Python program to run an algorithm for a given number of seconds and then to print the best result so far and to end. 我希望我的Python程序在给定的秒数内运行算法,然后输出到目前为止最好的结果并结束。

What is the best way to do so? 最好的方法是什么?

I tried the following but it did not work(the program kept running after the printing): 我尝试了以下操作,但不起作用(打印后程序继续运行):

def printBestResult(self):
    print(self.bestResult)
    sys.exit()

def findBestResult(self,time):
    self.t = threading.Timer(time, self.printBestResult)
    self.t.start() 

    while(1):
        # find best result

Untested code, but something like this? 未经测试的代码,但是像这样?

import time    
threshold = 60
start = time.time()

best_run = threshold
while time.time()-start < threshold:
   run_start = time.time()
   doSomething()
   run_time = time.time() - start
   if run_time < best_run:
       best_run = run_time

On unix, you can use signals -- This code times out after 1 second and counts how many times it iterates through the while loop in that time: 在unix上,您可以使用信号-此代码在1秒钟后超时,并计算在该时间内遍历while循环的次数:

import signal
import sys

def handle_alarm(args):
    print args.best_val
    sys.exit()

class Foo(object):
    pass

self=Foo() #some mutable object to mess with in the loop
self.best_val=0
signal.signal(signal.SIGALRM,lambda *args: handle_alarm(self))

signal.alarm(1) #timeout after 1 second
while True:
    self.best_val+=1 # do something to mutate "self" here.

Or, you could easily have your alarm_handler raise an exception which you then catch outside the while loop, printing your best result. 或者,您可以轻松地使alarm_handler引发一个异常,然后将其捕获到while循环之外,从而输出最佳结果。

If you want to do this with threads, a good way is to use an Event . 如果要使用线程执行此操作,一个好方法是使用Event Note that signal.alarm won't work in Windows, so I think threading is your best bet unless in that case. 请注意, signal.alarm在Windows中将无法运行,因此除非出现这种情况,否则我认为线程化是您的最佳选择。

import threading
import time
import random

class StochasticSearch(object):
    def __init__(self):
        self.halt_event = threading.Event()

    def find_best_result(self, duration):
        halt_thread = threading.Timer(duration, self.halt_event.set)
        halt_thread.start()
        best_result = 0
        while not self.halt_event.is_set():
            result = self.search()
            best_result = result if result > best_result else best_result
            time.sleep(0.5)
        return best_result

    def search(self):
        val = random.randrange(0, 10000)
        print 'searching for something; found {}'.format(val)
        return val

print StochasticSearch().find_best_result(3)

You need an exit condition, or the program will run forever (or until it runs out of memory). 您需要退出条件,否则程序将永远运行(或直到内存耗尽)。 Add one yourself. 自己添加一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在给定时间后结束 for 循环 - How to end a for loop after a given amount of time 如何在运行时结束python程序? - How to end a python program while it is running? Python - 在给定时间后退出程序的倒数计时器 - Python - Countdown timer that exits program after given time Python多处理程序未运行到最后 - Python multiprocessing program not running to the end Python:如何在用户输入3个无效值后结束程序,并防止以下功能在不使用系统退出/中断的情况下运行? - Python: How to end a program after user inputs 3 invalid values and prevent following functions from running without using system exit/break? 如何结束程序(Python)? - How to end the program (Python)? 如何在Python中运行整个程序后重复程序? - How to repeat program after running the whole program in Python? 在python中,如何在给定的系统时间启动程序? - In python, how can I begin a program at a given system time? Python在某个时间运行程序 - Python running program at a certain time Python:鉴于当前UTC时间,您如何确定特定时区内一天的开始和结束时间? - Python: Given the current time in UTC, how do you determine the start and end time of the day in a particular timezone?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM