[Tutor] stop a loop after precise amount of time
Steven D'Aprano
steve at pearwood.info
Sun Nov 25 12:36:39 CET 2012
On 25/11/12 22:01, Saad Javed wrote:
> time.sleep(30) will pause the program for 30s. I want to the run the
> program for 30s.
Your first email did not make that clear. Please take more care to
explain your question.
stop = time.time() + 30
while time.time() < stop:
do_something_useful()
print "Done"
This will not interrupt do_something_useful, it only checks the
time at the start of each loop. That's simple and easy and very
often is close enough.
But if you want to interrupt do_something_useful when 30s is up,
that becomes much, much, much harder. See here for an explanation
of why it is hard:
http://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python/
and here for one possible solution:
http://pguides.net/python-tutorial/python-timeout-a-function/
--
Steven
More information about the Tutor
mailing list