python - 经过一段时间后中止循环
问题描述
我有一个可能会陷入长循环的代码。这些不是无限循环,但某些输入可能会导致循环持续很长时间。我希望使用中断以防循环太长。有了这个中断,循环将重新评估它的输入,所以键盘中断不是我想要的。我在 Windows 上使用 python 2.7。
一种可能的方法是使用 time.time() 进行轮询,但效率极低。循环本身并不长,但是即使在正常运行中它也会迭代 100k 次,所以我无法在每次迭代后轮询时间,这会大大降低效率。或者,我可以介绍更多变量,
i=0
while i<some_very_large_number:
function(foo, foo1, foo2)
i=i+1
但这又是一个平庸的解决方案。
简而言之,我要找的是一些相当于微处理器硬件中断的python。我没有多线程的经验,所以如果答案在于多线程,请详细说明。
我在这里和这里检查过,但我认为他们没有回答我的问题。第二个链接实际上可以提供帮助,但显然信号包在 Windows 中不可用。
代码很长但很简单。基本上就是这样的结构。
def function(foo, foo1, foo2, N):
for i in range(N):
performance = performance_evaluator(foo, foo1, foo2)
if performance_takes_too_long:
interrupt ##this if clause is the main objective of this question##
record performance
new_foo, new_foo1, new_foo2 = evolve(foo, foo1, foo2)
解决方案
您还可以在单独的工作进程中执行长时间运行的代码,并在超过超时且工作人员尚未完成时尝试终止它:
import time
from multiprocessing import Process
def process_data():
while True:
print("processing...")
time.sleep(1)
def main():
worker = Process(target=process_data)
worker.start()
timeout = 5
time.sleep(timeout)
if worker.is_alive():
print("exceeded timeout", timeout, "sec")
print("terminate worker", worker)
worker.terminate()
worker.join()
print("is worker", worker, "alive:", worker.is_alive())
if __name__ == "__main__":
main()
这是输出:
processing...
processing...
processing...
processing...
processing...
exceeded timeout 5 sec
terminate worker <Process(Process-1, started)>
is worker <Process(Process-1, stopped[SIGTERM])> alive: False
推荐阅读
- c# - 在使用 asp.net 的 GridView 中显示名称而不是 Id,其值存在于不同的表中
- python - 是否可以在 python-unittest 中生成 Allure 报告?
- python - 如何用 PYSPARK 中的平均值替换空值?
- python - 我怎么能在python中调用一系列没有循环的函数?
- python - 从脚本访问 S3 存储桶,无需重新配置 AWS CLI
- javascript - 防止 Javascript 覆盖 CSS
- python - 使用 OpenCV 的 VideoCapture 和 Python 从视频中抓取慢速图像(帧)
- android - 如何在其他活动中发送价值?
- android - 打开任何类型的文件作为图像
- python - Python 代码在线运行但不在 Jupyter Notebook 中?