473,789 Members | 2,833 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Basic Python Question

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(t hreading.Thread ):
def __init__(self, port):
threading.Threa d.__init__(self )
self.setDaemon( 1)
self.resultQueu e = resultsQueue
self.s = socket.socket( socket.AF_INET, socket.SOCK_DGR AM )
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(9 999)
y = dataretriever(9 999)

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



Jul 18 '05 #1
4 1542
except:
print "Error binding worker"

I think this should be:
except:
print "Error binding worker"
raise

But maybe I did not understand your problem.

Jul 18 '05 #2
At the moment it detects the error and prints out "Error binding Worker"
just because it was something I could easily check was working.

I would like it to use the except to

check that it's a bind error,
find the existing instance that is bound to that port
make the new instance that it is attempting to create reference this
existing instance. Thus having the new instance effectively bound to the
port but in fact really linked to the existing instance which is in turn
bound to the port.

Cheers

Dave

"Gandalf" <ga*****@geoche msource.com> wrote in message
news:ma******** *************** **************@ python.org...
except:
print "Error binding worker"

I think this should be:
except:
print "Error binding worker"
raise

But maybe I did not understand your problem.


Jul 18 '05 #3
On Thu, 22 Jul 2004, Richard Spooner wrote:
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..


To get the effect you want (return the previous instance), you'll need to
do some trickery with __new__, the function which is responsible for
creating a class (as opposed to initialization, which is handled by
__init__):

import threading
import socket
import struct

class dataretriever(t hreading.Thread ):
__bound = {} # this holds data of the form port:class_inst ance
__opened = False # used to stop multiple __init__s

def __new__(cls,por t):

# try to get an existing class instance bound to port
try:
c = cls.__bound[port]

# if that fails, make a new instance
except KeyError:
c = threading.Threa d.__new__(cls, port)
# and store it in our class variable
cls.__bound[port] = c

# this is executed if the try: succeeded
else:
print 'Port %d already bound, returning previous instance!' % port

# __new__ must return an instance of cls
return c

def __init__(self, port):

# only initialize ourselves once
if self.__opened: return True
self.__opened=T rue

threading.Threa d.__init__(self )
self.setDaemon( 1)
self.resultQueu e = resultsQueue
self.s = socket.socket( socket.AF_INET, socket.SOCK_DGR AM )
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(9 999)
z = dataretriever(1 0000)
z is x False y = dataretriever(9 999) Port 9999 lready bound, returning previous instance! y is x

True

Hope this all makes some sense :P

Jul 18 '05 #4
"Richard Spooner" <rs******@frisu rf.no> wrote in message news:<6Z******* ***********@new s4.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(t hreading.Thread ):
def __init__(self, port):
threading.Threa d.__init__(self )
self.setDaemon( 1)
self.resultQueu e = resultsQueue
self.s = socket.socket( socket.AF_INET, socket.SOCK_DGR AM )
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(9 999)
y = dataretriever(9 999)

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(t hreading.Thread ): .... __port = None
.... __instance = None
.... def __init__(self,p ort):
.... if port == dataretriever._ _port:
.... print 'Error binding worker'
.... self.__dict__ = dataretriever._ _instance.__dic t__
.... return
.... else:
.... dataretriever._ _port = port
.... dataretriever._ _instance = self
.... self.do_what_ev er_you_want_to_ do()
.... def do_what_ever_yo u_want_to_do(se lf):
.... 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
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
9290
by: Michael Foord | last post by:
#!/usr/bin/python -u # 15-09-04 # v1.0.0 # auth_example.py # A simple script manually demonstrating basic authentication. # Copyright Michael Foord # Free to use, modify and relicense. # No warranty express or implied for the accuracy, fitness to purpose
3
1527
by: Player | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello I am teaching myself python, and I have gotten a long way, it's quite a decent language and the syntax is great :) However I am having a few, "problems" shall we say with certain conventions in python.
5
3002
by: Aaron Ginn | last post by:
I'm investigating the feasibility of using Python instead of Visual Basic for a commercial software package that I'm planning on developing. Now I'm absolutely a Python zealot. I use it for most of my software development at work where I work in a Solaris environment. To me, Python is the perfect language for most applications in a UNIX environment where a compiled language is not required. However, I'm not so sure about Windows. The...
9
3823
by: abisofile | last post by:
hi I'm new to programming.I've try a little BASIC so I want ask since Python is also interpreted lang if it's similar to BASIC.
6
1246
by: aghazalp | last post by:
hi guys, this would be the most basic question ever...I am not a programmer but I am trying to learn programming in python...I was reading John Zelle's text book and instructed me to make .py file and save it on the desk top...then it said close the python GUI and double click on the icon of the I just made and that should run the program...well, the good news is that it does but when I input a number for calculation and press the enter...
1
1471
by: bruce | last post by:
hi... i have the following test python script.... i'm trying to figure out a couple of things... 1st.. how can i write the output of the "label" to an array, and then how i can select a given element of the array.. i know real basic.. 2nd.. where can i go to find methods of libxml2dom. i've been looking using google, but can't seem to find a site pointing out the underlying methods,
4
2151
by: Hoop | last post by:
Hi, I have been working in getting Boost.Python running on my PC, seems to work now. I have what I believe is somewhat of basic question here. I am starting on an application that will developed in VS2005, probably using C++/CLI. I want to be able to exchange data in between Python and C++. The user when running the C++ app will be able to call a python script, set some values, that will then be communicated to running application, it
25
2593
by: samjnaa | last post by:
Please check for sanity and approve for posting at python-dev. In Visual Basic there is the keyword "with" which allows an object- name to be declared as governing the following statements. For example: with quitCommandButton .enabled = true .default = true end with
2
4349
by: Dave Dean | last post by:
Hi all, I'm just starting out in sockets/network programming, and I have a very basic question...what are the 'security' implications of opening up a socket? For example, suppose I've written a simple chat server and chat client. The server opens a socket, listens on a port, and accepts incoming connections. The clients open a socket and connect to the server. If the server receives a message from a client, it sends that message out to...
14
1852
by: MartinRinehart | last post by:
Working on parser for my language, I see that all classes (Token, Production, Statement, ...) have one thing in common. They all maintain start and stop positions in the source text. So it seems logical to have them all inherit from a base class that defines those, but this doesn't work: import tok class code: def __init__( self, start, stop ):
0
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10200
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10139
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9984
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9020
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7529
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6769
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3701
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.