Comme mettre un timeout sur une fonction sous python / windows ?

Le
actipy
Bonjour,
je tourne sous windows (), et souhaite limiter l'exécution d'une fonction à x secondes,
jé trouvé la solutions pour unix (ci dessous).
si quelqu'un a la solution windows, jsuis prenneur,
merci

=
source: http://mail.python.org/pipermail/python-list/2004-May/262746.html

>> i would like a function RunWithTimeout( func, args, timeout )
>> i would like it to invoke the function func on arguments args.
>> if timeout seconds elapse before func(args) returns, i would
>> like it to raise an exception. if func(args) returns before timeout
>> seconds, i would like it return the result.
>
> I'm guessing you want the exception raised after func has executed for
> timeout seconds (as opposed to waiting for func to complete).
>
> Since you can't stop func from the outside (as Tim said), I suppose you
> could run func in a separate thread. From the original thread, you'd
> have to wait for either timeout seconds or until func completes,
> whichever comes first. If the timeout happened first, then raise the
> exception (else you presumably return func's result). I'm no expert on
> threading in Python, but I'll bet the Library Reference has the
> information you need.

just use alarm and use a signal handler to be called after N seconds,
this is how I do it: (I've omitted the definition of the exception for
brevity)

--

import signal

#
# a alarm signal handler
#
def alarmHandler(signum, frame):
raise TimeExceededError, "Your command ran too long"

#
# a function that would run for too long
#
def infinite():
while 1:
pass
return

#
# set the alarm signal handler, and set the alarm to 1 second
#
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(1)

#
# the function infinite would never return, after 1 second the signalHandler
# is called, which immediately just raises the exception.
#
try:
infinite()
except TimeExceededError:
# but after 1 second, the alarmHandler raises this
# exception
print "code must have gone crazy"

--
Vidéos High-Tech et Jeu Vidéo
Téléchargements
Vos réponses
Gagnez chaque mois un abonnement Premium avec GNT : Inscrivez-vous !
Publicité
Poster une réponse
Anonyme