简体   繁体   English

如果花费很长时间,python超时功能

[英]python timing out of a function if takes a long time

Let's say I have a function 假设我有一个功能

def may_take_a_long_time():
    while 1:
        # do something
        if met_condition():
            break

timeout_dur = 600
may_take_a_long_time()
do_something_else()

What can I do so that if may_take_a_long_time() takes longer than timeout_dur , to abort whatever its doing, and proceed w/ do_something_else() 我该怎么办,如果may_take_a_long_time()timeout_dur花费更长的时间,则中止其所做的一切,并继续执行do / do_something_else()

perhaps, setting SIGALARM before calling may_take_a_long_time() ? 也许在调用may_take_a_long_time()之前设置SIGALARM how do i do that? 我怎么做? or run may_take_a_long_time() in a thread which happens async so i can have time.sleep(timeout_dur) in caller's thread? 或在异步发生的线程中运行may_take_a_long_time() ,以便我可以在调用者的线程中使用may_take_a_long_time() time.sleep(timeout_dur)

Threading in python has quirks, and if you want an answer specific to that, I suggest you edit your question and put that up front. python中的线程有一个怪癖,如果您想要一个特定的答案,我建议您编辑问题并将其放在前面。

For simple single threaded, you could use the existing timeout decorator as another user suggested or you can make your own, or you can do something like this (you'll have to tailor the code if you expect may_take_a_long_time() to return something, though: 对于简单的单线程,您可以按照其他用户的建议使用现有的超时装饰器,也可以使用自己的超时装饰器,也可以执行类似的操作(但是,如果希望may_take_a_long_time()返回某些内容,则必须对代码进行定制。 :

import time

def may_take_a_long_time(tout):
    timeout = time.time() + tout
    passed = False

    while not passed:
        passed = met_condition()
        if time.time() > timeout:
            break

def met_condition():
   if some_condition:
      return True
   else:
      return False           

def do_something_else():
   # TODO your code here

if '__name__' == '__main__':
    may_take_a_long_time(30)
    do_something_else()

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

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