Client Socket Connection to Java server
I am having problems with a socket connection to a Java server. In java I just open the socket, pass the length and then pass the bits across the socket. I created a socket object: import socket class MySocket: def __init__(self, host='localhost', port = 28192, buffsize = 1024): socket.setdefaulttimeout(10) self.host = host self.port = port self.buffsize = buffsize self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((host, port)) def send(self, data): self.socket.send(data) def receive(self): return self.socket.recv(self.buffsize) def sendAndReceive(self, data): self.send(data) return self.receive() def close(self): self.socket.close() But the java server gives the error: WARNING: Message length invalid. Discarding The data is of type string (xml). Am I doing something wrong? I know you have to reverse the bits when communicating from C++ to Java. Could this be the problem? I figured it would not because it said the length was invalid. I just started looking at python sockets tonight... and I don't have a real deep base with socket connections as it is... any help would be greatly appreciated. Greg -- http://mail.python.org/mailman/listinfo/python-list
Read Only attributes, auto properties and getters and setters
Ok, so I noticed some of the modules (such as many of the datetime
attributes) are read-only, which means the __setattr__ and __set__
methods are intercepted... pretty easy. I am looking for a way to
automate this. The real goal is not to have read only attributes, but
to have getters and setters that are automatically called when a
property is called. The getting is pretty easily achieved by setting
the metaclass which also creates the properties. What I have so far
will protect the get_ and set_ methods as well as the properties that
call the get methods. The reasoning for this is that I don't want
someone accidentally overwriting the property when the class uses a
private class variable. What I have so far:
class ReadOnlyMeta(type):
def __new__(cls, name, bases, methoddict):
pname = '_%s__protected_items' %(name)
protected = [pname]
methoddict[pname] = protected
for key, value in methoddict.items():
if key.startswith("get_"):
methoddict[key[4:]] = property(value)
protected.append(key[4:])
protected.append(key)
elif key.startswith("set_"):
protected.append(key)
return type.__new__(cls, name, bases, methoddict)
class ReadOnly(object):
__metaclass__ = ReadOnlyMeta
def __check_private(self, name, msg = None):
if name in self.__protected_items:
if msg is None:
msg = "'%s' of '%s' is Read only." %(name,
self.__class__.__name__)
raise AttributeError(msg)
def __setattr__(self, name, value):
self.__check_private(name, "attribute '%s' of '%s' objects is
not
writable" %(name, self.__class__.__name__))
self.__dict__[name] = value
def __delattr__(self, name):
self.__check_private(name, "attribute '%s' of '%s' objects
cannot be
removed" %(name, self.__class__.__name__))
self.__dict__.pop(name)
def __set__(self, instance, value):
self.__check_private(instance, "You cannot remap the method
'%s'" %
(instance))
self.__dict__[instance] = value
I then implement this by creating a subclass of the read only class:
class MyClass(ReadOnly):
def __init__(self, x):
self.set_x(x)
def get_x(self):
return self.__x
def set_x(self, x):
print 'Hello the setter was called!'
self.__x = x
What I want is to be able to auto-call the set_ methods whenever
someone tries to call a method that has a setter. This could be done
by each class... tedious! I want automation! To do this I have tried
adding a list of setters to the metaclass and then in the __set__ and
__setattr__ methods I check to see if 'set_%s' %(variable) exists in
the list... if it does I call the method. This would work, however
there are two lists of setters (in the example above), the ReadOnly
list and a MyClass list. When you print out a dir(self) IN the
ReadOnly class from an implementation (MyClass) it will show the
MyClass attributes, however they cannot be called from the parent
class... so my real question... how can you (or can you ever) call a
child method from a parent class without explicitly passing the
callable?
I hope this hasn't been too confusing... or made your head hurt like
mine does... If you want more code examples of what I have tried and
the out put... I'd be happy to give them.
Greg
--
http://mail.python.org/mailman/listinfo/python-list
Re: Read Only attributes, auto properties and getters and setters
Oh... one other thing that would be really cool is to do this with AOP/ descriptors! I just haven't been able to get that to work either. Basics... @readonly class MyClass(object): def __init__(self, x): self.set_x(x) def get_x(self): return self.__x def set_x(self, x): print 'Hello the setter was called!' self.__x = x and it's done! I don't think this will work because (maybe I'm wrong) but I don't think you can set the metaclass in the descriptor??? If this is the case, it is more work to do the AOP and set a metaclass... better to just inherit. If it can be done... that would be awesome! Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Embarrasing questio
On Feb 12, 9:03 am, Catherine Heathcote wrote: > But I just cant find it. How do I do an or, as in c/c++'s ||? Just > trying to do something simple, the python equivilent of: > > if(i % 3 == 0 || i % 5 == 0) > > Thanks. if i % 3 == 0 or i % 5 == 0 -- http://mail.python.org/mailman/listinfo/python-list
Re: Embarrasing questio
On Feb 12, 9:03 am, Catherine Heathcote wrote: > But I just cant find it. How do I do an or, as in c/c++'s ||? Just > trying to do something simple, the python equivilent of: > > if(i % 3 == 0 || i % 5 == 0) > > Thanks. in 2.5 and above you can do if any(i%3 == 0, i%5 == 0) -- http://mail.python.org/mailman/listinfo/python-list
Re: Embarrasing questio
On Feb 12, 9:19 am, Michele Simionato wrote: > On Feb 12, 5:07 pm, TechieInsights wrote: > > > On Feb 12, 9:03 am, Catherine Heathcote > > > wrote: > > > But I just cant find it. How do I do an or, as in c/c++'s ||? Just > > > trying to do something simple, the python equivilent of: > > > > if(i % 3 == 0 || i % 5 == 0) > > > > Thanks. > > > in 2.5 and above you can do > > if any(i%3 == 0, i%5 == 0) > > You are missing a few parenthesis: if any([i%3 == 0, i%5 == 0]) (but > the idiomatic solution is to use or). Thanks... my mistake -- http://mail.python.org/mailman/listinfo/python-list
Re: Read Only attributes, auto properties and getters and setters
On Feb 12, 9:27 am, josh logan wrote: > On Feb 12, 10:58 am, TechieInsights wrote: > > > > > Oh... one other thing that would be really cool is to do this with AOP/ > > descriptors! I just haven't been able to get that to work either. > > Basics... > > > @readonly > > class MyClass(object): > > def __init__(self, x): > > self.set_x(x) > > > def get_x(self): > > return self.__x > > > def set_x(self, x): > > print 'Hello the setter was called!' > > self.__x = x > > > and it's done! I don't think this will work because (maybe I'm wrong) > > but I don't think you can set the metaclass in the descriptor??? If > > this is the case, it is more work to do the AOP and set a metaclass... > > better to just inherit. If it can be done... that would be awesome! > > > Greg > > Are your needs not already satisfied by the Python built-in property? > > http://docs.python.org/dev/3.0/library/functions.html#property yea... just read the docs... I love reinventing the wheel (sarcasm)... Thanks for this... I just realized that you can set the fset and fdel to None... so everything can be done from the metaclass! -- http://mail.python.org/mailman/listinfo/python-list
Re: Read Only attributes, auto properties and getters and setters
Ok... for some closure I have written a class to automate the
process. It takes getters and setters and deleters and then sets the
property automatically. Sweet!
class AutoProperty(type):
def __new__(cls, name, bases, methoddict):
processed = []
getter = 'get_'
setter = 'set_'
deleter = 'del_'
starters = {getter:PropertyAttr(getter, PropertyAttr.FGET),
setter:PropertyAttr(setter,
PropertyAttr.FSET),
deleter:PropertyAttr(deleter,
PropertyAttr.FDEL)
}
for key, value in methoddict.items():
var = None
for start in starters.keys():
if key.startswith(start):
var = key[len(start):]
break
if var is None or var in processed:
continue
property_values = []
for start in starters.keys():
if '%s%s' %(start, var) in methoddict.keys():
property_values.append(starters[start].tostring(var))
else:
property_values.append(starters[start].tostring(None))
property_map = 'methoddict["%s"] = property(%s)' %(var,
','.join
(property_values))
exec(property_map)
return type.__new__(cls, name, bases, methoddict)
class PropertyAttr(object):
FGET = 'fget'
FSET = 'fset'
FDEL = 'fdel'
def __init__(self, start, type = FGET):
self.start = start
self.type = type
def tostring(self, var):
if self.type == self.FSET:
vars = ['v']
else:
vars = []
fullvar = ['self'] + vars
if var is None:
return '%s=None' %(self.type)
return '%s=lambda %s: self.%s%s(%s)' %(self.type,
','.join(fullvar),
self.start, var, ','.join(vars))
class ReadOnly(object):
__metaclass__ = AutoProperty
class MyClass(ReadOnly):
def __init__(self, x, y):
self.__x = x
self.__y = y
def get_x(self):
return self.__x
def set_x(self, x):
self.__x = x
def get_y(self):
return self.__y
mc = MyClass(10, 100)
print mc.x, mc.y
mc.x = 10
print mc.x
try:
mc.y = 100
except AttributeError:
print 'Yea it worked!'
try:
del mc.y
except AttributeError:
print "It's read only!"
And the output:
10 100
10
Yea it worked!
It's read only!
Now to work on descriptors doing it for you.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Spam
On Feb 12, 10:23 am, Tim Chase wrote: > > If you subscribe to C.P.L as a mailing list instead of a > > newsgroup, I believe most of the spam gets filtered out at the > > mailing list<->news group gateway by the Python.org spam > > filters... At least no spam in my Gmail spam folder appears to > > be flagged from this group(at a very brief glance) so they > > appear to be doing quite well. > > Allow me to take this opportunity to thank the folks that *are* > doing/managing this spam-filtering of the mailing list side of > things -- the drastic drop in spam (from 6+ months back) is much > appreciated! > > Though I guess this thread does beg the question: is there a way > to read the filtered mailing list with a newsreader (via NNTP) > instead of getting it delivered via email or subjecting oneself > to the spamminess of c.l.p? I like some of the "kill-thread" > types of options I've got on the NNTP side of readers that aren't > as readily available to me on the email side of things > (Thunderbird allows for thread-kills in News, but not in email). > > -tkc Enhancement request for google: hide messages by a certain author it would be individually set, but can get rid of a lot of junk at once. -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a way to determine a relative path to the script?
import os
os.path.relpath('/path/to/your/file', os.path.dirname(__file__))
tekion wrote:
> Hello,
> I have a script in /usr/local/app/mypython.py and a configuration file
> relative to /usr/local/app/conf. When I call the script with an
> absolute path of /usr/local/app/mypthon.py I recieved an error
> similar to the below error:
>
> Traceback (most recent call last):
> File "script/art/auditlog.py", line 28, in ?
> database = Config.get("DB", "user")
> File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
> python2.3/ConfigParser.py", line 505, in get
> raise NoSectionError(section)
> ConfigParser.NoSectionError: No section: 'DB'
>
> I know why, the configuration which I reference in the script is
> relative to "/usr/local/app", when I call the script via an absolute
> path, then the relative the configuration file is base on where ever I
> call the script from. One way to fix this is to add a path manually
> into the variable. But I would like to avoid this hard-coding
> parameter into my script. Is there a way to determined the relative
> location of the script programatically? FYI, in the end this scrip
> would run from CRON.
--
http://mail.python.org/mailman/listinfo/python-list
Re: is there a way to determine a relative path to the script?
Note:
The os.path.relpath is new in 2.6. If you are using an older version
you will have to write your own algorithm
TechieInsights wrote:
> import os
> os.path.relpath('/path/to/your/file', os.path.dirname(__file__))
>
> tekion wrote:
> > Hello,
> > I have a script in /usr/local/app/mypython.py and a configuration file
> > relative to /usr/local/app/conf. When I call the script with an
> > absolute path of /usr/local/app/mypthon.py I recieved an error
> > similar to the below error:
> >
> > Traceback (most recent call last):
> > File "script/art/auditlog.py", line 28, in ?
> > database = Config.get("DB", "user")
> > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
> > python2.3/ConfigParser.py", line 505, in get
> > raise NoSectionError(section)
> > ConfigParser.NoSectionError: No section: 'DB'
> >
> > I know why, the configuration which I reference in the script is
> > relative to "/usr/local/app", when I call the script via an absolute
> > path, then the relative the configuration file is base on where ever I
> > call the script from. One way to fix this is to add a path manually
> > into the variable. But I would like to avoid this hard-coding
> > parameter into my script. Is there a way to determined the relative
> > location of the script programatically? FYI, in the end this scrip
> > would run from CRON.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
You can use the built-in string formatting options and operations.
2.5: http://www.python.org/doc/2.5.2/lib/typesseq-strings.html
2.6: http://docs.python.org/library/string.html
In essence, you can do:
print "You still have $%i remaining" %(money)
On Jan 2, 2:15 pm, sprad wrote:
> I've done a good bit of Perl, but I'm new to Python.
>
> I find myself doing a lot of typecasting (or whatever this thing I'm
> about to show you is called), and I'm wondering if it's normal, or if
> I'm missing an important idiom.
>
> For example:
>
> bet = raw_input("Enter your bet")
> if int(bet) == 0:
> # respond to a zero bet
>
> Or later, I'll have an integer, and I end up doing something like
> this:
>
> print "You still have $" + str(money) + " remaining"
>
> All the time, I'm going int(this) and str(that). Am I supposed to?
--
http://mail.python.org/mailman/listinfo/python-list
__init__.py and package help
Ok I have read all of the tutorials and documents I could find. I am
running Python 2.6 on windows. The problem I am having with packages
is that they don't show up!
Simple example of what isn't working...
Structure-
pytest/ Root directory of package
__init__.py- code: __all__ = ['folder']
folder/ Another folder in the package
__init__.py- code: __all__ = ['hello']
hello.py- code: print('Hello World')
Then I append the path to sys.path, and try and import...
>>> sys.path.append(r'E:\dev\test\pytest')
>>> from pytest.folder import hello
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named pytest.folder
What am I doing wrong! It's driving me crazy.
Thanks in advance,
Greg
--
http://mail.python.org/mailman/listinfo/python-list
Re: __init__.py and package help
Ok... I figured it out... you can only import packages via the __all__
= ['subpackage/folder']... if you include a module such as hello.py,
it will fail.
Go figures I'd find this right after posting here...
Greg
TechieInsights wrote:
> Ok I have read all of the tutorials and documents I could find. I am
> running Python 2.6 on windows. The problem I am having with packages
> is that they don't show up!
>
> Simple example of what isn't working...
> Structure-
>
> pytest/ Root directory of package
> __init__.py- code: __all__ = ['folder']
> folder/ Another folder in the package
> __init__.py- code: __all__ = ['hello']
> hello.py- code: print('Hello World')
>
> Then I append the path to sys.path, and try and import...
>
> >>> sys.path.append(r'E:\dev\test\pytest')
> >>> from pytest.folder import hello
> Traceback (most recent call last):
> File "", line 1, in
> ImportError: No module named pytest.folder
>
> What am I doing wrong! It's driving me crazy.
> Thanks in advance,
> Greg
--
http://mail.python.org/mailman/listinfo/python-list
replacement for __file__ in compiled exe
__file__ command does not work when compiled to exe. It makes since because the file is now in a compressed library. Is there a replacement or something else you can do? The real problem is that when you create an exe of your program with python embedded, you can't always guarantee that your current directory is the directory of your program. I guess when you could just set a registry entry on windows... but it would be nice to have a quick fix for this (like os.path.dirname(__file__)). Thanks, Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__.py and package help
Thanks
J. Cliff Dyer wrote:
> On Mon, 2009-01-05 at 11:49 -0800, TechieInsights wrote:
> > Ok I have read all of the tutorials and documents I could find. I am
> > running Python 2.6 on windows. The problem I am having with packages
> > is that they don't show up!
> >
> > Simple example of what isn't working...
> > Structure-
> >
> > pytest/ Root directory of package
> > __init__.py- code: __all__ = ['folder']
> > folder/ Another folder in the package
> > __init__.py- code: __all__ = ['hello']
> > hello.py- code: print('Hello World')
> >
> > Then I append the path to sys.path, and try and import...
> >
> > >>> sys.path.append(r'E:\dev\test\pytest')
> > >>> from pytest.folder import hello
> > Traceback (most recent call last):
> > File "", line 1, in
> > ImportError: No module named pytest.folder
> >
> > What am I doing wrong! It's driving me crazy.
> > Thanks in advance,
> > Greg
>
> You want
>
> >>> sys.path.append(r'E:\dev\test')
>
> unless your code is in E:\dev\test\pytest\pytest\folder\hello.py
>
>
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
--
http://mail.python.org/mailman/listinfo/python-list
Re: replacement for __file__ in compiled exe
Yes, that is my exact question. How do you get the file path of your script/program. Normally in python you can use __file__ and it will return the file path of the script you are in, however, when you compile the script to exe py2exe (or whatever util you are using) compresses them into a zip folder... not usually a problem, except when you want the access the file path of the exe. Thanks for the answer... I should have thought of that all along... just look on the system path. Sometimes the answer was right in front of your face the whole time... Greg On Jan 5, 1:51 pm, John Machin wrote: > On Jan 6, 7:03 am, TechieInsights wrote: > > > __file__ command does not work when compiled to exe. It makes since > > because the file is now in a compressed library. Is there a > > replacement or something else you can do? The real problem is that > > when you create an exe of your program with python embedded, you can't > > always guarantee that your current directory is the directory of your > > program. > > How can you *ever* guarantee that the current directory is the same as > the directory in which the program resides? This lack of guarantee is > quite independent of whether the "program" is .py, .exe, .bat, .com, > etc. Isn't the real problem how to find out which directory the > program is in? > > > I guess when you could just set a registry entry on > > windows... but it would be nice to have a quick fix for this (like > > os.path.dirname(__file__)). > > if hasattr(sys, 'frozen'): > answer = os.path.split(sys.executable)[0] > else: > answer = os.path.split(sys.argv[0])[0] > > (maybe) ... your question is a little unclear. > > HTH, > John -- http://mail.python.org/mailman/listinfo/python-list
Python Socket Issues with VirtualBox
I have created a server and client that communicate via a TCP socket connection. Everything runs great on 6 of the 6 boxes. However, when I installed Sun's VirtualBox on one of the PC's I started getting: error: (10061, 'Connection refused') I tried restarting, stopping services, checking out a new copy of the code, changing ports, changing host names... all fails until I remove VirtualBox. I would REALLY like to be able to have both working. Any idea what might be causing this and how I could fix it? Thanks, Greg -- http://mail.python.org/mailman/listinfo/python-list
