Basic Python Question

Peter Abel PeterAbel at gmx.net
Thu Jul 22 20:53:46 CEST 2004


"Richard Spooner" <rspooner at frisurf.no> wrote in message news:<6ZLLc.4839$Mq3.91303 at news4.e.nsc.no>...
> Hey,
> 
> I'm very new to python and am trying to do the following.  I may get the
> jargon wrong at times but hopefully you can see what I'm trying to do...
> 
> I have created a threaded class which sets up a socket and then binds to a
> port.  When I make a new instance I send the port number and I would like
> the __init__ routine to set up the socket and then attempt to bind it to a
> port.
> 
> If I already have an instance of this class running then obviously I'll
> already have a port bound.  So if I try and create another instance with the
> same port I'd like the program to flag this error and inform the user that
> it is instead using the original instance..
> 
> So far I have this
> 
> import threading
> import socket
> import struct
> 
> class dataretriever(threading.Thread):
>     def __init__(self, port):
>         threading.Thread.__init__(self)
>         self.setDaemon(1)
>         self.resultQueue = resultsQueue
>         self.s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
>         try:
>             self.s.bind(( '', port))
>         except:
>             print "Error binding worker"
> 
> 
>         self.start()
>     def run(self):
>         while 1:
>             pass
>             #playing with the data I recieve
> 
> 
> x = dataretriever(9999)
> y = dataretriever(9999)
> 
> When it tries to define y,  I'd like it to say "Port xxxx already in use by
> x setting y = x"
> 
> Any ideas???
> 
> Thanks for your time, seems to be a good little language.
> 
> Dave

Maybe not a big hit but could be an approach:

>>> class dataretriever(threading.Thread):
... 	__port = None
... 	__instance = None
... 	def __init__(self,port):
... 		if port == dataretriever.__port:
... 			print 'Error binding worker'
... 			self.__dict__ = dataretriever.__instance.__dict__
... 			return
... 		else:
... 			dataretriever.__port = port
... 			dataretriever.__instance = self
... 			self.do_what_ever_you_want_to_do()
... 	def do_what_ever_you_want_to_do(self):
... 		print 'I do it'
... 
>>> a=dataretriever(2)
I do it
>>> b=dataretriever(2)
Error binding worker
>>> id(a)
12281616
>>> id(b)
14817928
>>> a.foo='bar'
>>> b.foo
'bar'
>>> 

Regards
Peter



More information about the Python-list mailing list