[Tutor] how to run function only for a pre-defined time

Vinu Vikram vvinuv at gmail.com
Sun Oct 28 10:57:07 CET 2007


Hi alan
Thanks.
But if I write a code like the followiing, how I can stop the thread

#!/usr/bin/env python
import threading
import time, os
class Infi(threading.Thread):
  def __init__(self, a):
    self.a = a
    threading.Thread.__init__(self)
  def run(self):
    i = 1
    while i==1:
      print self.a
      time.sleep(.5)
      self.a += 1
if __name__ == '__main__':
  t = Infi(1)
  t.start()
  time.sleep(2)
  if t.isAlive():
    print 'Here I want to stop the thread (the while loop) and continue with
the remaining part of the script'
  obj_file = open(clus_cata,'r')
  try:
    pnames = obj_file.readline().split()
  except:
    pass
......
......
......
and so on

Thanks in Advance
Vinu Vikram

On 10/27/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
> "Vinu Vikram" <vvinuv at gmail.com> wrote
>
> > Could anybody try to tell me whether it is possible to run a
> > function only
> > for a particular time period. In my python script I call some third
> > party
> > function which some time won't give results. I would like to write
> > the
> > script in such a way that, it will wait for the result from this
> > function
> > for some time, say 10 seconds, and if it fails to get any results
> > within
> > that time (10 seconds), the script should skip that function and
> > stop the
> > program.
> >
>
> I think you will need to use threading to launch your function in a
> separate thread. If the thread dopesn't end in time you can proceed
> in the main thread to kill the thread and exit the program.
>
> Read about Python threading here:
>
> http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
VINU VIKRAM
http://iucaa.ernet.in/~vvinuv/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071028/e8548993/attachment.htm 


More information about the Tutor mailing list