0

I want to run a certain function in Python (heavy function) but I would not like it to run more than X seconds. For example, I want to run foo() and if after 20 seconds it didn't finish processing, I'd like my program to continue running. I wouldn't like my program to keep running when foo() is running, I want it to continue its run only if foo() has finished OR 20 seconds has passed (so threads won't fit here)

Any suggestions?

Shai
  • 1,093
  • 4
  • 13
  • 20

1 Answers1

1

The "straightforward" way is to keep an init time within the function, and at sensible times (beginning, end of loops, before/after data writes, whatever) check the current time against that. This, of course, won't necessarily stop right at twenty seconds, and won't work if your foo() is hanging at any point internally.

Otherwise, you're probably looking at this: Asynchronous method call in Python?

If your method is dealing with sockets, asyncore from the Python Standard Library could also be useful.

EDIT: To go more in-depth (from http://docs.python.org/library/multiprocessing.html#multiprocessing.Process):

import multiprocessing

#identity function, replace with your actual foo
def foo(x):
    return x

if __name__ == '__main__':
    foo_args = #some tuple containing non-kw arguments for your function
    foo_kwargs = #some dict containing kw arguments for your function

    proc = multiprocessing.Process(target=foo,args=foo_args,kwargs=foo_kwargs)

    proc.start()
    proc.join(20) #This takes a timeout argument in seconds

You can also, contrary to your assumption in the question, use threads for this. You simply make the parent thread block on the call or until timeout (with the same join call--the interfaces for threading and multiprocessing are identical).

If you need the result of the function as a return value, pipes and queues on the same page can return that.

Community
  • 1
  • 1
A. Wilson
  • 8,534
  • 1
  • 26
  • 39
  • Thanks for your answer. Unfourntaley the function I'm trying to run is not mine and even that I can change it, I'm not allowed because of the project type. So I can't really add time tickers inside the function. Regarding the multiproccessing suggestion, I will try it. I will also try the methods you suggested with the threads. Thanks for your time! – Shai Apr 18 '12 at 21:20
  • Heh, yeah, the first suggestion only really applies if you need to not use any libraries, which is silly in Python anyway. It was more a poorly executed joke than anything else. Multiprocessing/threading should get you there, though. – A. Wilson Apr 18 '12 at 21:29