Re: Difference between a library and a module...

2006-03-07 Thread Laszlo Zsolt Nagy
sophie_newbie wrote:

OK this might seem like a retarded question, but what is the difference
between a library and a module?

If I do:

import string

am I importing a module or a library?
  

I'm not a guru, but... I think that modules are things that live inside 
the Python language. In the above case, you are importing a Python 
module. I think that a library is something that resides on the file 
system and contains code. But it can be anything, and it exists outside 
a Python program. I have the feeling that a library is usually lives in 
compiled form, while a python module can be anything that can be 
'import'-ed (py file, pyd file or an so file...)

And if i do string.replace() am I using a module or a function or a
method or what?
  

What you call here is:  string.replace. In the standard string module, 
replace is a function. But if string refers to a custom module, then 
string.replace could be a class or an object (or any callable) as well.

By the way, modules are not callable at all.
Methods can only be called with an object.
Class methods can be called with a class.

Well, a module is itself a special object, called the 'module object'. 
Module objects have no class, and they cannot be instantiated or called.

http://docs.python.org/ref/types.html#l2h-105


I hope this helps.

  Laszlo

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send email notification

2006-03-07 Thread Laszlo Zsolt Nagy
Ernesto wrote:

Is there a special module for mail ?

I'd like to send an email [to 'n' unique email addresses] from a python
script.  
  

http://www.justfuckinggoogleit.com/search.pl?python+smtp

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert dictionary to HTTP POST

2006-03-05 Thread Laszlo Zsolt Nagy

The values of some inputs are encoded using html entities.
How can I decode a string like Bessy#39;s cat  in Bessy's cat?



this snippet might help:

http://effbot.org/zone/re-sub.htm#strip-html
  

Thank you, worked like a charm. :-)

  Laszlo

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calculating md5 checksums.

2006-03-05 Thread Laszlo Zsolt Nagy
Rajesh Sathyamoorthy wrote:

 I tried the script and had to get a hexdigest to get the value provided

 My test:
 SimplyMEPIS-3.3.1-1.iso
 checksum: 41a19060d3bb37bd596708ba77964491
 i got: 41a19060d3bb37bd596708ba77964491

 Do people normally provide md5 checksum in a *hexadecimal string?
 *Besides that, is the script reliable?

I think the biggest problem is that you read the whole file as one 
string into memory. This won't work for large files, or at least it is 
very inefficient. Try to read chunks from the file until EOF and update 
the hash object with each chunk.

Best,

   Laszlo

-- 
http://mail.python.org/mailman/listinfo/python-list


Convert dictionary to HTTP POST

2006-03-03 Thread Laszlo Zsolt Nagy

  Hello,

How can I convert a dictionary into a HTTP POST string?
I have an example below, but this is not working correctly for special 
characters. ( ' and others). In other words, if I use Bessy's cat 
instead of Bessy then the http server will parse that to Bessy#39;s cat
Probably the problem is that I should not use urllib.quote but something 
else.
Can you please advise?

   Laszlo

form_values = {'name':'Bessy','age':'10','gender':'female'}
for key,value in form_values.iteritems():
values.append('%s=%s' % (urllib.quote(key),urllib.quote(value)) )
   
values.append('x=33')
values.append('y=14')
post_data = (''.join(values)).replace('/','%2F')
txheaders = {  

'Accept':'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language':'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
}
req = urllib2.Request(url, post_data, txheaders)
u = urllib2.build_opener()
req.add_data(post_data)
page2 = self.download(action,post_data,{
  'Content-Type': 'application/x-www-form-urlencoded'
})
openerdirector = u.open(req)
data = openerdirector.read()   

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert dictionary to HTTP POST

2006-03-03 Thread Laszlo Zsolt Nagy


See urllib.urlencode(). No idea why they don't include it in urllib2 as 
well, but there you go.

  from urllib import urlencode
  urlencode({'a':' Simple string', 'b': '[EMAIL PROTECTED]*()_+='})
'a=%26+%22Simple+string%22b=%3C%3E%21%40%23%24%25%5E%26%2A%28%29_%2B%3D'
 
  

Hmm. urlencode is using quote_plus internally. Looks like there is no 
difference in the encoding of the apostrophe.
I tried to create a very basic form and realized that the problem is NOT 
with the quoting.
I'm writting a program that puts orders into a wholesaler's database.
They do not have a programatic interface, so I have to login and post 
forms using a program.
There are some fields that I must not change, so I have to read the 
value from the HTML source and then post it back.
Here is the problem:

html
body
form method=POST
  input name=name value=Bessy#39;s cat
  input type=submit
/form
/body
/html

The values of some inputs are encoded using html entities.
How can I decode a string like Bessy#39;s cat  in Bessy's cat?

Thanks,

   Laszlo

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert dictionary to HTTP POST

2006-03-03 Thread Laszlo Zsolt Nagy

 Well I don't understand what's encoding the apostrophe as an encoded 
 entity anyway. That's only supposed to be done for HTML content, not 
 form content. 

You are right. I was wrong. The problem was not with quote. It was 
reading out the VALUE of an INPUT from HTML source.

 How about an RE that turned all #DD; into %DD ?

Good idea, but then I still need to examine for nbsp;  gt; and the 
others. I just wonder if there is a standard function in Python that can 
convert HTML escaped value into plain string.

Regards,

   Laszlo


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerical solver

2006-03-01 Thread Laszlo Zsolt Nagy
Robert Kern wrote:

In [7]: scipy.optimize.fmin_cobyla?

Type:   function
Base Class: type 'function'
String Form:function fmin_cobyla at 0x4fff3b0
Namespace:  Interactive
File:
/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/scipy-
0.4.7.1607-py2.4-macosx-10.4-ppc.egg/scipy/optimize/cobyla.py
Definition: scipy.optimize.fmin_cobyla(func, x0, cons, args=(),
consargs=None, rhobeg=1.0, rhoen
d=0.0001, iprint=1, maxfun=1000)
Docstring:
Minimize a function using the Contrained Optimization BY Linear
Approximation (COBYLA) method
  

...

Returns:

x -- the minimum
  

I'm going to try this. I hope x and x0 can be a vectors. :-)


-- 
http://mail.python.org/mailman/listinfo/python-list


Numerical solver

2006-02-28 Thread Laszlo Zsolt Nagy

  Hello,

I would like to use a numerical solver for a specific problem. My 
problem looks like this:

   1. I have numeric constants, named A,B,C etc.
   2. I have numeric variables, named x,y,z etc.
   3. I have functions, like f1(x), f2(x), f3(x,y), f4(y) etc.
   4. I have constraints like f1(x)  A  f3(x,y)  B etc.

Fortunately, all of the variables can be limited to a closed finite 
interval. (E.g.   0 = x = 100)
There is a specific function, called P(x,y,z) that needs to be optimized 
(need to find its maximum/minimum).

I'm looking for a native Python solution: I would like to define the 
functions and the constraints in Python.
I have looked at the cheeseshop and found LogiLab's constraint:

http://www.logilab.org/projects/constraint/documentation

It is almost perfect for me, but it is working with finite sets.
I'm not sure about SciPy or NumPy. Do you have an idea about what is the 
package I need?
I'll gladly read any documentation or tutorial, just I do not know which 
one is the best to start with.

Thanks,

   Laszlo

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: _bsddb on NetBSD

2006-01-17 Thread Laszlo Zsolt Nagy
Miki Tebeka wrote:

Hello All,

I can't seem to build Python2.4.2 with bsddb on NetBSD.
bsddb seems to be missing from the pkg_add installation as well.
  

Please look at the message that you get when you execute

pkg_add -r python

You will see that tkinter, bsddb, gdbm and some other libs are available 
as separate packages.

Did you try

pkg_add -r py24_bsddb
pkg_add -r py24_gdbm


Best,

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Developing a network protocol with Python

2005-12-15 Thread Laszlo Zsolt Nagy
Paul Rubin wrote:

Laszlo Zsolt Nagy [EMAIL PROTECTED] writes:
  

But how can I transfer pure python objects otherwise? Pyro also uses
Pickle and it also transfers bytecode.


Pyro in the past used pickle in an insecure way.  I'd heard it had
been fixed and I didn't realize it still uses pickle.
  

On the features page, you can read this:

Mobile objects. Clients and servers can pass objects around - even when 
the server has never known them before. Pyro will then automatically 
transfer the needed Python bytecode.

I believe that using cPickle and transferring data (but not the code) is 
still more secure than transferring bytecode. :-)

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Developing a network protocol with Python

2005-12-14 Thread Laszlo Zsolt Nagy

Try Pyro  http://pyro.sourceforge.net
before rolling your own Python-specific protocol.
  

You are right. I wanted to use pyro before, because it is well tested 
and it has nice features.
Unfortunately, it is not good for me. :-(

I already have my own classes. My objects are in object ownership trees, 
and they are referencing to each other (weakly and strongly). These 
classes have their own streaming methods, and they can be pickled 
safely. This is something that pyro cannot handle. It cannot handle 
these ownership object trees with weak references. Pyro can distribute 
distinct objects only, and it uses an 'object naming scheme'. This is 
not what I want. My objects do not have a name, and I do not want to 
create 'technical names' just to force the Pyro style access. (Another 
problem is that I do not want to rewrite my classes and inherit them 
from the Pyro base object class.)

Thanks for the comment. I'm going to check the Pyro documentation again. 
I might find something useful.

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Developing a network protocol with Python

2005-12-14 Thread Laszlo Zsolt Nagy
Paul Rubin wrote:

Laszlo Zsolt Nagy [EMAIL PROTECTED] writes:
  

I already have my own classes. My objects are in object ownership
trees, and they are referencing to each other (weakly and
strongly). These classes have their own streaming methods, and they
can be pickled safely.



Standard warning: if you're accepting requests from potentially
hostile sources, don't use pickle.
  

Yes, I know.  Not talking about TLS/SSL - there can be hostile persons, 
knowing a valid password and using a modified client program.

But how can I transfer pure python objects otherwise? Pyro also uses 
Pickle and it also transfers bytecode.
Well, Pyro has an option to use XML messaging, but that is very 
restricted, you cannot publish arbitrary python objects with XML. :-(

I read somewhere that Pickle had a security problem before Python 2.2, 
but after 2.2 it has been solved.
BTW how CORBA or COM does this? They can do object marshaling safely. 
Can we do the same with Python?
Isn't it enough to implement find_global of a cPickler ?

   Les


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Developing a network protocol with Python

2005-12-13 Thread Laszlo Zsolt Nagy
Tom Anderson wrote:

I think to be effective, I need to use TCP_NODELAY, and manually 
buffered transfers.


Why?

Because of the big delays when sending small messages (size  1500 bytes).


Personally, i'd steer clear of doing it like this, and try to use an 
existing, language-neutral generic marshalling layer. XML and ASN.1 would 
be the obvious ones, but i wouldn't advise using either of them, as 
they're abominations. JSON would be a good choice:

http://www.json.org/
  

I need to send Python objects too. They are too elaborate to convert 
them to XML. (They are using cyclic weak references and other Python 
specific stuff.) I can be sure that on both sides, there are Python 
programs. Is there any advantage in using XML if I already need to send 
Python objects? Those objects cannot be represented in XML, unless 
pickled into a CDATA string.

And didn't get much in the way of answers. Someone did point to this, 
though:

http://www.internet2.edu/~shalunov/writing/protocol-design.html
  

Hmm, this was very helpful. Thank you!

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance + classmethod question

2005-12-12 Thread Laszlo Zsolt Nagy
Mike Meyer wrote:

Laszlo Zsolt Nagy [EMAIL PROTECTED] writes:
  

Is it possible to tell, which instance was used to call the
classmethod that is currently running?



Ok, I read through what got to my nntp server, and I'm still
completely confused.

A class method isn't necessarilry called by an instance. That's why
it's a class method. What should happen in that case?
  

Here is the answer (an example):

@ClassOrInstanceMethod
def process_create_table(cls_or_self,tabledef,processor):
Process the CREATE TABLE command.

@param tabledef: a L{TableDefinition} instance.
@param processor: a L{SQLProcessor} instance.
hname = cls_or_self.hashident(tabledef.name)
if (isinstance(cls_or_self,type)) or (not 
cls_or_self.istableexists(hname)):
processor.addline(create table %s \n (% hname)
for field in tabledef.fields:
if not (field() is None):

cls_or_self.process_create_table_field(field(),processor)
processor.addline(,)
processor.truncate_last_comma()
processor.addline()
processor.addline())
cls_or_self.addtablespaceclause(tabledef,processor)
processor.processbuffer()

So if the method was called with an instance, it will check if the table 
exists and create the table only if it did not exist before.
But if the method was called with a class, it will create the table anyway.

The above method is just a short example. I have many methods for 
creating sequences, triggers, constraings etc.
The full pattern is:

def process_XXX(cls_or_self,defobject,processor):
longer code
   a condition, depending on the class or the instance
   longer code
   another condition, depending on the class or the instance
   longer code

There are two reasons why I do not want to create two methods (one 
instance and one class method).

1. If you look the above pattern, it is clear that the method does the 
same thing, just there are some conditions when I call it with an 
instance. I do not want to call process_create_table_with_class and 
process_create_table_with_instance, because the name of the method 
should reflect what it does primarily. (BTW, I also looked at 
multimethods, but they are not exactly for this kind of problem.)

2. The pattern above makes it clear that I just can't easily split the 
method into elementary parts. Steven wrote this pattern:

class C(object):
...
@classmethod
def do_stuff(cls, *args):
...
def do_instance_stuff(self, *args):
# instance stuff
...
self.do_stuff(*args)
# more instance stuff
  

But I cannot do this, because primarily I do class stuff, and in some 
cases, I can make use of an instance (but do not require it).
Comments welcome

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Developing a network protocol with Python

2005-12-12 Thread Laszlo Zsolt Nagy

  Hello,

I would like to develop a new network protocol, where the server and the 
clients are Python programs.
I think to be effective, I need to use TCP_NODELAY, and manually 
buffered transfers.
I would like to create a general messaging object that has methods like

sendinteger
recvinteger
sendstring
recvstring

To be more secure, I think I can use this loads function to transfer 
more elaborate python stuctures:

def loads(s):
Loads an object from a string.
   
@param s: The string to load the object from.
@return: The object loaded from the string. This function will not 
unpickle globals and instances.

f = cStringIO.StringIO(s)
p = cPickle.Unpickler(f)
p.find_global = None
return p.load()

Am I on the right way to develop a new protocol?
Are there any common mistakes that programmers do?
Is there a howto where I can read more about this?

Thanks

   Les


-- 
http://mail.python.org/mailman/listinfo/python-list


instance + classmethod question

2005-12-11 Thread Laszlo Zsolt Nagy

  Hello,

Is it possible to tell, which instance was used to call the classmethod 
that is currently running?

Background: I have a class called DatabaseConnection and it has a 
classmethod called process_create_tables. This method should create some 
database tables defined by a database definition object. The 
DatabaseConnection has many descendants, for example 
PostgreSQLConnection. Descendants know how to create tables in a given 
RDBMS type. I also use subclasses of the 'SQLProcessor' class, that 
processes SQL commands in different ways (print to stdout, write to 
file, execute directly in the database etc.) I would like to use the 
process_create_tables classmethod as is, because sometimes I only need 
to save a SQL script. However, I also want to use the same classmethod 
to create tables directly into an existing database. That database is 
presented as a DatabaseConnection instance. In that case, I only want to 
create the tables that do not exists yet.  Examples:

processor = SQLProcessors.StdOutProcessor() # Print to stdout
PostgreSQLConnection.process_create_tables(processor,dbdef)  # This 
sould create all tables, using the processor

processor = SQLProcessors.DirectProcessor(conn) # Execute directly
conn.process_create_tables(processor,dbdef) # This should create 
non-existing tables only, using the processor

Is this possible? Maybe there is a better way to achieve this, I'm not 
sure. I was thinking about this construct:

@classsmethod
def process_create_tables(cls,processor,dbdef,conn=None)

and then calling it as

conn.process_create_tables(processor,dbdef,conn)

but this looks very ugly to me. It would be much easier if I could tell 
which instance (if any) was used to call the classmethod.

Thanks,

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance + classmethod question

2005-12-11 Thread Laszlo Zsolt Nagy

  Hello Steven,

I already implemented this using the form

@classmethod
def  methodname(cls,other_params,self=None)

but your example code looks so neat! This is exactly what I needed. :-)
In my methods, most code is about string manipulation and calling other 
classmethods.
There are only a few places where I can use an instance, but it is not 
required.
I would like to reuse as most code as possible, so I do not want to 
create two different
methods. That would result in duplicating code. Now the only problem is 
how I name this.
It is not a classmethod, but it is also not a normal method. All right, 
it is a
ClassOrInstanceMethod. Amazing! Probably Python is the only language 
that is
flexible enough to do this. :-)

Thanks again!

   Laszlo


Steven Bethard wrote:

Laszlo Zsolt Nagy wrote:
  

 Hello,

Is it possible to tell, which instance was used to call the classmethod 
that is currently running?


  class ClassOrInstanceMethod(object):
... def __init__(self, func):
... self.func = func
... self.classfunc = classmethod(func)
... def __get__(self, obj, objtype=None):
... func = obj is None and self.classfunc or self.func
... return func.__get__(obj, objtype)
...
  


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to ping in Python?

2005-12-07 Thread Laszlo Zsolt Nagy
Michael Schneider wrote:

I telnet to port 13 (returns time)

The problem is that most modern up-to-date servers use firewalls. They 
only open the ports that are absolutely necessary. Usually the time 
service is part of inetd, which is disabled by default, on most of the 
servers. PING ICMP may work, but sometimes it does not either. In the 
worst case, all port are closed and you have no way to tell if there is 
a computer or not.

Can you tell more about what kind of server do you need to ping?

Example: if you need to know if a web server is alive, you should 
connect to port 80 (http). If the connection was successful, you can 
close the connection immeditelly. You can expect a HTTP server to open 
the HTTP port, but all other ports may be closed.

   Les



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extract python install info from registry

2005-12-06 Thread Laszlo Zsolt Nagy
rbt wrote:

On windows xp, is there an easy way to extract the information that 
Python added to the registry as it was installed?
  

Using regedit.exe, look at the registry keys and values under

HKEY_LOCAL_MACHINE\Software\Python

If you need to know how to read the registry from Python: please install 
the python win32 extensions (or use ActivePython).

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extract python install info from registry

2005-12-06 Thread Laszlo Zsolt Nagy

There's more to it than that... isn't there? I've used _winreg and the 
win32 extensions in the past when working with the registry. I thought 
perhaps someone had already scripted something to extract this info.
  

Ok, if you need to get all changes in the registry, you can use regdiff.

http://p-nand-q.com/download/regdiff.html

Take a snapshot before and after installing Python. However, this is not 
a wise approach.
For example:

   1. One can have a system drive 'C:\' others 'G:\'
   2. One can have Windows installed in \Windows others in \WinNT and
  others in \MyWinNT
   3. For many registry values, you cannot really tell if you need to
  correct a value or not.

As a result, I believe you will only be able to use the 'regdiff' only 
on the same type of computer, with the same system drive, same system 
directory, same windows version etc. For other computers, there is no 
guarantee for that it will work.

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: windows installer problems

2005-12-06 Thread Laszlo Zsolt Nagy
[EMAIL PROTECTED] wrote:

Hi,
I'm trying to install Python on Windows 2000 Server using remote
desktop. I log as a user that is in administrators group. Instalator
starts, I select default installation directory, on the next screen
with parts to install I click just next. Than blicks screen with
progress bar but it is immediately replaced with screen informing that
installation failed. But there's no information why or what is wrong.
On remote connection I use 16 colors - can it be the problem?
  

Please try to do the same using Start Menu/Control Panel/AddRemovePrograms.
Once I had the same problem and it turned out that when you start the 
Control Panel, the terminal goes into a different mode where you can 
install programs. Without that, you will not be able to add new 
programs. I'm not sure why.

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


junk pointer ????

2005-12-06 Thread Laszlo Zsolt Nagy
  Hi All,

I got this while using Python 2.4 under FreeBSD 5.4:


python in free(): warning: junk pointer, too high to make sense
Segmentation fault (core dumped)


What does it mean?
Thanks,

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


ZSI bug?

2005-12-05 Thread Laszlo Zsolt Nagy

  Hi All,

I'm trying to use ZSI (and SOAP) for the first time. I read somewhere 
that ZSI is the most compete SOAP implementation. I have ZSI-1.7 and 
PyXML-0.8.4. This very simple code:

import ZSI
fname = 'eBaySvc.wsdl'
version = 421
url = 'http://developer.ebay.com/webservices/%s/%s' % (version,fname)
print Creating proxy...
proxy = ZSI.ServiceProxy(url)
print proxy

Throws me:

C:/Python24/pythonw.exe -u  T:/Python/Projects/eBay-SOAP/test.py
Creating proxy...
Traceback (most recent call last):
  File T:/Python/Projects/eBay-SOAP/test.py, line 6, in ?
proxy = ZSI.ServiceProxy(url)
  File C:\Python24\Lib\site-packages\ZSI\ServiceProxy.py, line 34, in 
__init__
wsdl = ZSI.wstools.WSDLTools.WSDLReader().loadFromURL(wsdl)
  File C:\Python24\Lib\site-packages\ZSI\wstools\WSDLTools.py, line 
42, in loadFromURL
wsdl.load(document)
  File C:\Python24\Lib\site-packages\ZSI\wstools\WSDLTools.py, line 
260, in load
schema = reader.loadFromNode(WSDLToolsAdapter(self), item)
  File C:\Python24\Lib\site-packages\ZSI\wstools\XMLSchema.py, line 
80, in loadFromNode
schema.load(reader)
  File C:\Python24\Lib\site-packages\ZSI\wstools\XMLSchema.py, line 
1116, in load
tp.fromDom(node)
  File C:\Python24\Lib\site-packages\ZSI\wstools\XMLSchema.py, line 
2271, in fromDom
self.content.fromDom(contents[indx])
  File C:\Python24\Lib\site-packages\ZSI\wstools\XMLSchema.py, line 
2328, in fromDom
self.derivation.fromDom(i)
  File C:\Python24\Lib\site-packages\ZSI\wstools\XMLSchema.py, line 
2388, in fromDom
component = SplitQName(contents[indx].getTagName())[1]
IndexError: list index out of range

Is this a ZSI bug? Or is it something that is not implemented in ZSI yet?

Unfortunately, eBay's simple XML API is deprecated, I do not want to 
start a new project with that. Also I would not like to use MS .NET or 
Java because I prefer Python, of course. :-)

Thanks,

   Laszlo Nagy



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IE Temporary Internet Files Python

2005-11-10 Thread Laszlo Zsolt Nagy

The script does not seem to work when used on Temporary Internet Files. 
  

Doesn't work well? What does it mean? Is there an exception raised?

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html parser?

2005-10-19 Thread Laszlo Zsolt Nagy
Thorsten Kampe wrote:

* Christoph Söllner (2005-10-18 12:20 +0100)
  

right, that's what I was looking for. Thanks very much.



For simple things like that BeautifulSoup might be overkill.

import formatter, \ 
   htmllib,   \ 
   urllib 

url = 'http://python.org' 

htmlp = htmllib.HTMLParser(formatter.NullFormatter()) 
  

The problem with HTMLParser is that does not handle unclosed tags and/or 
attirbutes given with invalid syntax.
Unfortunately, many sites on the internet use malformed HTML pages. You 
are right, BeautifulSoup is an overkill
(it is rather slow) but I'm affraid this is the only fault-tolerant 
solution.

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html parser?

2005-10-18 Thread Laszlo Zsolt Nagy
Christoph Söllner wrote:

Hi *,

is there a html parser available, which could i.e. extract all links from a 
given text like that:

a href=foo.php?param1=testBARimg src=none.gif/a
a href=foo2.php?param1=testparam2=testBAR2/a


and return a set of dicts like that:

{
  ['foo.php','BAR','param1','test'],
  ['foo2.php','BAR2','param1','test','param2','test']
}


thanks,
Chris 
  

I asked the same question a week ago, and the answer I got was a really 
beautiful one. :-)

http://www.crummy.com/software/BeautifulSoup/

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Outdated documentation

2005-10-17 Thread Laszlo Zsolt Nagy

Hi All,


This is from the documentation of the dbhash module:

Returns the key next key/value pair in a database traversal. The
following code prints every key in the database |db|, without having
to create a list in memory that contains them all:

print db.first()
for i in xrange(1, len(db)):
print db.next()


Apparently, it is different for gdbm:

k = db.firstkey()
while k != None:
print k
k = db.nextkey(k)

I think both of them is outdated. This should be:

for key,value in db.iteritems():
print key,value

Is this the good place to post?

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a spider library

2005-10-12 Thread Laszlo Zsolt Nagy
Fredrik Lundh wrote:

Laszlo Zsolt Nagy wrote:

  

The question: is there a good library for Python for extraction links and 
images
out  of (possibly malformed) HTML soucre code?



http://www.crummy.com/software/BeautifulSoup/
  

Thanks a lot! This is just what I wanted. Why it is not part of the 
standard Python library yet? :-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Very dumb question

2005-10-12 Thread Laszlo Zsolt Nagy
I have a program with this code fragment:

print len(data)
print data[:50]
raise SystemExit

This prints:

20381
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.1//EN

But if I change 50 to 51

print len(data)
print data[:51]
raise SystemExit

then it prints

20381
 !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.1//EN

After all, only the last 50 bytes are printed. The string is the same 
(length 20381) in both cases.
Surprisingly, I can print more than 50 characters, this works:

print 012345678901234567890123456789012345678901234567890123456789A

I'm sure it is my mistake, but I don't know what am I doing wrong. Do 
you have an idea?
Thanks,

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Very dumb question

2005-10-12 Thread Laszlo Zsolt Nagy


I assume the code snippets are exact copy/paste so this is not a typo
(like print data[51:] ...) - and I can't reproduce it here... even with
a string of 20381 characters.
  

Yes, they were cut out. type(data) returns 'type str'.
The data was downloaded from a website, it starts with

!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.1//EN
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd;

Even if it had special control characters in it, I do not understand the 
effect (printing only the first 50 chars).
But probably it is an issue with the terminal, since it is working fine 
on Windows.

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Very dumb question

2005-10-12 Thread Laszlo Zsolt Nagy

i. e. a character after a 'carriage return' ('\r') overwrites part of the
string which therefore doesn't seem to grow. Try 

print repr(data[:51]) 

to see what's really in your data string.
  

Yes, that was it! Thanks for you help. I thought it will be something 
obvious.
The server returned carriage returns in the HTML source code, and I 
tried to print that. :-)

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy
dcrespo wrote:

¡Beautiful and elegant solution!

Two copies of the password: one on the client, the other on the server.

1. Client wants to connect
2. Server generates a random_alphanumeric_string and sends it to the
client
3. Both Client and Server creates a hash string from
password+random_alphanumeric_string
4. Client sends the hash string to the server
5. Server compares his hash result with the hash string received from
de client.

I think it is a very good solution, Isn't it?
  

In fact this is almost an OTP but be aware!
A man-in-the-middle attack can crack your algorithm. This is beacuse you 
create a random string only on one side.
You cannot trust in the connection you are using. You can modify you 
algorigthm to be more secure:

1. Client wants to connect
2. Server generates a server_random_alphanumeric_string and sends it to the
client
3. Client generates a client_random_alphanumeric_string and sends it to the
client too
3. Both Client and Server creates a hash string from
server_random_alphanumeric_string+password+client_random_alphanumeric_string

4. Client sends the hash string to the server
5. Server compares his hash result with the hash string received from
de client.

This is only a bit difference, but is makes sense. An intuder (who knows 
the your algorithm, because getting the code is not as difficult) could 
make a fake server to you, and send back HIS string (that is not 
random). Suppose we have a weakness in the hash function. The intuder 
can exploit this weakness by sending you his special string. The 
modified version has the advantage of sending two random strings, this 
way the intuder cannot take advantage of possible hash function 
weaknesses, because the hash function will be called on a string that is 
random for sure.

Best,

Les


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy

Ignoring all the other issues, any solution which actually requires the 
password to be stored on the server is a bad solution.  Administrators 
should not have access to user passwords, and in addition users should 
not be put in the position of having to trust your server-side security 
to keep their passwords (which they might have used on other systems) 
from being grabbed by hackers.
  

Users will always need to trust in the server. The authentication 
process ensures that the
client is really talking with the desired server and vice versa. But 
even if you know that you
are talking to the right server, you need to trust in the server. The 
administrator of the server
has access to all data. Possibly other persons and softwares too. 
Passwords are not different
from this point of view.

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy

If you really want to do it right, use SRP, http://srp.stanford.edu.
  

This is a bit offtopic here. I read the RFC and I do not see why SRP is 
not vulnerable to dictionary attacks.
If I have a working client software then I can use it to reveal 
passwords. Isn't it a dictionary attack?
Can you please enlighten me?

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy
Paul Rubin wrote:

Laszlo Zsolt Nagy [EMAIL PROTECTED] writes:
  

This is a bit offtopic here. I read the RFC and I do not see why SRP
is not vulnerable to dictionary attacks.
If I have a working client software then I can use it to reveal
passwords. Isn't it a dictionary attack?



Dictionary attack in this context means an eavesdropper records a
session, then compares all the hashed passwords against a word list
offline.  If the attacker is allowed to make unlimited online queries,
then he can guess at SRP passwords too.  But the host should notice
that and prevent it.
  

I see. So the eavesdropper records the random strings and the password 
hash value sent.
Having these values, he can try to find a suitable password in his list 
that will result in the same communication.
He can do this without having to connect to the server again, just by 
replaying the algorithm for a given password
(and the same 'random' strings).

The difference in SRP is that the random strings are private, they will 
never be sent over the network.
So they cannot be eavesdropped. Cracking SRP would require to calculate 
the dividers of a product of
two very big primes (like in RSA). This is why it is hard to use 
dictionary attacks - you cannot replay the
algorithm for a given password.

Thank you, I think I understand now.

   Les



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy

If you're saying that people have no choice but to trust that their 
passwords, stored in the clear on the server of some idiot who didn't 
know better, are safe from casual administrator observation and safe 
from hackers stealing the password file, then you shouldn't be allowed 
anywhere near a supposedly secure system...
  

Of course I would not say this. :-)

If you're just saying that one has to trust that the server you are 
talking to at this instant in time is really the one you thought it was, 
then that's an entirely different issue and I agree.
  

Not just this.
one has to trust that the server you are talking to at this instant in 
time is really the one you thought it was - this is just authentication.
I'm saying that even if the authentication is secure and the server is 
really the one that you wanted to talk with, the server can still be 
vulnerable to other kinds of attacks. Since users are storing data on 
the server, they need to trust in its security. Storing the clear 
passwords is not a good idea, I agree. But having a secure 
authentication method and not storing clear passwords doesn't 
automatically mean that the server is secured. :-)

I'm sorry, I was not clear. I think we were talking about the same thing.

   Les


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing lists

2005-10-10 Thread Laszlo Zsolt Nagy
Odd-R. wrote:

I have to lists, A and B, that may, or may not be equal. If they are not 
identical, I want the output to be three new lists, X,Y and Z where X has 
all the elements that are in A, but not in B, and Y contains all the 
elements that are B but not in A. Z will then have the elements that are 
in both A and B.
  

These are set operations.

One way of doing this is of course to iterate throug the lists and compare 
each of the element, but is there a more efficient way?
  

Maybe, using sets?

L1 = [1,2,3,4]
L2=[3,4,5,6]
diff1 = list(set(L1)-set(L2))   # [1,2]
diff2 = list(set(L2)-set(L1))   # [5,6]
symdiff = diff1+diff2 # Symmetric difference [1,2,5,6]
intersect = set(L1+L2) - set(symdiff) # Intersect [3,4]

Best,

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send password over TCP connection

2005-10-10 Thread Laszlo Zsolt Nagy
How about an OTP (One Time Password) algorithm? It is described in RFC2289.

http://www.faqs.org/rfcs/rfc2289.html

I have a working implementation in Messlib. You can download it an look 
at the MessageSocket.SecureMessageSocket class.
That is a modified version where a good random generator is used instead 
of a finite sequence of passwords.
But it is just example implementation - you can get the idea there and 
develop your own. In fact, my class also has support for
encrypting the communication channel, but the OTP algorithm itself only 
requires a cryptographically secure hash algorithm and a
good random number generator. These are all included in Python. ;-)

I also tried to use SSL before, but I realized that for secure 
password type authentication, OTP is much easier to understand and
use. Of course, SSL can be used for securing the communication line 
WITHOUT AUTHENTICATION, and it is harder to understand
and use.

Best,

   Les



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's Performance

2005-10-08 Thread Laszlo Zsolt Nagy
Dave wrote:

 Hello All,
  
 I would like to gather some information on Python's runtime 
 performance. As far as I understand, it deals with a lot of string 
 objects. Does it require a lot string processing during program 
 execution? How does it handle such time-consuming operations? Is there 
 a way to find out how many string operations (perhaps in the 
 underlying system) ) it does during program execution?

Do you want to know how many internal string operations are done inside 
the Python interpreter? I believe it is not a useful information. There 
are benchmarks testing the *real performance* of Python.

For example: http://www.osnews.com/story.php?news_id=5602


   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help-log in to a web page

2005-10-06 Thread Laszlo Zsolt Nagy
Murugesh wrote:

Hi all,
I'm a newbie to python.I need to login to a webpage after supplying 
usename and password.

import urllib   
sock = urllib.urlopen(http://xop-pc.main.com;)
htmlSource = sock.read()   
sock.close()   
print htmlSource

In the above code how can i supply username and password to that URL.
Thanks for you time.
  

xop-pc.main.com is not an existing site.
Can you tell me what kind of authentication method it is using?
If that is the basic authentication (defined the standard HTTP 
protocol) then you need to read this:

http://docs.python.org/lib/urlopener-objs.html

Basically, you need to subclass URLopener or FancyURLopener, and 
overwrite its prompt_user_passwd method.
That method will be then called whenever the server needs authentication.

Here is a template for you (untested):


from urllib import FancyURLOpener
class MyOpener(FancyURLOpener):
def prompt_user_passwd(host,realm):
   return ('myusername','mypassword')

opener = MyOpener({})
f = opener.open(http://xop-pc.main.com;)
try:
html_source = f.read()
finally:
f.close()



Best,

  Les






-- 
http://mail.python.org/mailman/listinfo/python-list


Class property (was: Class methods)

2005-10-06 Thread Laszlo Zsolt Nagy
Hughes, Chad O wrote:

 Is there any way to create a class method?  I can create a class 
 variable like this:

Hmm, seeing this post, I have decided to implement a 'classproperty' 
descriptor.
But I could not. This is what I imagined:

class A(object):
_x = 0
@classmethod
def get_x(cls):
print Getting x...
return cls._x
@classmethod
def set_x(cls,value):
print Setting x...
cls._x = value
x = classproperty(get_x,set_x)

Usage example:

 print A.x
Getting x
0
 A.x = 8
Setting x
 print A.x
Getting x
8

I was trying for a while, but I could not implement a 'classproperty' 
function. Is it possible at all?
Thanks,

   Les




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help-log in to a web page

2005-10-06 Thread Laszlo Zsolt Nagy


 I tried to view the source,it has,
   
  
  src=/em/cabo/images /t.gif height=80/tdtdtable 
 align=center border=0 cellspacing=2 cellpadding=0tr 
 id=username
 __xc_td align=right nowrapspan class=x8span 
 title=Required class=xc*/spannbsp;*User Name/s
 pan/tdtd width=12img src=/em/cabo/images/t.gif 
 width=12/tdtd valign=top nowrapinput
 id=username class=x4 onkeypress=return 
 _submitOnEnter(event, 'User'); name=j_username size=30
 type=text value=myadmin/td/trtrtd align=right 
 nowrapspan class=x8span title=Required
 class=xc*/spannbsp;Password/span/tdtd 
 width=12img src=/em/cabo/images/t.gif width=12/td
 td valign=top nowrapinput id=M__Id class=x4 
 name=j_password size=30* autocomplete=off type=p
 ...
 ...

Either it is a javascript or a form. Most likely this will be a normal 
form, like:

form method=POST action=login.php
  input name=login type=text
  input name=pwd type=text
/form

This is another authentication method that is used frequently. You need 
to POST the login/password and other parameters to the URL specified by 
the action attribute of the form tag.

Say, if you download the above HTML page from http://here.net/there

then you should POST your login data  to

http://here.net/there/login.php

The response may contain cookies - you need to use them to keep yourself 
logged in.

Please read documentation about these:

- HTML forms
- HTTP cookies

and then read the docs of the urllib module here:

http://www.python.org/doc/current/lib/module-urllib.html

It has parts where you can learn how to POST or GET data.
If you need to handle cookies as well (probably, this is true in your 
case), you might want to change to urllib2

http://www.python.org/doc/current/lib/module-urllib2.html

because it has support for cookies.

Don't do anything until you understand what cookies and HTML forms are.
(And don't ask about them here - it is not about Python programming...)

Best,

   Les
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: /usr/bin/env python, force a version

2005-10-06 Thread Laszlo Zsolt Nagy
[EMAIL PROTECTED] wrote:

I've got a trouble, and i think that anybody there can help me

I've got a python script which i distribute in somes packages for *nix.
This script is full of python and need python 2.4 ! And i'd like to
display a message when the user doesn't have a python2.4 version.
  

  import sys
  sys.version
'2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]'
 

There is also

sys.hexversion
sys.api_version
sys.version_info*

Read this:

*http://docs.python.org/lib/module-sys.html


  Les

**
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: /usr/bin/env python, force a version

2005-10-06 Thread Laszlo Zsolt Nagy
Roel Schroeven wrote:

Laszlo Zsolt Nagy wrote:
  

[EMAIL PROTECTED] wrote:



I've got a trouble, and i think that anybody there can help me

I've got a python script which i distribute in somes packages for *nix.
This script is full of python and need python 2.4 ! And i'd like to
display a message when the user doesn't have a python2.4 version.
 

  

import sys
sys.version
  

'2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]'



Yes, but the problem is also that Debian (not only Sid, but also stable
and testing) has python 2.4 but it is not the default, i.e.
/usr/bin/python is a symlink to /usr/bin/python2.3 even if
/usr/bin/python2.4 is available to.
  

Hmm.

Idea one:

Create a list of possible locations. First of all, use your PATH, and 
then add common locations:

['/bin','/usr/bin','/opt/bin','/usr/local/bin']  # etc.

Then use a list of the possible executable names:

['python','python2.3','python2.4'] # etc

Finally using these combinations, execute each executeable with

python -V

and examine its output. This may work, but I'm affraid there is no 
general solution.
The system administrator can install different python versions to 
virtually any location.
But I don't think you should be affraid of that. If a system admin 
installs different
versions into strange locations, then he will take the responsibility to 
fix python programs
that need a specific version. But in most cases, looking for a python 
executable
on your PATH should be enough; and it is the most I would expect from an 
application. :-)

Last idea:

- create a configuration file that resides beside your Python program
- take the path to the good executeable there
- if the program was started with the wrong version, but you have 
the path to the good one (from the config file), then re-execute
- otherwise print an error message telling the required version AND 
how the user can set it up in the config file

Third idea (for Windows only): read available versions from the 
registry. ;-)

Best,

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class property

2005-10-06 Thread Laszlo Zsolt Nagy
Peter Otten wrote:

Laszlo Zsolt Nagy wrote:

  

I was trying for a while, but I could not implement a 'classproperty'
function. Is it possible at all?



You could define a normal property in the metaclass:
  

The only way I could do this is:

class MyXMetaClass(type):
_x = 0
def get_x(cls):
print Getting x
return cls._x
def set_x(cls,value):
cls._x = value
print Set %s.x to %s % (cls.__name__,value)
x = property(get_x,set_x)

class A(object):
__metaclass__ = MyXMetaClass
   
print A.x
A.x = 8


Results in:

Getting x
0
Set A.x to 8

But of course this is bad because the class attribute is not stored in 
the class. I feel it should be.
Suppose we want to create a class property, and a class attribute; and 
we would like the property get/set methods to use the values of the 
class attributes.
A real example would be a class that keeps track of its direct and 
subclassed instances:

class A(object):
cnt = 0
a_cnt = 0
def __init__(self):
A.cnt += 1
if self.__class__ is A:
A.a_cnt += 1
   
class B(A):
pass
   
print A.cnt,A.a_cnt # 0,0
b = B()
print A.cnt,A.a_cnt # 1,0
a = A()
print A.cnt,A.a_cnt # 2,1

But then, I may want to create read-only class property that returns the 
cnt/a_cnt ratio.
This now cannot be implemented with a metaclass, because the metaclass 
cannot operate on the class attributes:

class A(object):
cnt = 0
a_cnt = 0
ratio = a_class_property_that_returns_the_cnt_per_a_cnt_ratio() # 
def __init__(self):
A.cnt += 1
if self.__class__ is A:
A.a_cnt += 1

Any ideas?

   Les



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python, Mysql, insert NULL

2005-10-05 Thread Laszlo Zsolt Nagy
Python_it wrote:

Python 2.4
MySQL-python.exe-1.2.0.win32-py2.4.zip

How can I insert a NULL value in a table (MySQL-database).
I can't set a var to NULL? Or is there a other possibility?
My var must be variable string or NULL.
Becaus i have a if statement:
if 
  cursor.execute(.insert NULL ..)
if 
  cursor.execute(.insert string ..)

  

Use parameters! For example, did you try:

cursor.execute( insert into tablename(fieldname) values (%s),[value])

None will be converted to NULL, any other value will be quoted as neccesary.

BTW, you did not write which driver are you using.
Usage of parameters is different for each driver, but it is standardized.
If it is DB API 2.0 compatible, then parametrized queries should work as 
desicribed in PEP 0249:

http://www.python.org/peps/pep-0249.html

Under 'cursor objects' section, look for the '.execute' method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python, Mysql, insert NULL

2005-10-05 Thread Laszlo Zsolt Nagy


 BTW, you did not write which driver are you using.

Oh, you did. Sorry. :-( Import your DB module 'yourmodule' and then

print yourmodule.paramstyle

Description of paramstyle is also in PEP249:

paramstyle
  
String constant stating the type of parameter marker
formatting expected by the interface. Possible values are
[2]:

'qmark' Question mark style, 
e.g. '...WHERE name=?'
'numeric'   Numeric, positional style, 
e.g. '...WHERE name=:1'
'named' Named style, 
e.g. '...WHERE name=:name'
'format'ANSI C printf format codes, 
e.g. '...WHERE name=%s'
'pyformat'  Python extended format codes,   

e.g. '...WHERE name=%(name)s'


Best,

   Les

e.g. '...WHERE name=%(name)s'


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the output from os.system() into a variable?

2005-10-05 Thread Laszlo Zsolt Nagy
alexLIGO wrote:

Hi,

I would like to execute some command in python on the bash, e.g.

os.system('globus-job-run mike4.cct.lsu.edu/jobmanager-pbs -l
/bin/date')

and want the result of the output in a vector, so something like:

result=python_command(' command_on_the_bash ')

Is that possible? And how to do that?
  

You can use one of these:

the subprocess module: http://docs.python.org/lib/module-subprocess.html
the popen2 module: http://docs.python.org/lib/module-popen2.html
popen and spawn variants from the os module:  
http://docs.python.org/lib/os-process.html
pexpect (it is not in the standard library):  
http://pexpect.sourceforge.net/

I believe that if you do not need the extended functionality of 
pexpect, then you should start with the subprocess module.
It is the newest.

   Les



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the output from os.system() into a variable?

2005-10-05 Thread Laszlo Zsolt Nagy

result=python_command(' command_on_the_bash ')

Is that possible? And how to do that?



Check out the commands module.

http://docs.python.org/lib/module-commands.html

Hmm, I forgot this one. It is only working from UNIX, am I right?

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: change a value to NULL?

2005-10-05 Thread Laszlo Zsolt Nagy
Bell, Kevin wrote:

I'm pulling a list of numbers from MS Excel, but occasionally if there
is no data from excel, the value is an asterisk, but I need to make it
null.  

What is the best way to do that?  Thus far, I'm using:


for value in myRange:
   try:
   intV = int(value)
   print intV
   except:
   print its an asterisk 
  

I'm affraid I did not understand what is your real problem.
Here is an answer, anyway.

When converting a string intoto an int, you should use TypeError to trap 
type errors only:

try:
  intV = int(value)
except TypeError:
  intV = None

print intV # It will be None if 'value' is not an int

Best,

   Les



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to keep collection of existing instances and return one on instantiation

2005-10-05 Thread Laszlo Zsolt Nagy

I've removed all references to the object, except for the cache.  Do I
have to implement my own garbage collecting is or there some magical
way of doing this within Python?  I pretty much want to get rid of the
cache as soon as there are no other references (other than the cache).

Store weak references to instances.

from weakref import ref

class Spam(object):
cache = {}
def __new__(cls, x):
instance = None
if cls.cache.has_key(x):
instance = cls.cache[x]()
if instance is None:
instance  = object.__new__(cls, x)
cls.cache[x] = ref(instance )
return instance
def __init__(self, x):
self.x = x

Then:

  a = Spam('foo')
  b = Spam('foo')
  a is b
True
  print Spam.cache
{'foo': weakref at 00A1F690; to 'Spam' at 00A2A650}
  del a
  del b
  print Spam.cache
{'foo': weakref at 00A1F690; dead}
 

Well, of course this is still not thread safe, and weak references will 
use some memory (but it can be much less expensive).
You can grabage collect dead weak references periodically, if you wish.

Best,

   Les


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class methods

2005-10-05 Thread Laszlo Zsolt Nagy
Hughes, Chad O wrote:

 Is there any way to create a class method?  I can create a class 
 variable like this:

...

 Any ideas? 

Oh man, it has been a long time I have read such an disturbing question.

RTMF here:  http://docs.python.org/lib/built-in-funcs.html#l2h-14

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class methods

2005-10-05 Thread Laszlo Zsolt Nagy



Oh man, it has been a long time I have read such an disturbing question.

RTMF here:  http://docs.python.org/lib/built-in-funcs.html#l2h-14
  

I feel I was a bit harsh.

class A(object):
x = 0
@classmethod
def f(cls):
   cls.x += 1
   print x is,cls.x

  A.f()
x is 1
  A.f()
x is 2
  A.f()
x is 3

Ashes to my head. :-(

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


email module, redirecting to stdout

2005-10-04 Thread Laszlo Zsolt Nagy

  Hello,

I have this code:

s = smtplib.SMTP()
s.set_debuglevel(1)
s.connect(host=smtp_host)
s.set_debuglevel(0)
log(Connected, sending e-mail)
sys.stdout.flush()   
s.sendmail(
consts.EMAIL_FROMADDRESS,
[to],
msg.as_string()
)
log(E-mail sent OK)
s.quit()

The problem is that whenever I set the debuglevel to 1, messages will go 
to stderr. I would like them to go to stdout. Using

sys.stderr = sys.stdout

has no effect. Redirecting stderr to stdout from the shell is not an 
option for me, because I need to use stderr for other messages.

Thanks,

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: @staticmethod, backward compatibility?

2005-09-27 Thread Laszlo Zsolt Nagy
Neal Becker wrote:

How can I write code to take advantage of new decorator syntax, while
allowing backward compatibility?

I almost want a preprocessor.

#if PYTHON_VERSION = 2.4
@staticmethod
...


Since python  2.4 will just choke on @staticmethod, how can I do this?
  

Decorators are there because

class MyClass:
@staticmethod
def my_method(arg1, arg2, ...):
whatever

is nicer than

class MyClass:
def my_method(arg1, arg2, ...):
whatever
my_method = staticmethod(my_method)

I'm affraid, if you need to be 2.3 compatible then you need to use the 
later form.

   Les


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem subclassing (Newbie)

2005-09-24 Thread Laszlo Zsolt Nagy

Then I have an instance of class Button called obj. My probelm is that 
the test isinstance(obj, Widget) resturns False! 

You must have a typo somewhere. Please try this little test program.

  class Widget(object):
...   pass
...
  class Button(Widget):
...   pass
...
  b = Button()
  isinstance(b,Widget)
True
  isinstance(b,Button)
True
  issubclass(Widget,Button)
False
  issubclass(Button,Widget)
True
 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Indexed variables

2005-09-22 Thread Laszlo Zsolt Nagy

a1=a2=0

def f(x):
if x == a1:
a1 = a1 + 1
elif x == a2:
a2 = a2 + 1


Now if I call f with f(a2) only a1, of course, is incremented because the
if-clause does only check for the value of the input and the values of a1
and a2 are identical.

So how do I define the function such as to discrimate wheter I call it by 
f(a1) or f(a2) ?
  

What you are trying to do is to create a function with a side effect. 
(Side effect is when a function changes its environment. The environment 
of a function is everything that is not local to that function, plus the 
actual parameters and I/O devices.)

If you really want to change an actual parameter inside an object, then 
you should use a mutable object. In Python, there are two kinds of 
objects: mutable and immutable. Immutable objects cannot change their 
value. Integers are immutable. The object zero will always be zero. You 
can add another integer to it, but it will create another object, while 
the zero object will remain zero. There are other immutable objects. For 
example, tuples are immutable.

 t = (1,2,3)

This object is an immutable tuple. You cannot change its value. Mutable 
objects can change their values. For example, lists are mutable.

 L = [1,2,3]

Usually, mutable objects have methods to change their value.

 L.append(4)
 print L

[1,2,3,4]

So if you really want to create a function with a side effect, do 
something like this:


 a1 = [0]
 a2 = [0]


 def f(x):
... if x is a1:
... a1[0] += 1
... elif x is a2:
... a2[0] += 1
...
 a1
[0]
 f(a1)
 a1
[1]
 a2
[0]



But please note that having side effect is generally considered harmful.

Please read the tutorial, these things are explained quite well.

http://docs.python.org/tut/tut.html

Best,

   Les





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Indexed variables

2005-09-22 Thread Laszlo Zsolt Nagy

If you really want to change an actual parameter inside an object, then 
  

inside a function, I mean
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32 service and time.sleep()

2005-09-20 Thread Laszlo Zsolt Nagy
rbt wrote:

I have a win32 service written in Python. It works well. It sends a
report of the status of the machine via email periodically. The one
problem I have is this... while trying to send an email, the script
loops until a send happens and then it breaks. Should it be unable to
send, it sleeps for 10 minutes with time.sleep(600) and then wakes and
tries again. This is when the problem occurs. I can't stop the service
while the program is sleeping. When I try, it just hangs until a reboot.
Can some suggest how to fix this?
  

Yes. Generally, most of the win32 services work like this:

- the main thread listens to win32 service commands
- when starting the service, you should create a new worker thread that 
does the job for you
- when stopping the service, your service should report 
win32service.SERVICE_STOP_PENDING immediately, and ask the worker thread 
to terminate
- you should be continuously reporting win32service.SERVICE_STOP_PENDING 
until your workder thread has stopped

Here is a simple module that uses a 'Processor' class and a new thread 
to do the work.
(The full program is here: http://mess.hu/download/SimpleHTTPService.zip )

class Service(win32serviceutil.ServiceFramework):
_svc_name_ = SERVICE_NAME
_svc_display_name_ = SERVICE_DISPLAY
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.stopped = threading.Event()
self.stopped.clear()
self.logger = getLogger(SERVICE_NAME)

def SvcStop(self):
self.logger.info(Got SvcStop, trying to stop service...)
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.stopped.set()

def SvcDoRun(self):
Write an event log record - in debug mode we will also see 
this message printed.
try:
import servicemanager
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, '')
)
self.logger.info(Started.)
self.logger.debug(Creating processor instance)
processor = Processor(self.stopped)
self.logger.debug(Starting processor thread)
thread.start_new_thread(processor.Process,())
self.logger.debug(Waiting for the processor thread to finish)
self.stopped.wait()
self.logger.debug(Stopping)
time.sleep(1)
while not processor.stopped.isSet():

self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000)
time.sleep(5)
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, )
)
self.logger.info(Stopped)
except:
self.logger.error('',exc_info = sys.exc_info())


if __name__=='__main__':
win32serviceutil.HandleCommandLine(Service)
-- 
http://mail.python.org/mailman/listinfo/python-list


Where is my exception

2005-09-20 Thread Laszlo Zsolt Nagy
I have this code in a wxWidgets program:

class HtmlHintWindow(wx.Frame):
def __init__(self,pos,hint,config):
global _current_hint_window
# Determine the size of the screen
self.screensize = wx.ClientDisplayRect()[2:]
# Calculate the size of the hint ;-)
self.renderer = MegaXMLRenderer()
self.renderer.LoadStyle(config.style)
self.cookie, self.parsed_xml = self.renderer.Parse(hint)
print point 1
try:
self.image = self.renderer.Render(
self.cookie,
self.parsed_xml,
(0,0,self.screensize[0],self.screensize[1]),
draw=True
)
finally:
print point 2
raise

The program prints out point 1 but it does not print point 2. What 
am I missing?

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: testing a website from python

2005-09-20 Thread Laszlo Zsolt Nagy
M.N.A.Smadi wrote:

hi;

I just want to test that a given website is up or not from a python 
script.  I thought of using wget as an os command.  Any better ideas?
  

urllib

http://www.python.org/doc/current/lib/module-urllib.html

If you only want to test if the HTTP port is open or not:

socket

http://docs.python.org/lib/module-socket.html

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is my exception

2005-09-20 Thread Laszlo Zsolt Nagy

The program prints out point 1 but it does not print point 2. What 
am I missing?
  

Sorry from all. I should have been looked at the processor before I 
posted. There is no exception. It was an infinite loop inside the try 
block, but it was called from an event handler. I did not notice that my 
CPU is at 100%. :-(

   Les


 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Doc Problem Example: os.path.split

2005-09-18 Thread Laszlo Zsolt Nagy

is the doc writer, trying to write the doc with some austereness, but
is confused about the behavior of split, or confused about expressing
it? Did his pretension fucked him up?
  

 Dear Xah Lee,

The Python community is very sorry because we have a very bad 
documentation. You are right. The documentation is bad, and the language 
is bad etc. The mailing list itself is not helpful and you cannot use it 
for anything. We will try to follow all of your glorious suggestions.  
But we have so many things to do, I'm affraid you need to wait until 
Python 5000 is released. Until that, I can recommend you the Visual 
Basic language. Its documentation is much more perfect. MSDN is really 
really well structured and easy to use! It is commercial, and - as you 
would expect - you will get immediate fixes after you make a kind 
suggestion like this. I think this is the best thing you can do.

For more information about this fabolous  ClosedSource commercial 
product, please visit this link:

http://msdn.microsoft.com/vbasic/

Good Luck!

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to clear screen in Python interactive shell mode?

2005-09-16 Thread Laszlo Zsolt Nagy
A. L. wrote:

In Python interactive mode, is there some function acting like 'clear'
command in bash?  Could somebody here give some advice?
  

Under Linux/UNIX system (on x86 at least) you can use the CTRL+L 
combination to clear the screen.
I do not now similar for Windows and MACs.

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Self reordering list in Python

2005-09-16 Thread Laszlo Zsolt Nagy

I wonder why you don't use a dictionary? The only time I used a
move-front algorithm I stored algorithms and had to evaluate a
condition to select the correct algo. That means no constant search key
was available for accessing the correct one. In case of an image list I
would implement a self-ordering list if I have to do some pattern
recognition in order to select the correct image. Holding a reference
as a search key a Python hash-table will always have a better average
time complexity no matter which language is used to implement
move-front. 

You are right in that holding a reference will have a better time 
complexity. But holding a reference makes it impossible to free the 
object. :-) As I said, my list has a maximum length. I just can't store 
any number of images in memory. I need to keep only the most frequently 
used ones. I do not know which ones will be used the most frequently, 
this is why I need a self reordering list. Accessing an element makes it 
more imporant than the others. I already implemented this in Python 
and it was ten times faster compared to the original version. (200 
frames per sec instead of 20 fps)

Probably my problem was a no-problem. I realized that it does not 
matter how fast is my list. The most time consuming part is still the 
rendering of the images that are not in the cache. I need to speed up 
rendering and have more RAM, of course. :-)

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Self reordering list in Python

2005-09-15 Thread Laszlo Zsolt Nagy

  Hello,

Do you know how to implement a really efficient self reordering list in 
Python? (List with a maximum length. When an item is processed, it 
becomes the first element in the list.) I would like to use this for 
caching of rendered images. Of course I could implement this in pure 
Python, I just wonder if there is a faster implementation that uses some 
cool feature of the standard library. (Maybe a C implementation could be 
added to the collections module?)

   Les


-- 
http://mail.python.org/mailman/listinfo/python-list


Distutils question

2005-09-08 Thread Laszlo Zsolt Nagy
How how can I install my .mo files from a distutil script into its 
default location?

sys.prefix + os.sep + 'share' + os.sep + 'locale'


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: popen in thread on QNX

2005-09-08 Thread Laszlo Zsolt Nagy
Jacek Popławski wrote:

I am still in the process of creating my script which will run command 
received from socket.
My scripts works perfectly on Linux, but doesn't work on QNX!

File /usr/lib/python2.4/popen2.py, line 108, in __init__
   self.pid = os.fork()
OSError: [Errno 89] Function not implemented

When I try to use os.popen3 - it works. But when I try to use it in new 
thread - I see that error message.
Do you see any solution?
This script must work on QNX, command must be on thread, because I need 
to stop it after timeout. I need popen to see stdout and stderr.
Any ideas?
  

os.popen already creates a new process. So what if you try to call 
os.popen from your main thread, then pass the file descriptors to your 
thread?
It is just an idea...

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: popen in thread on QNX

2005-09-08 Thread Laszlo Zsolt Nagy

os.popen already creates a new process. So what if you try to call 
os.popen from your main thread, then pass the file descriptors to your 
thread?
It is just an idea...



But I need to run command from thread, that's the main reason to create 
new thread :)
  

Ok, but can't your main thread be a server thread with a queue?
Workflow example:

- one of your worker threads wants to run a command
- it creates the argument list and puts it into a message queue
- woker thread starts to sleep
- main thread processes the message queue - it will run popen, put back 
the file descriptors into the message and wake up the worker thread
- the worker thread starts to work with the files

Or, if you create the new thread just to interact with that new process, 
why don't you call popen before you start the thread?
Well, of course this would increase the time needed to start up a new 
worker.

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Distutils extension proposal (was: Re: Distutils question)

2005-09-08 Thread Laszlo Zsolt Nagy
Peter Hansen wrote:

How how can I install my .mo files from a distutil script into its 
default location?

sys.prefix + os.sep + 'share' + os.sep + 'locale'



I can't answer the first question, but the latter should be written this 
way instead

os.path.join(sys.prefix, 'share', 'locale')

for greater portability and maintainability.
  

Of course. :-)

I know that Peter is a big Python guru, and he could not answer the 
question. I also read the archives in the i18n-sig. There were questions 
about the same problem and the answer was that there is no standard way 
to include message files with a distribution. I would like to propose an 
extension in distutils.

Most of the packages contain messages and they should be i18n-ed. The 
proposal itself contains two parts.

1. We should extend the distutils interface to allow message files to be 
installed to the default location

os.path.join(sys.prefix, 'share', 'locale')

2. Domain names for packages should be somehow standardized, especially 
in conjunction with PEP 301 (Package Index and Metadata for Distutils). 
Somehow, the package name and version should identify the message files 
that can be used.

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


The right way to do i18n

2005-09-07 Thread Laszlo Zsolt Nagy

  Hello,

I wonder if there is a standard for making i18n in Python projects. I 
have several Python projects that are internationalized. I also have 
Python packages with i18n. But it is still not clean to me what is the 
recommended way to do it. Currently, I use a module called 
'localization.py' with this code:

from i18n_domain import DOMAIN
import gettext
t = gettext.translation(DOMAIN,'messages',languages=['hu'])
t.install()


But I believe this is not the best way to do it. Problem one: I cannot 
do unit testing and I cannot use pydoc/epydoc for my libraries. They all 
use the _() function but it is installed in the main program only. What 
I do now is this:

import pydoc
import sys
import __builtin__
import os
sys.argv.append('-g')
def _(s):
return str(s)
__builtin__._ = _

pydoc.cli()

But this is very very ugly.

Another problem is with libraries. I have a common library 'LibFoo' and 
several projects 'Project1', 'Project2' etc. I would like to distribute 
my projects and my library as distinct Python (distutil) packages. Of 
course, I would like to include all messages (po, pot and mo files) with 
my distributions. Is there a standard way to do it? I mean, there are 
many packages out there and most of them need i18n. Also there are many 
projects and they also need i18n. But how these two come together? There 
should be a standard way to unify gettext messages from various 
libraries. I'm thinking about a general i18n protocol, where each 
package or module has a standard way to add its own messages to the whole.

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple question: $1, $2 in py ?

2005-09-05 Thread Laszlo Zsolt Nagy

Oh, yes. Right : )
It feels that I miss-looked it.

thank You very much for an advice : )
  

Also try the OptParse module.

http://www.python.org/doc/2.4/lib/module-optparse.html

It handles the GNU/POSIX syntax very well.

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


epydoc CLI and many files

2005-09-05 Thread Laszlo Zsolt Nagy
Hello,

I have a problem under Windows. I use the cli.py program included with 
epydoc. I wrote a small program that lists all of my modules after the 
cli. Something like this:

cli.py  --html  --inheritance=grouped module1.py module2.py module3.py 
..

The problem is that now I have so many modules that the shell (cmd.exe) 
cannot interpret this as a one command. It truncates the command line 
and gives me and error message. (cli.py does not start). Unfortunately, 
I cannot split the documentation into parts, because there are many 
crossreferences. How to overcome this problem?

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


pexpect.exitstatus not working?

2005-09-01 Thread Laszlo Zsolt Nagy

This function:

def scp(from_path,to_path,pwd):
Copy a file with scp.
cmd = '/bin/csh -c scp -q %s %s ; echo XXX' %(from_path,to_path)
print cmd
child = pexpect.spawn(cmd)
child.expect('Password:')
child.sendline(pwd)
child.expect('XXX')
return child.exitstatus

always returns None. This one:

def scp(from_path,to_path,pwd):
Copy a file with scp.
cmd = 'scp -q %s %s ' %(from_path,to_path)
print cmd
child = pexpect.spawn(cmd)
child.expect('Password:')
child.sendline(pwd)
child.interact()
return child.exitstatus

will return the correct exit status. The big problem is that I would 
like to run this function from a cron job. Inside a cron job, interact() 
will not work because it is not connected to a real terminal. How can I 
get the exit status code? Please help me.

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect.exitstatus not working?

2005-09-01 Thread Laszlo Zsolt Nagy
Laszlo Zsolt Nagy wrote:

This function:

def scp(from_path,to_path,pwd):
Copy a file with scp.
cmd = '/bin/csh -c scp -q %s %s ; echo XXX' %(from_path,to_path)
print cmd
child = pexpect.spawn(cmd)
child.expect('Password:')
child.sendline(pwd)
child.expect('XXX')
return child.exitstatus

always returns None. 



How can I 
get the exit status code? Please help me.
  

I could develop a workaround, but this is a real hack, using bourne 
shell and the $? variable.

def scp(from_path,to_path,pwd):
Copy a file with scp.
   
Return the exit code.
cmd = '/bin/sh -c scp -q %s %s ; echo $? ; echo XXX ' 
%(from_path,to_path)
print cmd
child = pexpect.spawn(cmd)
child.expect('Password:')
child.sendline(pwd)
child.expect(XXX)
parts = []
for item in child.before.split('\n'):
if item.strip() != :
parts.append(item.strip())
code = int(parts[-1])
print exit code:, code
if (code != 0):
print parts[0]
return code

Is there a platform independent solution?

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FileIO problem

2005-08-24 Thread Laszlo Zsolt Nagy
Try this:

gclas = raw_input(What is the class:)
def Princlas():
count = 0
while count != 1000:
count = count + 1
return Admin forceclass %s %s  % ( count , gclas )
#asks for file name
a = raw_input(What is new file name:)
out_file = open(a,w)
#this is the input of text
out_file.write(Princlas())
out_file.close()


i know i need to get it to a string but i dont know how?


Your functions should RETURN a string, with the return statement.
Another issue: you cannot write the function itself, only its result:

out_file.write(Princlas())

instead of

out_file.write(Princlas)


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: zlib + Windows 32 service problem (ImportError)

2005-08-17 Thread Laszlo Zsolt Nagy
|

| 
C:\Python24;C:\Python24\DLLs;c:\Python24\Lib\site-packages\win32;c:\oracle\product\10.1.0\db_1\bin;c:\oracle\product\10.1.0\db_1\jre\1.4.2\bin\client;c:\oracle\product\10.1.0\db_1\jre\1.4.2\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program
| Files\Common Files\GTK\2.0\bin
|
| Then I restarted my computer. It is still missing initzlib. :-(
| Please note that I can run the same program as an application, logged in
| as the same user.
|
|  Les

Changing the Windows dll search path doesn't make any difference. It is 
sys.path (Python's search path) that's causing you the headache. Please see 
the mentioned thread for proposed solutions.
  

Great. I could make my service working with this snippet:

import sys
sys.path.insert(0,r'C:\Python24\DLLs')

But this is very ugly. Primarily, I do not want to use absolute path 
names in a this program. I want to use the same code on different 
computers and operating systems, but this code is not portable. 
Secondly, I do not understand why sys.path is different when I start 
python interactively. I believe that sys.path should be the same when 
starting the program as a service. The only difference between the 
application and the service is that the 'main' program of the service 
imports some additional modules. See them below.

iT:\Python\Projects\NamedConnectorpython
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on 
win32
Type help, copyright, credits or license for more information.
  import sys
 
  s1 = str(sys.path)
 
  import win32serviceutil, win32service
  import pywintypes, win32con, winerror
  from win32event import *
  from win32file import *
  from win32pipe import *
  from win32api import *
  from ntsecuritycon import *
 
 
  s2 = str(sys.path)
 
  print s1 == s2
True

I cannot distribute my service until I make it independent of the python 
installation directory.

Why sys.path is different when starting the code as a windows service?
How can I make this code portable?

By the way, you have been a great help. Thank you very much. I can now 
continue working.  :-)

   Les
-- 
http://mail.python.org/mailman/listinfo/python-list


sys.path and win32 services (was: importerror)

2005-08-17 Thread Laszlo Zsolt Nagy

Why do you think str() is needed here?
  

Because I'm not sure if sys.path was overwritten or changed. Some bad 
modules could overwrite sys.path with another list. I know I'm paranoid. :-)

Possibly because sys.path can start with '' which is interpreted as the 
current directory. Perhaps when the code is started as a windows service 
[I know nothing about windows services], the current directory is set to 
%windir%\system32 (where lots of DLLs hang out), and if there is a 
zlib.dll there, it will get picked up first. Try printing the current 
directory (see above).
  

Okay, I did so. I wrote a service that prints out sys.path into a 
logfile. Here is the result:

sys.path=['C:\\Python24\\lib\\site-packages\\win32', 'T:\\Python\\Lib', 
'C:\\WINDOWS\\system32\\python24.zip', 'C:\\WINDOWS\\system32', 
'C:\\Python24\\DLLs', 'C:\\Python24\\lib', 
'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-tk', 
'C:\\Python24\\lib\\site-packages\\win32', 'C:\\Python24', 
'C:\\Python24\\lib\\site-packages', 
'C:\\Python24\\lib\\site-packages\\PIL', 
'C:\\Python24\\lib\\site-packages\\win32\\lib', 
'C:\\Python24\\lib\\site-packages\\Pythonwin', 
'C:\\Python24\\lib\\site-packages\\wx-2.6-msw-ansi', 
'T:\\Python\\Projects\\NamedConnector']

The empty string is not on sys.path. This is very strange, because it is 
different when I start the python interactively. The problem was caused 
by C:\WINDOWS\system32, not the empty string. I'm still not sure why 
it is included in sys.path, and why '' is not there? I also checked the 
Python documentation about sys.path, and read the thread mentioned 
before but still sys.path is magical, and magic is not Pythonic. :-)

Anyway, I think I have found the most platform independent solution. 
Here it is:

  import _socket
  import os
  import sys
  dyndir = os.path.split(_socket.__file__)[0]  # This can be 
/usr/local/lib/python2.4/lib-dynload or C:\Python24\DLLs or whatever
  sys.path.append(dyndir)

In most cases, '_socket.pyd' will be the first module that can be 
imported, and it will by in the dynaload directory for sure.

I feel this is still unclean code. Do you think that it would be nice to 
add new features to the sys module?

sys.dlpath   - could be the path to the lib-dynload or DLLs folder
sys.libpath  - could be the path to the lib folder


Setting the PYTHONVERBOSE environment variable may assist in showing 
where modules are being loaded from.
  

This cannot be used in conjunction with a windows service, because its 
output cannot be seen. :-(


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: zlib + Windows 32 service problem (ImportError)

2005-08-16 Thread Laszlo Zsolt Nagy
vincent wehren wrote:

Laszlo Zsolt Nagy [EMAIL PROTECTED] schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
| Sorry, I realized that the import zlib was not executed from my
| (working) service.
| So here is the question: why can't I use zlib from a win32 service? Is
| there any way to make it working?
|
| -
| Python could not import the service's module
|   File T:\Python\Projects\NamedConnector\Service.py, line 17, in ?
| from Processor import *
|   File c:\Python\Projects\NamedConnector\Processor.py, line 35, in ?
| from mess import MessageSocket
|   File T:\Python\Lib\mess\MessageSocket.py, line 31, in ?
| import zlib
| exceptions.ImportError: dynamic module does not define init function
| (initzlib)
| -
|
|
|
I had a similar problem where a zlib.dll that is *not a Python extension* is 
in sys.path *before* zlib.pyd. Python will try to import this zlib.dll and 
find the  dll doesn't export a initzlib:
for more info see 
http://mail.python.org/pipermail/python-list/2004-October/thread.html#248107
  

Thanks. I set my system environment variable 'PATH' to this:

C:\Python24;C:\Python24\DLLs;c:\Python24\Lib\site-packages\win32;c:\oracle\product\10.1.0\db_1\bin;c:\oracle\product\10.1.0\db_1\jre\1.4.2\bin\client;c:\oracle\product\10.1.0\db_1\jre\1.4.2\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program
 
Files\Common Files\GTK\2.0\bin

Then I restarted my computer. It is still missing initzlib. :-(
Please note that I can run the same program as an application, logged in 
as the same user.

  Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Windows 32 service problem (ImportError)

2005-08-15 Thread Laszlo Zsolt Nagy

  Hi All!

I have a running service (a small web server) implemented in python, 
running as a win32 service. I wrote another program that is very similar 
to the web server but I cannot start the service. From the event log, I 
can read this traceback:

-
Python could not import the service's module
  File T:\Python\Projects\NamedConnector\Service.py, line 17, in ?
from Processor import *
  File c:\Python\Projects\NamedConnector\Processor.py, line 35, in ?
from mess import MessageSocket
  File T:\Python\Lib\mess\MessageSocket.py, line 31, in ?
import zlib
exceptions.ImportError: dynamic module does not define init function 
(initzlib)
-

Facts:

1. I'm using the same module (MessageSocket) for my web server
2. The web server runs fine as a service

Where is the problem? Please help.

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


zlib + Windows 32 service problem (ImportError)

2005-08-15 Thread Laszlo Zsolt Nagy
Sorry, I realized that the import zlib was not executed from my 
(working) service.
So here is the question: why can't I use zlib from a win32 service? Is 
there any way to make it working?

-
Python could not import the service's module
  File T:\Python\Projects\NamedConnector\Service.py, line 17, in ?
from Processor import *
  File c:\Python\Projects\NamedConnector\Processor.py, line 35, in ?
from mess import MessageSocket
  File T:\Python\Lib\mess\MessageSocket.py, line 31, in ?
import zlib
exceptions.ImportError: dynamic module does not define init function 
(initzlib)
-
  


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About size of Unicode string

2005-06-06 Thread Laszlo Zsolt Nagy
Frank Abel Cancio Bello wrote:

Hi all!

I need know the size of string object independently of its encoding. For
example:

   len('123') == len('123'.encode('utf_8'))

while the size of '123' object is different of the size of
'123'.encode('utf_8')

More:
I need send in HTTP request a string. Then I need know the length of the
string to set the header content-length independently of its encoding.

Any idea?
  

This is from the RFC:


 The Content-Length entity-header field indicates the size of the 
 entity-body, in decimal number of OCTETs, sent to the recipient or, in 
 the case of the HEAD method, the size of the entity-body that would 
 have been sent had the request been a GET.

   Content-Length= Content-Length : 1*DIGIT
  

 An example is

   Content-Length: 3495
  

 Applications SHOULD use this field to indicate the transfer-length of 
 the message-body, unless this is prohibited by the rules in section 
 4.4 http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4.

 Any Content-Length greater than or equal to zero is a valid value. 
 Section 4.4 describes how to determine the length of a message-body if 
 a Content-Length is not given.

Looks to me that the Content-Length header has nothing to do with the 
encoding. It is a very low levet stuff. The content length is given in 
OCTETs and it represents the size of the body. Clearly, it has nothing 
to do with MIME/encoding etc. It is about the number of bits transferred 
in the body. Try to write your unicode strings into a StringIO and take 
its length

   Laci

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom for constructor?

2005-06-01 Thread Laszlo Zsolt Nagy
Mac wrote:

Is there a nice Python idiom for constructors which would expedite the
following?

class Foo:
  def __init__(self, a,b,c,d,...):
self.a = a
self.b = b
self.c = c
self.d = d
...

I would like to keep the __init__ parameter list explicit, as is,
rather than passing in a dictionary, as I want the code to be explicit
about what arguments it expects... in effect enforcing the right number
of arguments.
  

I could list the parameter names programatically:

classA(object):
def __init__(self,a,b,c,d,e,f,):
varnames = self.__init__.im_func.func_code.co_varnames
for varname in varnames[1:7]:
print varname
   
a = A(1,2,3,4,5,6)

But I could not get their values.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom for constructor?

2005-06-01 Thread Laszlo Zsolt Nagy

You could try:

class Foo:
   def __init__(self,a,b,c,d):
   args = locals()
   for arg in args.keys():
   if name!='self':
  self.__dict__[arg] = args[arg]
  

Should be:

if arg!='self'

Also it is not perfect. For example:

class Foo:
def __init__(self,a,b,c,d):
temp = 12
self.foo2 = temp + 4
args = locals()
for arg in args.keys():
if arg!='self':
self.__dict__[arg] = args[arg]
   
a = Foo(1,2,3,4)
print dir(a)

Results in:

['__doc__', '__init__', '__module__', 'a', 'b', 'c', 'd', 'foo2', 'temp']

E.g. not only the parameters but all local variables are used...
-- 
http://mail.python.org/mailman/listinfo/python-list


Manipulating mailboxes

2005-05-23 Thread Laszlo Zsolt Nagy

 Hi All,

I need to create a daemon that sits on a server and forwards some 
e-mails. (Well not only that, it needs to change header information 
before forwarding and also insert messages into a database). The mailbox 
module is fine but I do not see a way to delete/add messages - it is 
ready only. The other possiblity is IMAP4 but it is bad because my 
program should not store passwords for all users. I can only see one 
solution right now:

1. Make a copy of the mailbox
2. Truncate the mailbox
3. Process the messages in the copy and forward the e-mails by sending 
out real e-mails.

But this looks so clumsy. Is there a way to delete/add messages to 
mailboxes of different users, directly?

Thanks,

  Laci 2.0

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Manipulating mailboxes

2005-05-23 Thread Laszlo Zsolt Nagy
Maksim Kasimov wrote:

change header information, insert messages into a database, delete/add 
messages, should not store passwords for all users, ... and any things else 
you wish to do - if your OS is UNIX - just forward mail messages of some users 
to your python script (you don't need to write a daemon for this)
All you need is to place file .forward in users home directory, and write 
like this:
|/path/myscript.py
  


and chmod the script:
chmod 777 /path/myscript.py
  

Oh, fantastic. :-) Then I can open stdin and read the e-mail message 
from there.
Thank you so much

Laci 2.0


-- 
http://mail.python.org/mailman/listinfo/python-list


minidom and DTD

2005-05-23 Thread Laszlo Zsolt Nagy

  Hi All,

How can I put the

!DOCTYPE collection SYSTEM recipes.dtd

thing into an XML created by xml.dom.minidom?

Of course I can parse the generated XML file and insert the DOCTYPE string
but there must be a standard way to do this...

Best,

   Laci 2.0


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: minidom and DTD

2005-05-23 Thread Laszlo Zsolt Nagy
Martin v. Löwis wrote:

Laszlo Zsolt Nagy wrote:
  

How can I put the

!DOCTYPE collection SYSTEM recipes.dtd

thing into an XML created by xml.dom.minidom?



You should put a DocumentType node into your
DocumentNode, and pass a qualifiedName of
collection and a systemId of recipes.dtd
to the createDocumentType call.
  

That worked, thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EpyDoc problem

2005-05-19 Thread Laszlo Zsolt Nagy

EpyDoc is hosted in Sourceforge. This alone may answer your question
about a bug-tracker:

http://sourceforge.net/tracker/?atid=405618group_id=32455func=browse
  

Well, I wrote to the bug tracker some days ago but no answer so far.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super() and automatic method combination

2005-05-18 Thread Laszlo Zsolt Nagy


I have the impression that this is supposed to call the f method
in both A and B, so it should print
  

Not really true. The first parameter of 'super' should be a type, not an 
instance.

   A
   B
   C
or maybe
  B
  A
  C
depending on the resolution order.  However, it only calls A.f and not B.f.

I also notice that if I say


class B(object):
def f(self):
super(B,self).f()
print 'b'

then 
  test(B)
raises an exception since B has no superclass with an f method.  

Correct. When you use super(B,self) it accesses the current instance as 
the class B. If it has no method named 'f' then this will end up in an 
exception.

That doesn't seem like such a good thing necessarily.
  

But yes, it is. When you try to call a nonexistent method, it should 
raise an exception.

Anyway, is there a preferred way of writing this example so that C.f
automatically calls both A.f and B.f?
  

I do not know a preferred way. However, I made this example for you, I 
hope it helps.


class CallSupersMixin(object):
def callsupers(self,fname,*args,**kwargs):
l = self.__class__.__bases__
for cls in l:
if hasattr(cls,fname):
getattr(cls,fname)(self,*args,**kwargs)
elif cls == CallSupersMixin:
pass
else:
raise AttributeError(Base class %s does not have a 
method named %s  % ( str(cls),fname ) )
   
   
class A(object):
def f(self):
print 'A.f called'
   
class B(object):
def f(self):
print 'B.f called'
   
class AB(A,B,CallSupersMixin):
def f(self,*args,**kwargs):
self.callsupers('f',*args,**kwargs)
   
ab = AB()
ab.f()


Of course you can remove the raise AttributeError part. Then it will 
call only the classes that have the given method.
I know it is not a very good example but you can go from here.
Best,

   Laci 2.0

-- 
_
  Laszlo Nagy web: http://designasign.biz
  IT Consultant   mail: [EMAIL PROTECTED]

Python forever!


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super() and automatic method combination

2005-05-18 Thread Laszlo Zsolt Nagy

The trick is that C.f only calls A.f, but A.f needs to end up calling B.f 
when it is used in a C.
  

I believe your response only applies to single inheritance. For classes 
with muliple bases classes, you need to call the base methods one by one.

BTW I prefer to call the base methods in this form:

class AB(A,B):
def f(self):
   A.f(self)
   B.f(self)

This arises the question: is there a difference between these:

super(A,self).f()  # I do not use to use this
A.f(self)

-- 
_
  Laszlo Nagy web: http://designasign.biz
  IT Consultant   mail: [EMAIL PROTECTED]

Python forever!


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super() and automatic method combination

2005-05-18 Thread Laszlo Zsolt Nagy

Which is fine so long as nobody else tries to add further subclasses later:

class C(B): ...
class Mine(AB,C): ...

Mine().f()

Using super throughout this works (it calls f in Mine, AB, A, C, B, and 
then Base), but your explicit call to the base classes means that if you 
don't call C.f() explicitly from Mine it never gets called, and if you do 
call it explicitly from Mine it gets called *after* B.f() has been called 
(and B.f() probably ends up being called twice).
  

Okay, I understand now. It was a good learning session for me. :-)
At this moment I do not see a problem where I would need a diamond 
shaped inheritance graph but
I'll keep in mind the difference between super and direct calls. :-)

I tested this and I realized that if you change the parameter list in 
the descendants then it is not wise to use super.
I'm going to publish the example below, I hope others can learn from it too.

Example (good):

class A(object):
def f(self):
print A.f called
   
class B(A):   
def f(self):
super(B,self).f()
print B.f called
   
class C(A):   
def f(self):
super(C,self).f()
print C.f called   
   
class D(B,C):   
def f(self):
super(D,self).f()
print D.f called   
   
   
d = D()
d.f()

Results in:

A.f called
C.f called
B.f called
D.f called

Example (bad):

class B(A):   
def f(self,what):
super(B,self).f()
print B.f called (%s) % what

Will result in:

C:/Python24/pythonw.exe -u  C:/Python/Projects/Test4/test4.py
Traceback (most recent call last):
  File C:/Python/Projects/Test4/test4.py, line 22, in ?
d.f()
  File C:/Python/Projects/Test4/test4.py, line 17, in f
super(D,self).f()
TypeError: f() takes exactly 2 arguments (1 given)

Of course you cannot tell if super(C,self).f() will call A.f or not 
(when add another
subclass under class A, it will change the MRO...)

If you do not want to add any other subclasses then probably you can use

super(C,self).f('foo')

but in that case it is equivalent to

A.f(self,'foo')

Best,

   Laci 2.0



-- 
_
  Laszlo Nagy web: http://designasign.biz
  IT Consultant   mail: [EMAIL PROTECTED]

Python forever!


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EpyDoc problem

2005-05-18 Thread Laszlo Zsolt Nagy

Looks like it is a problem with wxWidgets. There is no problem if I do 
not import wx. How to overcome this problem?
Currently I cannot document modules that import wx. :-(
  

I found the answer on the wxPython-users list.
It is disappointing that the standard documentation tool has no support. 
:-(
I had to patch EpyDoc. The author was not responding and there is no 
mailing
list for EpyDoc. Is it still a live project?

-- 
_
  Laszlo Nagy web: http://designasign.biz
  IT Consultant   mail: [EMAIL PROTECTED]

Python forever!


-- 
http://mail.python.org/mailman/listinfo/python-list


EpyDoc problem

2005-05-17 Thread Laszlo Zsolt Nagy

  Hello,

I would like to create documentation for my lib using EpyDoc.
I do not see how to report bugs on the EpyDoc home page.
When I try to create documentation, I get this error:

Internal error: Expected a pointer
Unhandled exception in thread started by function document at 0x00A44C30

At the end of the traceback:

wx\_misc.py line 3665, in _eq_
return _misc_.DateTime.__eq__(*args)
TypeError: Expected a pointer

I have no clue what does it mean but I guess it is an EpyDoc bug.
Does anyone ran into the same problem? Any ideas?

-- 
_
  Laszlo Nagy web: http://designasign.biz
  IT Consultant   mail: [EMAIL PROTECTED]

Python forever!


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EpyDoc problem

2005-05-17 Thread Laszlo Zsolt Nagy


At the end of the traceback:

wx\_misc.py line 3665, in _eq_
return _misc_.DateTime.__eq__(*args)
TypeError: Expected a pointer

I have no clue what does it mean but I guess it is an EpyDoc bug.
Does anyone ran into the same problem? Any ideas?
  

Looks like it is a problem with wxWidgets. There is no problem if I do 
not import wx. How to overcome this problem?
Currently I cannot document modules that import wx. :-(

-- 
_
  Laszlo Nagy web: http://designasign.biz
  IT Consultant   mail: [EMAIL PROTECTED]

Python forever!


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python instances

2005-04-20 Thread Laszlo Zsolt Nagy

Guess i shouldn't think of the __init__(self) function as a constructor
then.
 

__init__ is THE constructor in Python
--
_
 Laszlo Nagy  web: http://designasign.biz
 IT Consultantmail: [EMAIL PROTECTED]
Python forever!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Faster os.walk()

2005-04-20 Thread Laszlo Zsolt Nagy
fuzzylollipop wrote:
I am trying to get the number of bytes used by files in a directory.
I am using a large directory ( lots of stuff checked out of multiple
large cvs repositories ) and there is lots of wasted time doing
multiple os.stat() on dirs and files from different methods.
 

Do you need a precise value, or are you satisfied with approximations too?
Under which operating system? The 'du' command can be your firend.
man du
Best,
  Laci 2.0

--
_
 Laszlo Nagy  web: http://designasign.biz
 IT Consultantmail: [EMAIL PROTECTED]
Python forever!
--
http://mail.python.org/mailman/listinfo/python-list


Re: logging to two files

2005-04-20 Thread Laszlo Zsolt Nagy
Tor Erik Sønvisen wrote:
Hi
Have the following code:
import logging
   logging.basicConfig(level = logging.DEBUG,
   format = '[%(levelname)-8s %(asctime)s] 
%(message)s',
   filename = 'rfs.log',
   filemode = 'w')

When using logging.(debug, info etc) stuff is logged to rfs.log.
How may I specify another log with different charateristics, such as a 
different file

regards 

 

I'm not sure if I understood your problem. However, just a tip for you: 
is it possible to create your own handler object? (See section 6.29.5 in 
the library reference).
You could setup a handler object that holds a list of other handler 
objects and distribute all logging events to them. This way you should 
be able to add/remove handlers at runtime.

Best,
  Laci 2.0
--
_
 Laszlo Nagy  web: http://designasign.biz
 IT Consultantmail: [EMAIL PROTECTED]
Python forever!
--
http://mail.python.org/mailman/listinfo/python-list


Re: modules and namespaces

2005-04-19 Thread Laszlo Zsolt Nagy

However it doesn't work until I import the string module into m1 and m2
modules. I found in the manual that imported modules will be searched in
the container module first. Is it more efficient to import the string
module into main and m1 and m2 than importing only into m1 and m2?
 

I bet the most efficient is
str.join( ('a','b'))
The reason is that 'str' is a built-in type. But since new style classes 
were introduced, they are also real objects with methods. :-)

p.s.: Hello Mage. I'm also known as nagylzs at enternet dot hu. Do you 
remember me from the SQL list? Good to see you here. :-)

--
_
 Laszlo Nagy  web: http://designasign.biz
 IT Consultantmail: [EMAIL PROTECTED]
Python forever!
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >