max time wait for a function

Terry Reedy tjreedy at udel.edu
Tue May 18 12:22:58 EDT 2010


On 5/18/2010 6:24 AM, Albert Hopkins wrote:
> On Tue, 2010-05-18 at 02:45 -0700, pacopyc wrote:
>> Hi, I've a question for you. I'd like to call a function and waiting
>> its return value for a time max (30 sec).
>> The function could not respond and then I must avoid to wait for
>> infinite time. OS is Windows XP.
>> Can you help me?
>>
>> Thank
>
> This is how I do it with a function decorator. I probably borrowed this
> from someone and not attributed it.  Anyway, it works on Linux, not sure
> about Windows:
>
> def function_timeout(seconds):
>      """Function decorator to raise a timeout on a function call"""
>      import signal
>      class FunctionTimeOut(Exception):
>          pass
>
>      def decorate(f):
>          def timeout(signum, frame):
>              raise FunctionTimeOut()
>
>          def funct(*args, **kwargs):
>              old = signal.signal(signal.SIGALRM, timeout)
>              signal.alarm(seconds)

from help(signal):
     alarm() -- cause SIGALRM after a specified time [Unix only]

I do not know of any replacement in the stdlib, but one could check the 
code for multiprocessing to see how it does a timeout. Or check the 
pywin32 library
http://pypi.python.org/pypi/pywin32/210

>              try:
>                  result = f(*args, **kwargs)
>              finally:
>                  signal.signal(signal.SIGALRM, old)
>              signal.alarm(0)
>              return result
>
>          return funct
>
>      return decorate
>
>





More information about the Python-list mailing list