Re: What does mod_python.publisher handler do?

2006-09-04 Thread Steve Holden
yaru22 wrote:
 I was reading Chapter 6.1 in mod_python manual at www.python.org.
 
 The manual simply says:
 
 The publisher handler is a good way to avoid writing your own handlers
 and focus on rapid application development.
 
 I still don't understand what this publisher handler is for.
 
 Can someone elaborate the above phrase with some examples please?
 
 Thanks in advance.
 
I think perhaps your reading of the documentation has been a little less 
than assiduous. Does


 http://www.modpython.org/live/current/doc-html/hand-pub.html

make it any clearer? There the examples show you exactly how to use the 
handler, and the point of providing it is to allow you to use mod_python 
without going to the trouble of writing your own handler.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: how can i change the text delimiter

2006-09-04 Thread sonald
Hi,
Thanks a lot for the snips you have included in your post...
those were quite helpful...

And about the 3rd party data
we receive the data in csv format ... but we are not supposed to modify
the files provided by the user directly...

Instead we make another file with the same name  different
extensions... and use the new files created by the python for further
processing

 quote_char
 Defines the character used to quote fields that
 contain the field separator or newlines.  If set to None
 special characters will be escaped using the escape_char.
 # That's what you are looking for #

Yes you got me right
I was indeed looking for the quote_char...

 Aha!! Looks like some misguided person has got a copy of the
 object-craft code, renamed it fastcsv, and compiled it to run with
 Python 2.4 ... so you want some docs. The simplest thing to do is to
 ask it, e.g. like this, but with Python 2.4 (not 2.2) and call it
 fastcsv (not csv):


I guess... that's true... ;)

Thank you very much.




Thanks a lot for the reponse
John Machin wrote:

 sonald wrote:
  Hi,
  I am using
  Python version python-2.4.1 and along with this there are other
  installables
  like:
  1. fastcsv-1.0.1.win32-py2.4.exe

 Well, you certainly didn't get that from the object-craft website --
 just go and look at their download page
 http://www.object-craft.com.au/projects/csv/download.html -- stops dead
 in 2002 and the latest windows kit is a .pyd for Python 2.2. As you
 have already been told and as the object-craft csv home-page says,
 their csv was the precursor of the Python csv module.


  2. psyco-1.4.win32-py2.4.exe
  3. scite-1.63-setup.exe
 
  We are freshers here, joined new... and are now into handling this
  module which validates the data files, which are provided in some
  predefined format from the third party.
  The data files are provided in the comma separated format.
 
  The fastcsv package is imported in the code...
   import fastcsv
  and
   csv = fastcsv.parser(strict = 1,field_sep = ',')

 Aha!! Looks like some misguided person has got a copy of the
 object-craft code, renamed it fastcsv, and compiled it to run with
 Python 2.4 ... so you want some docs. The simplest thing to do is to
 ask it, e.g. like this, but with Python 2.4 (not 2.2) and call it
 fastcsv (not csv):

 ... command-prompt...\python22\python
 Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
 Type help, copyright, credits or license for more information.
  import csv
  help(csv.parser)
 Help on built-in function parser:

 parser(...)
 parser(ms_double_quote = 1, field_sep = ',',
auto_clear = 1, strict = 0,
quote_char = '', escape_char = None) - Parser

 Constructs a CSV parser object.

 ms_double_quote
 When True, quotes in a fields must be doubled up.

 field_sep
 Defines the character that will be used to separate
 fields in the CSV record.

 auto_clear
 When True, calling parse() will automatically call
 the clear() method if the previous call to parse() raised
 an
 exception during parsing.

 strict
 When True, the parser will raise an exception on
 malformed fields rather than attempting to guess the right
 behavior.

 quote_char
 Defines the character used to quote fields that
 contain the field separator or newlines.  If set to None
 special characters will be escaped using the escape_char.
 # That's what you are looking for #
 escape_char
 Defines the character used to escape special
 characters.  Only used if quote_char is None.

  help(csv)
 Help on module csv:

 NAME
 csv - This module provides class for performing CSV parsing and
 writing.

 FILE
 SOMEWHERE\csv.pyd

 DESCRIPTION
 The CSV parser object (returned by the parser() function) supports
 the
 following methods:
 clear()
 Discards all fields parsed so far.  If auto_clear is set to
 zero. You should call this after a parser exception.

 parse(string) - list of strings
 Extracts fields from the (partial) CSV record in string.
 Trailing end of line characters are ignored, so you do not
 need to strip the string before passing it to the parser.
 If
 you pass more than a single line of text, a csv.Error
 exception will be raised.

 join(sequence) - string
 Construct a CSV record from a sequence of fields.
 Non-string
 elements will be converted to string.

 Typical usage:

 import csv
 p = csv.parser()
 file = open('afile.csv')
 while 1:
 line = file.readline()
 if not line:
 break
 fields = 

Re: Exception EOFError.

2006-09-04 Thread Sybren Stuvel
Dennis Lee Bieber enlightened us with:
 The above is windows, I believe Linux uses ctrl-d instead of
 ctrl-z

That's correct. And so do all unix systems including MacOS X.

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Twisted vs POS (Plain-old sockets)

2006-09-04 Thread Guido Goldstein

Hi!

On Sun, 3 Sep 2006 00:19:17 -0700
  Darren Kirby [EMAIL PROTECTED] wrote:
[...]
 I guess I am wondering if given the fact I need a custom protocol, and need
 to
 talk TCP/IP should I stick with twisted or just use plain old sockets and
 build it myself? Is there a third option I should consider? Have others
 found
 themselves in this situation? Thoughts? Comments? I am really just fishing
 for opinions here...

You might have a look at asyncore/asychat in the standard library.
It does the async stuff for you and it's easy to understand and to
use.

Hope it helps.

Cheers
  Guido G.
-- 
http://mail.python.org/mailman/listinfo/python-list


upgrade 2.4 - 2.5 HowTo

2006-09-04 Thread Helmut Jarausch
Hi,

what has to be done for upgrading from Python 2.4 to 2.5?

- How can I find out which packages (in addition to the core packages) have been
   installed up to now
- Can I just copy   /usr/local/lib/python2.4/site-packages  to
 /usr/local/lib/python2.5 ?

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Reading config.ini in PythonWin.

2006-09-04 Thread Vesa Leppanen
Hi,

I am new in python-list and quite new in Python programming as well. I
am working mainly with GIS and using Esri's geoprocessing tools.

I want to use .ini file to set the parameters, especially paths, in my
project. PythonWin 2.1. is my version.

Why do I get the default back in the case below? Any way around?

The Paths,Temp is c:/temp.

 win32ui.SetProfileFileName('D:\\config.ini')
 Temp = win32ui.GetProfileVal('Paths','Temp','c:/')
 print Temp
c:/

-- 

I saw one old thread but didn't se any solution there.

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


fcntl() and packing structs with unions.

2006-09-04 Thread tyler
I'm having some trouble building a proper argument for an ioctl call.
The operation I'm working with is TUNSETIFF _IOW('T', 202, int) which
takes a struct ifreq as the arg.  Could someone familiar with the
struct (usually defined in net/if.h) tell me how the heck to encode it
using the struct/array module?  An example would be fantastic.



Thanks

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


Re: upgrade 2.4 - 2.5 HowTo

2006-09-04 Thread Steve Holden
Helmut Jarausch wrote:
 Hi,
 
 what has to be done for upgrading from Python 2.4 to 2.5?
 
 - How can I find out which packages (in addition to the core packages) have 
 been
installed up to now
 - Can I just copy   /usr/local/lib/python2.4/site-packages  to
  /usr/local/lib/python2.5 ?
 
Alas, no, this will only work for pure Python packages.

If any of your packages are extensions in compiled languages 
(typically C or C++) then they need to be completely rebuilt, as the 
interpreter API changes between releases.

Technically you should be able to copy the pure Python packages and 
midules across, althought eh .pyc file format alos differs between 
releases. However, the .pyc files will all be rebuilt automatically when 
they are required.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: CONSTRUCT -

2006-09-04 Thread Georg Brandl
lazaridis_com wrote:
 Georg Brandl wrote:
 lazaridis_com wrote:
  I would like to fulfill the following task:
 
  The construct:
 
  if __name__ == '__main__':
 
  should be changed to something like:
 
  if identifier.name == '__main__':
 
  The term identifier should be selected based on the meaning of the
  __double-underscore-enclosure__ of the entities.
 ...
 
 import sys
 class _identifier:
 def __getattr__(self, name):
 return sys._getframe(1).f_globals['__%s__' % name]
 identifier = _identifier()
 
 ok, I understand.
 
 this one would work with modules.
 
 but how would look a more general solution, which would work with
 objects too?

Why can't you try to come up with something yourself? You should have
had enough exposure to the Python language by now.

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


Re: raw audio in windows

2006-09-04 Thread Ben Sizer
Jay wrote:
 So, are you saying this would be possible to do with the PlaySound
 function?

Fredrik is often terse. ;)  I think what he's saying is that when I
said you could pass a .wav file to an external application, he showed
that you could pass it to a Python module instead. I think you still
need to get it into .wav format first, though this can apparently be in
memory rather than on disk.

-- 
Ben Sizer

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


Newbie XML Output question

2006-09-04 Thread kryten21
Hi,

I was wondering if someone could help me with a problem I've been
having with mod-python and a javascript application I'm running.  When
I run a GET on the actual XML file from the javascript, I can easily
parse the file.  However, when I use a mod-python handler and run this
code:

LOCAL_FILE = 'htdocs/ethan/info.xml';

def get_request(req):
if req.method == 'GET':
req.content_type = text/xml
req.sendfile(LOCAL_FILE)
req.write(file)
return apache.OK

The file is sent but the same code that parsed the actual file can't
parse what is sent through this request.  Is there some kind of special
formatting that is required to properly send back XML to a javascript
xmlhttprequest()?

Any help would be greatly appreciated,

Ethan

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


Re: Newbie XML Output question

2006-09-04 Thread kryten21
Sorry, there should be no req.write(file) there.


 def get_request(req):
   if req.method == 'GET':
   req.content_type = text/xml
   req.sendfile(LOCAL_FILE)
   req.write(file)
 return apache.OK


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


Re: Syntax suggestion.

2006-09-04 Thread samir

Alex Martelli wrote:
 What a mess it would be to disambiguate statements such as

 x = foo bar baz bat

 is it x = (foo, bar, baz, bat)
 or x = foo(bar, baz, bat)
 or x = foo(bar(baz), bat)
 or x = foo(bar, baz(bat))
 or x = foo(bar(baz, bat))

It will be x=foo(bar,baz,bat). The parenthese ommition would only be
valable for the first function call in the statement.

 or ... [even ignoring the possibility that one or more of these might be
 functions callable without arguments...!!!]...

That won''t be a problem: x=foo bar(baz) bat would be equivalent to
x=foo(bar(baz),bat).
Or, but least realistic, it would be in the scheme trend. For example:

a=b(c,d(e,f(g,h,i,j,k))) == a=b c (d e (f g h i j k))

It looks nicer, isn't it? :)

 iPython has some heuristics that may be reasonable for the commandline
 (and are, in any case, at least simple), but in practice I find that I
 go back to using the good old interactive Python interpreter rather than
 putting up with even those simple heuristics.

That depends of your need to such tools. For example if you need to
copy a file, then, resolve a linear system then chroot and set the
password as de hexadecimal representation of the hash function of pi
multiplied by the averge of the solution coordinations +_+, you'll need
IPython ;)

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


What are super()'s semantics?

2006-09-04 Thread Mike Krell
I'm reading Alex Martelli's Nutshell second edition.  In the section
called Cooperative superclass method calling, he presents a diamond
inheritance hierachy:

class A(object):
def met(self):
print A.met
class B(A):
def met(self):
print B.met
A.met(self)
class C(A):
def met(self):
print C.met
A.met(self)
class D(B,C):
def met(self):
print D.met
B.met(self)
C.met(self)


D().met() # essentially D B A C A

Martelli says In this code, when we call D().met(), A.met ends up being
called twice. How can we ensure that each ancestor's implementation of
the method is called once, and only once? The solution is to use
built-in type super. super(aclass, obj), which returns a special
superobject of object obj. When we look up an attribute (e.g., a method)
in this superobject, the lookup begins after class aclass in obj's
MRO. We can therefore rewrite the previous code as:

class A(object):
def met(self):
print A.met

class B(A):
def met(self):
print B.met
super(B, self).met()

class C(A):
def met(self):
print C.met
super(C, self).met()

class D(B,C):
def met(self):
print D.met
super(D, self).met()

D().met() # essentially D B C A


Now, D().met() results in exactly one call to each class's version of
met.

I see that this is true, but I am confused by the explanation (the bit
about truncated lookup in the class's MRO).  In particular:

1. The super() call in D somehow invokes both parent class methods
   instead of stopping when the method is resolved in B. This has
   nothing to do with truncated lookup per se.  Why isn't the output D
   B A?

2. If I understand correctly, B's MRO is (B, A) and super(B, self) would
   have an MRO of (A).  Similarly for C.  So it seems that by the above
   explanation, A.met() would still be invoked twice (assuming both
   B.met() and C.met() are invoked).

I guess I can just take it on faith that super() invokes everything once
and only once, but I'd rather understand how.  Can someone point me to a
more complete description of super()'s semantics and how they work?

BTW, the official docs are even worse in this regard.  AFAICT, they
essentially say that super() returns a superclass with no discussion of
diamond inheritance or any hint of how the semantics of super(B,
self).met() would be any different than those of A.met(self).

This seems like very important functionality to be documented in the
official docs so poorly.

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


Better way to replace/remove characters in a list of strings.

2006-09-04 Thread Chris Brat
Hi,

Is there a better way to replace/remove characters (specifically ' and
 characters in my case, but it could be anything) in strings in a
list, than this example to replace 'a' with 'b':



x = [a,123a,as]

for i, v in enumerate(x) :
x[i] = v.replace(a,b)


This works, but I'd like to know peoples opinions.

Thanks
Chris

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


Re: a new object definition

2006-09-04 Thread Sylvain Ferriol
 Michele Simionato already pointed you to `PEP 359`_.  One of the reasons 
 that I withdrew it was that people seemed to feel that you could get 
 most of what you want now by defining appropriate metaclasses.  In your 
 case, for example, the appropriate metaclass and its usage might look 
 like::
 
  def instance(name, bases, dict):
 ... cls = dict.pop('__class__')
 ... dict.pop('__metaclass__')
 ... dict.pop('__module__') # silently added by class statement
 ... return cls(**dict)
 ...
  class C(object):
 ... def __init__(self, a, b):
 ... self.a = a
 ... self.b = b
 ...
  class c:
 ... __metaclass__ = instance
 ... __class__ = C
 ... a = 'foo'
 ... b = 'bar'
 ...
  c.a, c.b
 ('foo', 'bar')
 
 Sure, it's misleading to use a class statement when you're not actually 
 creating a class, but I guess people felt that wanting to do this was 
 uncommon enough that they weren't worried about it.

i know that there is always a solution. But this problem show that 
python and others are not coherent in the syntax (contrary to lisp for 
example).

with the 'make' syntax, it will be really easy to translate a program or 
a data structure defined in XML format into python syntax.

i do not know how many use-cases we need for changing a PEP status :)

another advantage is that we have the same syntax in all definition 
levels: metaclass, class, instance.
and if we just want to use objects and do a sort of 'prototype 
programming', we can with this syntax.
example:
instance my_obj(prototype_obj):
   ...
   ... object specialisation
   ...

sylvain



 .. _PEP 359: http://www.python.org/dev/peps/pep-0359/
 
 STeVe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re.compile() doesn't work under Windows?

2006-09-04 Thread Sibylle Koczian
ddtl schrieb:
 Thanks everybody for pointing out the problem.
 And indeed, the script was named differently on Linux.
 
 ddtl.

And because I just spent a day searching all the wrong corners: you
remembered to delete or rename the re.pyc that the first import
probably left in the same directory you had re.py in?

-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python loops

2006-09-04 Thread Nicko
Steve Holden wrote:
 Nicko wrote:
  Fredrik Lundh wrote:
 if you cannot refrain from pulling arguments out of your ass, you not
 really the right person to talk about hygiene.
 
  I'm impressed but your mature argument. Clearly, in the face of such
  compelling reasoning, I shall have to concede that we should all
  generate our range lists up front.
 
 I'm impressed that you think any of this will be news to the effbot,
 whose sagacity is exceeded only by his irritability in the face of
 ignorance.

Well, I may not have written as much award winning Python software as
Fredrik, but sagacity usually implies wisdom and good judgement rather
than mere knowledge.  Still I'm hard pressed to see why suggesting
that, when I want to iterate a number of times, I should use an
iterator that goes around a number of times (and appreciate the bounded
storage requirements that result) rather than writing down the list of
numbers and then selecting each in turn, should warrant such an
outburst.

One wonders if the authors of PEP 3100, the outline plans Python 3.0,
are all premature optimisation freaks too. After all it states that
sooner or later the built in range function will return an iterator and
those of us who prefer to iterate rather than count on our
fingers/lists will have yet another optimisation; we'll not need to put
an x in front of our ranges.

Nicko

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


Re: Classes referencing each other

2006-09-04 Thread Manuel Bleichner
   Does the EMCenter really need to /subclass/ from all of those? Or
 would it be better to make some of those attributes of an EMCenter
 INSTANCE (passing in instances of the others to the __init__() ).

   class EMCenter(object):
   def __init__(self, b, r, c, ol):
   self.building = b
   self.researcher = r
   ...

   IOW: the difference between:
   an EMCenter IS a building AND
   IS a researcher AND
   IS a constructor AND
   IS a OnLand

= These relations are correct:
the EM Center can build units and research technologies, therefore
it is a researcher and constructor.


 Note that OnLand already sounds like an attribute -- and at that,
 maybe an attribute of Building

Yes, this one is really an attribute, but it's not yet implemented and
I wasn't sure how to do it when I wrote the template code.


   As soon as you get a recursive definition, you MUST split...

Yes =(
I'll have to try to reduce such relations to a minimum...
It would have just been nice to declare and later define the classes,
but such a feature would bloat the neat python syntax.

Thanks for all the text you wrote, but it all went a bit in the
wrong direction, sorry :)


Manuel

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


Re: Broadcast server

2006-09-04 Thread swell
Thx Alex,
  This is exactly what i want to look at . Async will definitely be
something i will look at . Does it make sense to mix async and threaded
server ( let say a threaded server accepting max 10 connections and
dealing with client request asynchronously ). Does it sounds you a good
design.

Of course i will have a look a twisted that sounds me doing all the job
( for sure better that i can do ) .

Thx
Manu

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


Re: Better way to replace/remove characters in a list of strings.

2006-09-04 Thread Philipp Pagel
Chris Brat [EMAIL PROTECTED] wrote:
 Is there a better way to replace/remove characters (specifically ' and
  characters in my case, but it could be anything) in strings in a
 list, than this example to replace 'a' with 'b':

x = map(lambda foo: foo.replace('a', 'b'), x)

cu
Philipp

-- 
Dr. Philipp Pagel  Tel. +49-8161-71 2131
Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186
Technical University of Munich
http://mips.gsf.de/staff/pagel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: working with ldap files

2006-09-04 Thread Michael Ströder
flit wrote:
 
 I am struggling with some ldap files.

More general you are struggling with multiple attribute values of DN
syntax stored in a single field of a CSV file.

 I am using the csv module to work with this files (I exported the ldap
 to a csv file).

I guess you have MS AD and used MS tools for CSV export.

 I have this string on a field
 CN=pointhairedpeoplethatsux,OU=Groups,OU=Hatepeople,OU=HR,DC=fabrika,DC=com;CN=pointhairedboss,OU=Groups,OU=Hatepeople,OU=HR,DC=fabrika,DC=com
 this string is all the groups one user has membership.

It seems they are using ; as a delimiter for multi-valued attributes in
a single CSV field. Note that ; is also a special character for
LDAPv2-DNs. So a naive parsing will fail under special circumstances.

I'd recommend to export your data as LDIF and use the module 'ldif' from
python-ldap to extract the entry records. You can use this module
separately simply by placing the file ldif.py under site-packages/ if
you don't need the rest of python-ldap.

 So what I am trying to do.
 read this string
 and extract only the CNs

This is another issue.

Note that in general DN parsing is more complex than simply using
string.split(). If you are sure that all the attribute values used in
your DNs don't have any special chars you could use string.split(). But
you should definitely cross-check with RFC 4514 or use a decent DN parser.

Ciao, Michael.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better way to replace/remove characters in a list of strings.

2006-09-04 Thread George Sakkis
Philipp Pagel wrote:

 Chris Brat [EMAIL PROTECTED] wrote:
  Is there a better way to replace/remove characters (specifically ' and
   characters in my case, but it could be anything) in strings in a
  list, than this example to replace 'a' with 'b':

 x = map(lambda foo: foo.replace('a', 'b'), x)

Or more pythonically:

x = [s.replace('a', 'b') for s in x]

George

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


Re: What are super()'s semantics?

2006-09-04 Thread Michele Simionato
Mike Krell wrote:
 BTW, the official docs are even worse in this regard.  AFAICT, they
 essentially say that super() returns a superclass with no discussion of
 diamond inheritance or any hint of how the semantics of super(B,
 self).met() would be any different than those of A.met(self).

 This seems like very important functionality to be documented in the
 official docs so poorly.

Well, you are right. I remember being fooled myself. 'super' does NOT
return a
superclass. Actually, there is no meaningful concept of superclass in a
multiple inheritance
world. Anyway, the MRO concept is documented here:

http://www.python.org/download/releases/2.3/mro/

(yes, it is not easy to find this link in python.org).

Michele Simionato

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


Re: What are super()'s semantics?

2006-09-04 Thread Carl Banks
Mike Krell wrote:
 class A(object):
 def met(self):
 print A.met

 class B(A):
 def met(self):
 print B.met
 super(B, self).met()

 class C(A):
 def met(self):
 print C.met
 super(C, self).met()

 class D(B,C):
 def met(self):
 print D.met
 super(D, self).met()

 D().met() # essentially D B C A
[snip]

 2. If I understand correctly, B's MRO is (B, A) and super(B, self) would
have an MRO of (A).

This is the source of your misunderstanding.

Essentially, it's objects that have MROs, not classes.  When you create
an object of class D, the MRO of that object is (D,B,C,A), and it
doesn't change, even when you're executing code defined in class B.
Thus, when self is of type D, super(B,self) does not have and MRO of
(A,), but (C,A).  Therefore, super(B,self).__init__() invokes
C.__init__.


Carl Banks

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


Re: What are super()'s semantics?

2006-09-04 Thread Maric Michaud
Le lundi 04 septembre 2006 12:25, Mike Krell a écrit :
 1. The super() call in D somehow invokes both parent class methods
    instead of stopping when the method is resolved in B. This has
    nothing to do with truncated lookup per se.  Why isn't the output D
    B A?


Yes but, super(B, B()) and super(B,D()) are not the same object like the code 
below shows.

 2. If I understand correctly, B's MRO is (B, A) and super(B, self) would
    have an MRO of (A).  Similarly for C.  So it seems that by the above
    explanation, A.met() would still be invoked twice (assuming both
    B.met() and C.met() are invoked).

super(class_, self), is an instance of super, so its class, super, have a 
mro of [type 'super', type 'object']
self in each method call is the same and indeed its type's mro doesn't 
change !


-- In [80]: class A(object) :
   : def sup(self) :
   : print 'A'
   :
   :

In [81]: class B(A) :
   : def sup(self) :
   : print 'B'
   : s(B, self).sup()
   :
   :

In [82]: class C(A) :
   : def sup(self) :
   : print 'C'
   : s(C, self).sup()
   :
   :

In [83]: class D(B,C) :
   : def sup(self) :
   : print 'D'
   : s(D, self).sup()
   :
   :

In [97]: class s(super) :
   : def __new__(*a) :
   : print a
   : return super.__new__(*a)
   :
   :

In [98]: D().sup()
D
(class '__main__.s', class '__main__.D', __main__.D object at 
0xa763186c)
B
(class '__main__.s', class '__main__.B', __main__.D object at 
0xa763186c)   --- instance is always the same !!
C
(class '__main__.s', class '__main__.C', __main__.D object at 
0xa763186c)   --- instance is always the same !!
A

In [100]: super(B, D()).sup()
C
(class '__main__.s', class '__main__.C', __main__.D object at 
0xa763178c)
A

This shows that C is called following the mro of type(D()) from class B to top 
and not the mro of B.

All the magic is in the __getattribute__ of super  which retrieve the 
following class in the mro given its argument.


In [140]: class A(object) :
   .: def sup(self) : print 'a'
   .:
   .:

In [141]: class B(A) :
   .: def sup(self) : print 'b'
   .:
   .:

In [142]: class C(A) :
   .: def sup(self) : print 'c'
   .:
   .:

In [143]: class D(B,C) : pass
   .:


In [147]: super.__getattribute__(super(D,D()), 'sup')()
b

In [148]: super.__getattribute__(super(B,D()), 'sup')()
c

In [149]: super.__getattribute__(super(C,D()), 'sup')()
a

Hope this is clear.

_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are super()'s semantics?

2006-09-04 Thread Maric Michaud
Le lundi 04 septembre 2006 13:48, Carl Banks a écrit :
 Essentially, it's objects that have MROs, not classes.
Wrong, __mro__ is an attribute of types (subtypes of type) but like __class__ 
it is not available in the instances.
mro() is standard a method of type.

In [150]: A.mro()
Out[150]: [class '__main__.A', type 'object']

In [152]: A().mro()
---
exceptions.AttributeErrorTraceback (most recent 
call last)

/home/maric/ipython console

AttributeError: 'A' object has no attribute 'mro'

In [154]: type.mro(A)
Out[154]: [class '__main__.A', type 'object']


-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: upgrade 2.4 - 2.5 HowTo

2006-09-04 Thread Sibylle Koczian
Helmut Jarausch schrieb:
 Hi,
 
 what has to be done for upgrading from Python 2.4 to 2.5?
 
 - How can I find out which packages (in addition to the core packages)
 have been
   installed up to now
 - Can I just copy   /usr/local/lib/python2.4/site-packages  to
 /usr/local/lib/python2.5 ?
 
 Many thanks for a hint,
 

Which OS?

Windows: control panel / software will list all python packages which
came with separate installers.

Linux: the package manager of your distribution should tell you what's
installed.

-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


modbus

2006-09-04 Thread kilnhead
Is anyone using python for modbus? I would like to communicate with
some
modbus devices - I can use pyserial and follw the protocol, just
wondering
if anybody has already done this?

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


Re: python-database

2006-09-04 Thread skip

Cliff On Sun, 2006-09-03 at 21:30 -0700, sridhar wrote:
 is there any way to call stored procedures from python as in java?

Cliff I mostly use PostgreSQL, so perhaps it's different for some other
Cliff databases, but calling stored procedures doesn't require any
Cliff special support from the language or driver.  Usually you simply
Cliff SELECT from the stored procedure.

In a stored procedure you can execute multiple SELECTs.  On the receiving
end you need some way to distinguish each result set.

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


are there any lib for receive hotmail ?

2006-09-04 Thread 叮叮当当
thanks.

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


Re: Better way to replace/remove characters in a list of strings.

2006-09-04 Thread Chris Brat
Thanks, thats exactly what I was looking for - very neat.


George Sakkis wrote:
 Philipp Pagel wrote:

  Chris Brat [EMAIL PROTECTED] wrote:
   Is there a better way to replace/remove characters (specifically ' and
characters in my case, but it could be anything) in strings in a
   list, than this example to replace 'a' with 'b':
 
  x = map(lambda foo: foo.replace('a', 'b'), x)

 Or more pythonically:
 
 x = [s.replace('a', 'b') for s in x]
 
 George

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


This seems to crash my program and gives me errors on the #include statements

2006-09-04 Thread [EMAIL PROTECTED]
I was trying to add this to my project but I must be missing some
includes or there is a serius error somewhere


Anthra Norell wrote:
 Dexter,

 Here's a function that screens out all instrument blocks and puts them into a 
 dictionary keyed on the instrument number:


 


 def get_instruments (file_name):


INSIDE  = 1
OUTSIDE = 0


f = file (file_name, 'ra')
state = OUTSIDE
instruments = {}
instrument_segment = ''


for line in f:
   if state == OUTSIDE:
  if line.startswith ('CsInstruments'):
 state = INSIDE
 instrument_segment += line
   else:
  instrument_segment += line
  if line.lstrip ().startswith ('instr'):
 instrument_number = line.split () [1]
  elif line.startswith ('/CsInstruments'):
 instruments [instrument_number] = instrument_segment
 instrument_segment = ''
 state = OUTSIDE


f.close ()
return instruments


 


 You have received good advice on using parsers: beautiful soup or 
 pyparse. These are powerful tools capable of doing complicated
 extractions. Yours is not a complicated extraction. Simon tried it with 
 beautiful soup. That seems simple enough, though he finds
 the data by index leaving open where he gets the index from. There's surely a 
 way to get the data by name.
   Contrary to the parser the function will miss if tags take liberties 
 with upper-lower case letters as they are probably
 allowed by the specification. A regular expression might have to be used, if 
 they do.
  From your description I haven't been able to infer what the final format 
 of your data is supposed to be. So I cannot tell you
 how to go on from here. You'll find out. If not, just keep asking.


 The SE solution which you said couldn't work out would be the following. It 
 makes the same dictionary the function makes and it is
 case-insensitive:


 


  Instrument_Segment_Filter = SE.SE ('EAT 
  ~(?i)CsInstruments(.|\n)*?/CsInstruments~==\n\n  ')
  instrument_segments= Instrument_Segment_Filter ('file_name', '')
  print instrument_segments
 (... see all instrument segments ...)
  Instrument_Number = SE.SE ('EAT ~instr.*~==\n')
  instruments ={}
  for segment in instrument_segments.split ('\n\n'):
 if segment:
instr_line = Instrument_Number (segment)
instrument_number = instr_line.split ()[1]
instruments [instrument_number] = segment


 --


 (If you're on Windows and the CRs bother you, take them out with an 
 additional definition when you make your
 Instrument_Block_Filter: (13)=  or  \r=)


 Regards


 Frederic


 - Original Message -
 From: [EMAIL PROTECTED]
 Newsgroups: comp.lang.python
 To: [EMAIL PROTECTED]
 Sent: Wednesday, August 30, 2006 1:51 AM
 Subject: Re: newbe question about removing items from one file to another file


  Anthra Norell wrote:
   Dexter,


   I looked at the format specification. It contains an example:


   ---


   CsoundSynthesizer;
 ; test.csd - a Csound structured data file


   CsOptions
 -W -d -o tone.wav
   /CsOptions


 ...
 etc.



I cut and pasted this..  It seems to be crashing my program.. I am not
sure that I have all the right imports..  seems to be fine when I go to

an older version of the file...  I uploaded it onto source forge.

https://sourceforge.net/project/showfiles.php?group_id=156455package...

http://www.dexrow.com

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


methods and functions, instances and classes

2006-09-04 Thread David Isaac
When I create an instance of a class,
are the class's functions *copied* to create the methods?
Or are method calls actually calls of the class's functions?

I am sure this is both obvious and FAQ,
but I did not find a clear answer
(e.g. here
http://docs.python.org/tut/node11.html#SECTION001134 ,
a lot turns on the meaning of 'equivalent'.)

Thank you,
Alan Isaac


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


Unicode characters

2006-09-04 Thread Paul Johnston
Hi
I have a string which I convert into a list then read through it
printing its glyph and numeric representation

#-*- coding: utf-8 -*-

thestring = abcd
thelist = list(thestring)

for c in thelist:
 print c,
 print ord(c)

Works fine for latin characters but when I put in a unicode character
a two byte character gives me two characters. For example an arabic
alef returns

*  216
* 167

( the first asterix is the empty set symbol the second a double s)

Putting in sequential characters i.e. alef, beh, teh mabuta, gives me
sequential listings i.e.
216  167
216  168
216  169 
So it is reading the correct details.


Is there anyway to get the c in the for loop to recognise it is
reading a multiple byte character.
I have followed the info in PEP 0263 and am using Python 2.4.3 Build
12 on a Windows box  within Eclipse 3.2.0 and Python plugins 1.2.2

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


Re: methods and functions, instances and classes

2006-09-04 Thread Diez B. Roggisch
David Isaac wrote:

 When I create an instance of a class,
 are the class's functions *copied* to create the methods?
 Or are method calls actually calls of the class's functions?

On the class functions. You can make every instance have it's own methods,
though - but only explicitly.

Diez

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


Re: upgrade 2.4 - 2.5 HowTo

2006-09-04 Thread Helmut Jarausch
Sibylle Koczian wrote:
 Helmut Jarausch schrieb:
 Hi,

 what has to be done for upgrading from Python 2.4 to 2.5?

 - How can I find out which packages (in addition to the core packages)
 have been
   installed up to now
 - Can I just copy   /usr/local/lib/python2.4/site-packages  to
 /usr/local/lib/python2.5 ?

 Many thanks for a hint,

 
 Which OS?
 
 Windows: control panel / software will list all python packages which
 came with separate installers.
 
 Linux: the package manager of your distribution should tell you what's
 installed.
 

It's Linux.
Thanks, but I don't have a package manager. I'm working with Linux-From-Scratch.


-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


replace deepest level of nested list

2006-09-04 Thread David Isaac
I have a list of lists, N+1 deep.
Like this (for N=2):
[[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11'
,'b11']]]

I want to efficiently produce the same structure
except that the utlimate lists are replaced by a chosen (by index) item.
E.g.,
[['r00','r01'],['r10','r11']]

N is not known ahead of time.

Suggestions?

Thanks,
Alan Isaac


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


Re: methods and functions, instances and classes

2006-09-04 Thread Tim Chase
 When I create an instance of a class,
 are the class's functions *copied* to create the methods?
 Or are method calls actually calls of the class's functions?
 
 I am sure this is both obvious and FAQ,
 but I did not find a clear answer

The best way to find out is to try it:

###
class Foo(object):
def hello(self):
return Foo::hello

f1 = Foo()

print f1.hello()
Foo.hello = lambda self: new hello!
print f1.hello()

###

 From what I see of this evidence, method calls [are] actually 
calls of the class's functions, not copied.

-tkc






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


Re: This seems to crash my program and gives me errors on the #include statements

2006-09-04 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 I was trying to add this to my project but I must be missing some
 includes or there is a serius error somewhere
 
[...]
 
 I cut and pasted this..  It seems to be crashing my program.. I am not
 sure that I have all the right imports..  seems to be fine when I go to
 
 an older version of the file...  I uploaded it onto source forge.
 
 https://sourceforge.net/project/showfiles.php?group_id=156455package...
 
 http://www.dexrow.com
 

Nobody, or very few people, are going to bother to download code from 
sourceforge just to help you debug it.

As far as I can see you haven't yet explained *how* your program fails: 
does it give a Python error traceback (in which case we would need to 
see that traceback, which will at least tell us where the error occurs) 
or something else? A serious error tells us effectively nothing except 
that your program isn't doing what you want it to do, so even reading 
the source probably won't help.

Have you tried reproducing the serious error in a smaller program that 
you could include as a part of a posting on this list?

You are hiding the very information that is needed to help you solve 
your problem.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Unicode characters

2006-09-04 Thread limodou
On 9/4/06, Paul Johnston [EMAIL PROTECTED] wrote:
 Hi
 I have a string which I convert into a list then read through it
 printing its glyph and numeric representation

 #-*- coding: utf-8 -*-

 thestring = abcd
 thelist = list(thestring)

 for c in thelist:
  print c,
  print ord(c)

 Works fine for latin characters but when I put in a unicode character
 a two byte character gives me two characters. For example an arabic
 alef returns

 *  216
 * 167

 ( the first asterix is the empty set symbol the second a double s)

 Putting in sequential characters i.e. alef, beh, teh mabuta, gives me
 sequential listings i.e.
 216  167
 216  168
 216  169
 So it is reading the correct details.


 Is there anyway to get the c in the for loop to recognise it is
 reading a multiple byte character.
 I have followed the info in PEP 0263 and am using Python 2.4.3 Build
 12 on a Windows box  within Eclipse 3.2.0 and Python plugins 1.2.2

If the string is not a unicode, it's be encoded in byte, so you can
only get the every character encoding of the string. You can conver it
to unicode, and if the character value less than 127, it should be an
ascii, otherwise maybe a multibytes character. for example:

a = 'string'
b = unicode(a, encoding_according_your_situation)
for i in b:
   if ord(i)  127:
   print ord(i), 'ascii'
   else:
   print ord(i), 'multibytes'

-- 
I like python!
My Blog: http://www.donews.net/limodou
UliPad Site: http://wiki.woodpecker.org.cn/moin/UliPad
UliPad Maillist: http://groups.google.com/group/ulipad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode characters

2006-09-04 Thread Diez B. Roggisch
Paul Johnston wrote:

 Hi
 I have a string which I convert into a list then read through it
 printing its glyph and numeric representation
 
 #-*- coding: utf-8 -*-
 
 thestring = abcd
 thelist = list(thestring)
 
 for c in thelist:
  print c,
  print ord(c)
 
 Works fine for latin characters but when I put in a unicode character
 a two byte character gives me two characters. For example an arabic
 alef returns
 
 *  216
 * 167
 
 ( the first asterix is the empty set symbol the second a double s)
 
 Putting in sequential characters i.e. alef, beh, teh mabuta, gives me
 sequential listings i.e.
 216  167
 216  168
 216  169
 So it is reading the correct details.
 
 
 Is there anyway to get the c in the for loop to recognise it is
 reading a multiple byte character.
 I have followed the info in PEP 0263 and am using Python 2.4.3 Build
 12 on a Windows box  within Eclipse 3.2.0 and Python plugins 1.2.2

Use unicode objects instead of byte strings. The above string literal is
_not_ affected by the coding:-header whatsoever.

That applies only to 

usome text

literals, and makes them a unicode object.

The normal string literals are just bytes - because of your encoding being
properly set in the editor, an entered multibyte-character is stored as
such.

In a nutshell: try the above using uabcd.
Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Setting custom folder icon in OS X?

2006-09-04 Thread Kevin Walzer
Jet Jaguar wrote:
 I'm trying to find a way to set a custom folder icon in OS X.  I
 thought that Applescript would be able to do it, but apparently it
 can't.  Is there anything in the Macintosh libraries of Python that
 will allow me to take an image file (e.g., jpeg, png, tiff, etc.) and
 set it as the icon for a folder?
 
 Kevin D. Smith
 
There might be a way to do this via PyObjC (the Python-Objective C
bridge), which provides access to the Mac's Cocoa frameworks.

-- 
Kevin Walzer
Poetic Code
http://www.kevin-walzer.com
-- 
http://mail.python.org/mailman/listinfo/python-list


threading support in python

2006-09-04 Thread km
Hi all,

Is there any PEP to introduce true threading features into python's
next version as in java? i mean without having GIL.
when compared to other languages, python is fun to code but i feel its
is lacking behind in threading

regards,
KM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Twisted vs POS (Plain-old sockets)

2006-09-04 Thread Istvan Albert
Guido Goldstein wrote:

 You might have a look at asyncore/asychat in the standard library.
 It does the async stuff for you and it's easy to understand and to
 use.

or  Allegra might work

http://laurentszyster.be/blog/allegra/

its anti-twisted melodrama comes at no extra charge.

i.

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


Re: methods and functions, instances and classes

2006-09-04 Thread David Isaac
 Alan Isaac wrote:
  When I create an instance of a class,
  are the class's functions *copied* to create the methods?
  Or are method calls actually calls of the class's functions?


Diez B. Roggisch [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 On the class functions. You can make every instance have it's own methods,
 though - but only explicitly.


Could you please elaborate on that last sentence?
Thanks,
Alan Isaac


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


Re: threading support in python

2006-09-04 Thread bayerj
Hi,

GIL won't go. You might want to read
http://blog.ianbicking.org/gil-of-doom.html .

Regards,
-Justin

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


Re: This seems to crash my program and gives me errors on the #include statements

2006-09-04 Thread [EMAIL PROTECTED]
It is giving errors on the import statements..  I will get an error on
the line where I import this routine import csoundroutines and then the
when I import the the program that tried to import csoundroutines I get
an error and on down the chain..  when I go back to where I started in
csoundroutines all the import errors go away..  I can't tell if thier
is a problem with se.py that starts all the errors or if I am not
getting all the right import statements...  There is a short file on
sourceforge that gives the csoundroutines library I am trying to debug
and expand..

 https://sourceforge.net/project/showfiles.php?group_id=156455package


Steve Holden wrote:
 [EMAIL PROTECTED] wrote:
  I was trying to add this to my project but I must be missing some
  includes or there is a serius error somewhere
 
 [...]
 
  I cut and pasted this..  It seems to be crashing my program.. I am not
  sure that I have all the right imports..  seems to be fine when I go to
 
  an older version of the file...  I uploaded it onto source forge.
 
  https://sourceforge.net/project/showfiles.php?group_id=156455package...
 
  http://www.dexrow.com
 

 Nobody, or very few people, are going to bother to download code from
 sourceforge just to help you debug it.

 As far as I can see you haven't yet explained *how* your program fails:
 does it give a Python error traceback (in which case we would need to
 see that traceback, which will at least tell us where the error occurs)
 or something else? A serious error tells us effectively nothing except
 that your program isn't doing what you want it to do, so even reading
 the source probably won't help.

 Have you tried reproducing the serious error in a smaller program that
 you could include as a part of a posting on this list?

 You are hiding the very information that is needed to help you solve
 your problem.

 regards
   Steve
 --
 Steve Holden   +44 150 684 7255  +1 800 494 3119
 Holden Web LLC/Ltd  http://www.holdenweb.com
 Skype: holdenweb   http://holdenweb.blogspot.com
 Recent Ramblings http://del.icio.us/steve.holden

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


Re: replace deepest level of nested list

2006-09-04 Thread George Sakkis
David Isaac wrote:

 I have a list of lists, N+1 deep.
 Like this (for N=2):
 [[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11'
 ,'b11']]]

 I want to efficiently produce the same structure
 except that the utlimate lists are replaced by a chosen (by index) item.
 E.g.,
 [['r00','r01'],['r10','r11']]

 N is not known ahead of time.

 Suggestions?

 Thanks,
 Alan Isaac

Numeric/Numpy is ideal for this:



from Numeric import array



def slicelist(nestedlist,index):

a = array(nestedlist,'O')

# return the slice a[:,:,...,:,index]

fullindex = [slice(None)] * len(a.shape)

fullindex[-1] = index

return a[fullindex].tolist()


George

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


Re: replace deepest level of nested list

2006-09-04 Thread Roberto Bonvallet
David Isaac wrote:
 I have a list of lists, N+1 deep.
 Like this (for N=2):
 [[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11'
 ,'b11']]]
 
 I want to efficiently produce the same structure
 except that the utlimate lists are replaced by a chosen (by index) item.
 E.g.,
 [['r00','r01'],['r10','r11']]
 
 N is not known ahead of time.

First thing I came up with:

 l = 
 [[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11','b11']]]
 def get_deepest(l, n):
... if isinstance(l[0], list):
... return [get_deepest(s, n) for s in l]
... else:
... return l[n]
... 
 get_deepest(l, 0)
[['r00', 'r01'], ['r10', 'r11']]
 get_deepest(l, 1)
[['g00', 'g01'], ['g10', 'g11']]
 

n is the chosen index.
HTH.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: This seems to crash my program and gives me errors on the #include statements

2006-09-04 Thread Roberto Bonvallet
[EMAIL PROTECTED] wrote:
 It is giving errors on the import statements..  I will get an error on
 the line where I import this routine import csoundroutines and then the
 when I import the the program that tried to import csoundroutines I get
 an error and on down the chain..

Please paste here the errors you get, and paste also the relevant code (not
the whole program) that triggers that error.

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


Re: Python newbie with a problem writing files

2006-09-04 Thread Jason
limodou wrote:
  Code:
 
  import feedparser
  from xml.sax import saxutils
 
  feed_number=200
 
  feed_list = open(feed_listing.conf,r)
  for each_feed in feed_list:
  data=feedparser.parse(each_feed)
  feed_title=data.entries[0].title
  xml_output=open(xml_data\\feed + str(feed_number) + .xml, w)

 Maybe there is a extra '=', if it should be:

 xml_output.write(feed_title)

 ?


It took me a few moments to parse what limodou wrote here, but he's
absolutely correct.  Your problem is that you are trying to reassign
the write method in your file.  File objects are built-in types, and do
not allow their methods to be calvaliery replaced.

Here's an example on the correct way (and your way) of writing to a
file:
 f = open('spam.xml', 'w')
 f.write( 'This data is written to the file' )
 f.write = (This is not a valid Python syntax)
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: 'file' object attribute 'write' is read-only


You'll notice that the AttributeError describes exactly what's wrong in
this case.  The write method on your file attribute is read-only.  It
doesn't say anything about whether your file is read-only.

If you really, really want to change the write method into a string,
you can subclass from the file class:

 class MyFileType(file):
... pass
...
 myfile = MyFileType('spam_and_eggs.xml', 'w')
 myfile.write
built-in method write of MyFileType object at 0x00870B88
 myfile.write = Gonna replace write method with this string!
 myfile.write
'Gonna replace write method with this string!'


Of course, you can no longer easily access the original write method
after re-assigning it like that.

(limodou, I thought this might need a little bit of extra explanation
for the original poster.  I apologize if I seem rude here.)

--Jason

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


Re: replace deepest level of nested list

2006-09-04 Thread David Isaac
Thanks to both Roberto and George.
I had considered the recursive solution
but was worried about its efficiency.
I had not seen how to implement the numpy
solution, which looks pretty nice.

Thanks!
Alan


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


Re: threading support in python

2006-09-04 Thread km
Hi all,
Are there any alternate ways of attaining true threading in python ?
if GIL doesnt go  then does it mean that python is useless for
computation intensive scientific applications which are in need of
parallelization in threading context ?

regards,
KM
---
On 4 Sep 2006 07:58:00 -0700, bayerj [EMAIL PROTECTED] wrote:
 Hi,

 GIL won't go. You might want to read
 http://blog.ianbicking.org/gil-of-doom.html .

 Regards,
 -Justin

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

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


Re: This seems to crash my program and gives me errors on the #include statements

2006-09-04 Thread [EMAIL PROTECTED]
#import se

# se available at http://cheeseshop.python.org/pypi/SE/2.2%20beta

looks like it is the se beta..  I didn't get any kind of error or
traceback that would tell me that though..




Roberto Bonvallet wrote:
 [EMAIL PROTECTED] wrote:
  It is giving errors on the import statements..  I will get an error on
  the line where I import this routine import csoundroutines and then the
  when I import the the program that tried to import csoundroutines I get
  an error and on down the chain..

 Please paste here the errors you get, and paste also the relevant code (not
 the whole program) that triggers that error.
 
 -- 
 Roberto Bonvallet

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


Re: are there any lib for receive hotmail ?

2006-09-04 Thread Paul McGuire
 [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 thanks.


poplib 


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


Re: threading support in python

2006-09-04 Thread bayerj
Hi,

You might want to split your calculation onto different
worker-processes.

Then you can use POSH [1] to share data and objects.
You might even want to go a step further and share the data via
Sockets/XML-RPC or something like that. That makes it easy to throw
aditional boxes at a specific calculation, because it can be set up in
about no time.
You can even use Twisted Spread [2] and its perspective broker to do
this on a higher level.

If that's not what you want, you are left with Java I guess.

Regards,
-Justin

[1] http://poshmodule.sourceforge.net/
[2] http://twistedmatrix.com/projects/core/documentation/howto/pb.html

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


Re: threading support in python

2006-09-04 Thread Richard Brodie

km [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 if GIL doesnt go  then does it mean that python is useless for
 computation intensive scientific applications which are in need of
 parallelization in threading context ?

No. 


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


Re: threading support in python

2006-09-04 Thread Sybren Stuvel
km enlightened us with:
 Is there any PEP to introduce true threading features into python's
 next version as in java? i mean without having GIL.

What is GIL? Except for the Dutch word for SCREAM that is...

 when compared to other languages, python is fun to code but i feel
 its is lacking behind in threading

What's wrong with the current threading? AFAIK it's directly linked to
the threading of the underlying platform.

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading support in python

2006-09-04 Thread Jean-Paul Calderone
On Mon, 4 Sep 2006 17:48:14 +0200, Sybren Stuvel [EMAIL PROTECTED] wrote:
km enlightened us with:
 Is there any PEP to introduce true threading features into python's
 next version as in java? i mean without having GIL.

What is GIL? Except for the Dutch word for SCREAM that is...

 when compared to other languages, python is fun to code but i feel
 its is lacking behind in threading

What's wrong with the current threading? AFAIK it's directly linked to
the threading of the underlying platform.

Only one thread per process can execute Python bytecode, even on an SMP
system.  The main bytecode eval loop is protected by a lock, the Global
Interpreter Lock.

This doesn't prevent certain operations from being parallelized.  For
example, many of the I/O calls in Python release the GIL so that while
they are blocked on the network or the disk, another thread can continue
to execute.  Extension modules which perform computationally intensive
tasks can also release the GIL to allow better exploitation of SMP
resources.

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


Manipulating GIF image frames w/ PIL - where'd my palette go?

2006-09-04 Thread skip
I'm unclear how PIL handles multi-frame GIF images.  I have such a GIF image
in a file, bogus.gif.  I can view the individual frames like so
(ImageSequence is from the PIL tutorial):

 img = Image.open(bogus.gif)
 for frame in ImageSequence(img):
...   frame.show()

All but the first image appears black-and-white.  They apparently lose the
color palette associated with the overall image.  The palette for the
original image and the individual frames is the same, the histograms suggest
they have more than two colors and both the image the frames have mode 'P'.
What have I missed?

Thx,

Skip

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


Re: SQLObject or SQLAlchemy?

2006-09-04 Thread Bruno Desthuilliers
lazaridis_com wrote:
 Ο/Η Bruno Desthuilliers έγραψε:
 lazaridis_com wrote:
 John Salerno wrote:
 Are there any major differences between these two? It seems they can
 both be used with TurboGears, and SQLAlchemy with Django. I'm just
 wondering what everyone's preference is, and why, and if there are even
 more choices for ORM.

 Thanks.
 You can review the Persit Case, which will shortly evaluate the stated
 ORM's:

 http://case.lazaridis.com/wiki/Persist

 It is possibly of importance to remember some requirements which should
 be relevant for an persistency mechanism targetting an OO language:
 RDBMS are not persistency mechanism, they are data management tools.
 
 possibly.
 
 but this is not relevant, as the Persist case does not deal with
 RDBMS.
 
Then your post is irrelevant since there's a clear indication that the
OP question was about RDBMS integration in Python (hint: SQLObject and
SQLAlchemy both start with 'SQL').

good night.
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: threading support in python

2006-09-04 Thread Diez B. Roggisch
Sybren Stuvel wrote:

 km enlightened us with:
 Is there any PEP to introduce true threading features into python's
 next version as in java? i mean without having GIL.
 
 What is GIL? Except for the Dutch word for SCREAM that is...

the global interpreter lock, that prevents python from concurrently
modifying internal structures causing segfaults.
 
 when compared to other languages, python is fun to code but i feel
 its is lacking behind in threading
 
 What's wrong with the current threading? AFAIK it's directly linked to
 the threading of the underlying platform.

There exist rare cases (see the link from bayerj) where the GIL is an
annoyance, and with the dawn of MP-cores all over the place it might be
considered a good idea removing it - maybe. But I doubt that is something
to be considered for py2.x

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


py2exe and libxml

2006-09-04 Thread Laszlo Nagy

I wrote a little win32 console application that uses libxml2. It is 
working fine. If I create an .exe version, I get this error when I try 
to start the program:

Traceback (most recent call last):
  File MyProgram.py, line 3, in ?
  File mylib\item.pyc, line 5, in ?
ImportError: dynamic module does not define init function (initlibxml2)

What is wrong here?
Thanks

   Laszlo

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


Re: threading support in python

2006-09-04 Thread Sandra-24
The trouble is there are some environments where you are forced to use
threads. Apache and mod_python are an example. You can't make use of
mutliple CPUs unless you're on *nux and run with multiple processes AND
you're application doesn't store large amounts of data in memory (which
mine does) so you'd have to physically double the computer's memory for
a daul-core, or quadruple it for a quadcore. And forget about running a
windows server, apache will not even run with multiple processes.

In years to come this will be more of an issue because single core CPUs
will be harder to come by, you'll be throwing away half of every CPU
you buy.

-Sandra

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


Prevent self being passed to a function stored as a member variable?

2006-09-04 Thread Sandra-24
How can you prevent self from being passed to a function stored as a
member variable?

class Foo(object):
   def __init__(self, callback):
  self.func = callback

f =Foo(lambda x: x)
f.func(1) # TypeError, func expects 1 argument, recieved 2

I thought maybe you could do this:

class Foo(object):
   def __init__(self, callback):
  self.func = staticmethod(callback)  # Error, staticmethod not
callable

Somebody (maybe everybody other than myself) here must know?

Thanks,
-Sandra

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


Re: Prevent self being passed to a function stored as a member variable?

2006-09-04 Thread Qiangning Hong
On 4 Sep 2006 09:39:32 -0700, Sandra-24 [EMAIL PROTECTED] wrote:
 How can you prevent self from being passed to a function stored as a
 member variable?

 class Foo(object):
def __init__(self, callback):
   self.func = callback

 f =Foo(lambda x: x)
 f.func(1) # TypeError, func expects 1 argument, recieved 2

Do you really get that error? I got the following in my python shell:

. class Foo(object):
   def __init__(self, callback):
 self.func = callback

. f = Foo(lambda x: x)
. f.func(1)
1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Prevent self being passed to a function stored as a member variable?

2006-09-04 Thread Jean-Paul Calderone
On 4 Sep 2006 09:39:32 -0700, Sandra-24 [EMAIL PROTECTED] wrote:
How can you prevent self from being passed to a function stored as a
member variable?

This doesn't happen:

 class x:
... def __init__(self):
... self.x = lambda: None
... 
 x().x()
 class y(object):
... def __init__(self):
... self.y = lambda: None
... 
 y().y()
 

Perhaps you confused this case with the case of a function which is a
class attribute?

 z().z()
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: lambda() takes no arguments (1 given)
 

In which case, staticmethod() is actually the solution you want:

 class w(object):
... w = staticmethod(lambda: None)
... 
 w().w()
 

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


Re: threading support in python

2006-09-04 Thread Daniel Dittmar
km wrote:
 Is there any PEP to introduce true threading features into python's
 next version as in java? i mean without having GIL.
 when compared to other languages, python is fun to code but i feel its
 is lacking behind in threading

Some of the technical problems:

- probably breaks compatibility of extensions at the source level in a 
big way, although this might be handled by SWIG, boost and other code 
generators
- reference counting will have to be synchronized, which means that 
Python will become slower
- removing reference counting and relying on garbage collection alone 
will break many Python applications (because they rely on files being 
closed at end of scope etc.)

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


Using Content-Disposition in HTTP download

2006-09-04 Thread dclist
What is the correct way to download a file through HTTP and save it to
the file name suggested by Content-Disposition?

I would use urlretrieve but I'm not sure how to obtain the file name
through the HTTP headers without downloading the body (e.g.
urlopen(url).info()).

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


Re: methods and functions, instances and classes

2006-09-04 Thread Bruno Desthuilliers
David Isaac wrote:
 When I create an instance of a class,
 are the class's functions *copied* to create the methods?

No, unless you explicitely do it.

 Or are method calls actually calls of the class's functions?

Depends on how the method was associated to the instance (you can set
methods on a per-instance property), but in the general case (functions
defined in the class body), yes.

 I am sure this is both obvious

I once had the same question when I was learning computers and programming.

 and FAQ,

Not AFAIK.

 but I did not find a clear answer
 (e.g. here
 http://docs.python.org/tut/node11.html#SECTION001134 ,
 a lot turns on the meaning of 'equivalent'.)



If the name denotes a valid class attribute that
is a function object, a method object is created by packing (pointers
to) the instance object and the function object just found together in
an abstract object: this is the method object. When the method object is
called with an argument list, it is unpacked again, a new argument list
is constructed from the instance object and the original argument list,
and the function object is called with this new argument list.


IOW, a method object is a callable object keeping references to both the
instance and the function (note the (pointers to) ... the function
object).

You could represent yourself the method as something like:

class Method(object):
  def __init__(self, im_func, im_self):
self.im_self = obj
self.im_func = func

  def __call__(self, *args, **kw):
return self.im_func(self.im_self, *args, **kw)

Now suppose that the 'function' type definition (yes, Python functions
are objects) looks a bit like this:

class function(object):
. . .
def __get__(self, obj):
return Method(self, obj)


And that looking up an attribute on an instance looks like this (dumbed
down of course):

def __getattribute__(self, name):
  if name in self.__dict__:
return self.__dict__[name]
  elif hasattr(self.__class__, name)
attrib = getattr(self.__class__, name)
if hasattr(attrib, '__get__'):
  return attrib.__get__(self)
else:
  return attrib
  else:
raise AttributeError(object %s has no attribute %s % (self, name)


Then for :

class Foo(object):
  def bar(self, val):
return %s %s % (self, val)

foo = Foo()

Looking up 'bar' on 'foo':
bar = foo.bar

would resolve, thru __getattribute__ etc, to:
bar = Method(Foo.bar, foo)

Which, if then called, would resolve to
Foo.bar(foo, 42)



NB : reading the doc about new-style classes and the descriptor protocol
may help:
http://www.python.org/download/releases/2.2.3/descrintro/
http://users.rcn.com/python/download/Descriptor.htm

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Prevent self being passed to a function stored as a member variable?

2006-09-04 Thread Sandra-24
Qiangning Hong wrote:
 Do you really get that error?

Sorry, my bad. You're correct of course. I had accidentally passed an
object, by naming it the same as the function, instead of my function,
and the object had __call__ defined, and took exactly two parameters,
just like my function, but one of them beign self. So when I passed two
arguments, it got three, and that's how I was confused into thinking
self was being passed to my function (because it was, but not to my
function.) All a big foulup on my part. I might have worked on that
problem for a while before figuring it out, thanks!

-Sandra

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


Where to find fpconst?

2006-09-04 Thread Roy Smith
I'm trying to install SOAPpy per the instructions on Dive Into Python 
(http://diveintopython.org/soap_web_services/install.html).  I've got PyXML 
installed, but I'm stuck trying to find fpconst.

The URL given on the DIP page doesn't work; www.analytics.washington.edu 
doesn't resolve in DNS.  Likewise for 
http://software.biostat.washington.edu/statsoft/snake/fpconst

I found another URL, http://research.warnes.net/projects/rzope/fpconst, but 
that doesn't work either (I get a proxy error).

Anybody know where I can find fpconst?
-- 
http://mail.python.org/mailman/listinfo/python-list


Test for number?

2006-09-04 Thread Dr. Pastor
In the following code I would like to ascertain
that x has/is a number. What the simplest TEST should be?
(Could not find good example yet.)
---
x=raw_input('\nType a number from 1 to 20')
if TEST :
Do_A
else:
Do_B
---
Thanks for any guidance.

== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where to find fpconst?

2006-09-04 Thread Rob De Almeida
 Anybody know where I can find fpconst?

I uploaded the lastest copy I could find to the Cheese Shop
(http://www.python.org/pypi/fpconst/).

I'm not affiliated in any way with fpconst, btw.

Rob

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


Re: Where to find fpconst?

2006-09-04 Thread Roy Smith
In article [EMAIL PROTECTED],
 Rob De Almeida [EMAIL PROTECTED] wrote:

 http://www.python.org/pypi/fpconst/

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


Web queries in Python

2006-09-04 Thread Joseph
Hi,
Excel uses web queries to read data (like financial/weather data) from
web. How to do the same in python? Even pointers to such would be of
help.

Thank you,
Joseph

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


Re: Test for number?

2006-09-04 Thread Tim Williams
On 04/09/06, Dr. Pastor [EMAIL PROTECTED] wrote:
 In the following code I would like to ascertain
 that x has/is a number. What the simplest TEST should be?
 (Could not find good example yet.)
 ---
 x=raw_input('\nType a number from 1 to 20')
 if TEST :
 Do_A
 else:
 Do_B
 ---

Something simple like the following might help,

 def numtest():
... x=raw_input('\nType a number from 1 to 20')
... try:
... x=int(x)
... print x, is a number between 1  20 
... except:
... print x, is not a number
...
 numtest()   # enter 1
1 is a number between 1  20
 numtest()  #  enter f
f is not a number

its not a final solution though,  think input = -2, 5.5  or 21

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


Re: Twisted vs POS (Plain-old sockets)

2006-09-04 Thread Darren Kirby
On 9/3/06, Jean-Paul Calderone [EMAIL PROTECTED] wrote:
 On Sun, 3 Sep 2006 00:19:17 -0700, Darren Kirby [EMAIL PROTECTED] wrote:
 Hey all,
 
 I have a (FOSS) project here that I am about to start that requires TCP
 networking support, and in fact, will require me to design and implement a
 (text based) protocol from scratch.

 I'm sorry.

Don't be sorry, I am doing this for fun and to learn...


 If there are features you don't need, then don't use them.  What does their
 existence cost you?  Are you going to use the sunaudio module from the
 standard library?  If not, is this an argument in favor of using C++ instead
 of Python?

Well, the question I have is if it is worth digging through all the
complexity (in the code itself and docs) for the few nuggets I do
need... I am well aware I do not need to use everything...

 As for documentation, many people say it is lacking, but perhaps one person
 in a thousand points out _how_ or _where_ it is lacking.  Unfortunately it
 is difficult to improve things (or even determine if they really are lacking)
 with this level of feedback.

I am certainly not trying to dump on twisted. As for what is lacking,
the many methods I looked up that say simply Not Documented would be
the biggest problem

 Keep in mind that in addition to the online documentation, there is a Twisted
 book, an extremely helpful twisted mailing list (with years of archives
 online), and an IRC channel populated at nearly all hours of the day with
 people who can answer Twisted questions.

I am aware of the book, and if I decide to go the twisted route I
would certainly purchase it. However, not that I am overly swayed by
amazon reviews, but the consistent majority of them have said that the
book is big on specifics (as in, explaining the example code and not
much else), and small on the 'big-picture' so to speak. If this is
true I might as well stay with the docs.


 Talking to the TCP/IP stack is surprisingly difficult to get right.  Since
 it is extremely unlikely that you actually _care_ about all of the random,
 stupid differences between different TCP implementations, you should use
 Twisted, since it does its best to hide these differences and instead
 present a uniform API.

Fair enough...

 If you use bare sockets, you will need to learn many of these quirks yourself,
 frequently through a bug report from a user, since many of them are
 undocumented.

True, though keep in mind this is as much of a learning exercise for
me as it is to get an app out the door quick.


 Twisted is great.  It will speed up your development time and reduce the
 amount of defects you need to deal with.  It will


OK, I will stick with twisted and see if I can't figure it out, and
perhaps play with asyncore and see for myself what will work. Please
note I was really just looking for some anecdotes from experienced
programmers that may have found themselves in my situation, and the
solutions they chose...

 Hope this helps,

Sure it did, thanks for taking the time to respond, also thanks to
Guido and Istvan,

 Jean-Paul

-d
-- 
darren kirby :: Part of the problem since 1976 :: http://badcomputer.org
...the number of UNIX installations has grown to 10, with more expected...
- Dennis Ritchie and Ken Thompson, June 1972
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading support in python

2006-09-04 Thread Rob Williscroft
Daniel Dittmar wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 - removing reference counting and relying on garbage collection alone 
 will break many Python applications (because they rely on files being 
 closed at end of scope etc.)
 

They are already broken on at least 2 python implementations, so
why worry about another one.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test for number?

2006-09-04 Thread Helmut Jarausch
Tim Williams wrote:
 On 04/09/06, Dr. Pastor [EMAIL PROTECTED] wrote:
 In the following code I would like to ascertain
 that x has/is a number. What the simplest TEST should be?
 (Could not find good example yet.)
 ---
 x=raw_input('\nType a number from 1 to 20')
 if TEST :
 Do_A
 else:
 Do_B
 ---
 
 Something simple like the following might help,
 
 def numtest():
 ... x=raw_input('\nType a number from 1 to 20')
 ... try:
 ... x=int(x)
 ... print x, is a number between 1  20 
 ... except:
 ... print x, is not a number
 ...
 numtest()   # enter 1
 1 is a number between 1  20
 numtest()  #  enter f
 f is not a number
 
 its not a final solution though,  think input = -2, 5.5  or 21
 

One step further

try:
eval(x+'0')



-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: This seems to crash my program and gives me errors on the#include statements

2006-09-04 Thread Anthra Norell
Dexter,
  Whenever I can I post solutions. And when I do, I run them in an IDLE 
window and copy my commands plus the output over into
the message. So my posting should be replicable, if you would copy the commands 
into your IDLE window one by one and hitting return.
  Please do this and copy everything in your window back into your message. 
If we do that it shouldn't be hard to straighten
this out.

Frederic

- Original Message -
From: [EMAIL PROTECTED]
Newsgroups: comp.lang.python
To: python-list@python.org
Sent: Monday, September 04, 2006 5:37 PM
Subject: Re: This seems to crash my program and gives me errors on the#include 
statements


 #import se

 # se available at http://cheeseshop.python.org/pypi/SE/2.2%20beta

 looks like it is the se beta..  I didn't get any kind of error or
 traceback that would tell me that though..




 Roberto Bonvallet wrote:
  [EMAIL PROTECTED] wrote:
   It is giving errors on the import statements..  I will get an error on
   the line where I import this routine import csoundroutines and then the
   when I import the the program that tried to import csoundroutines I get
   an error and on down the chain..
 
  Please paste here the errors you get, and paste also the relevant code (not
  the whole program) that triggers that error.
 
  --
  Roberto Bonvallet

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

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


Re: Test for number?

2006-09-04 Thread Erik Max Francis
Helmut Jarausch wrote:

 One step further
 
 try:
eval(x+'0')
 

That is an exceedingly bad idea.  Type:

__import__('sys').exit(),

in the prompt and see what happens.

You _never_ want to run `eval` on an untrusted string.  Never.

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
  San Jose, CA, USA  37 20 N 121 53 W  AIM erikmaxfrancis
   Divorces are made in Heaven.
-- Oscar Wilde
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test for number?

2006-09-04 Thread Hardcoded Software

Dr. Pastor wrote:
 In the following code I would like to ascertain
 that x has/is a number. What the simplest TEST should be?
 (Could not find good example yet.)
 ---
 x=raw_input('\nType a number from 1 to 20')
 if TEST :
   Do_A
 else:
   Do_B
 ---
 Thanks for any guidance.

 == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
 News==
 http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
 Newsgroups
 = East and West-Coast Server Farms - Total Privacy via Encryption =

To test if it *is* a number, the solution is pretty simple (s.isdigit()
or an int(s) in a try..except ValueError), but if you want to test if
it is or *has* a number, I think that the simplest solution would be a
regexp:

import re
re_has_digit = re.compile(r'\d+')
try:
digits = re_has_digit.findall(input)[0]
number = int(digits)
print %d is a number. % number
except IndexError:
print '%s' has no number in it. % input

I didn't try it, but it should work.

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


Re: Twisted vs POS (Plain-old sockets)

2006-09-04 Thread Jean-Paul Calderone
On Mon, 4 Sep 2006 11:40:33 -0700, Darren Kirby [EMAIL PROTECTED] wrote:
 As for documentation, many people say it is lacking, but perhaps one person
 in a thousand points out _how_ or _where_ it is lacking.  Unfortunately it
 is difficult to improve things (or even determine if they really are lacking)
 with this level of feedback.

I am certainly not trying to dump on twisted. As for what is lacking,
the many methods I looked up that say simply Not Documented would be
the biggest problem

I don't mind dumping :)  I just prefer specific to non-specific.

Hope to see you over on the Twisted list,

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


Re: newbe question about removing items from one file to another file

2006-09-04 Thread Anthra Norell

- Original Message -
From: [EMAIL PROTECTED]
Newsgroups: comp.lang.python
To: python-list@python.org
Sent: Monday, September 04, 2006 4:58 AM
Subject: Re: newbe question about removing items from one file to another file



 Anthra Norell wrote:
  Dexter,
 
  Here's a function that screens out all instrument blocks and puts them into 
  a dictionary keyed on the instrument number:
 
  
 
  def get_instruments (file_name):

etc.

   CsOptions
  -W -d -o tone.wav
/CsOptions
   
  ...
  etc.

 I cut and pasted this..  It seems to be crashing my program.. I am not
 sure that I have all the right imports..  seems to be fine when I go to
 an older version of the file...  I uploaded it onto source forge.

 https://sourceforge.net/project/showfiles.php?group_id=156455package_id=201306release_id=444362
 http://www.dexrow.com


Eric (Eric or Dexer?)
  This thread seems to have split. So let me reiterate: please copy the 
output when you cut, paste and run. If you have an
import problem it must be on the other side of your interface with SE, because 
I don't import anything and SE imports what it needs.

Frederic


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


Re: Broadcast server

2006-09-04 Thread Alex Martelli
[EMAIL PROTECTED] wrote:

 Thx Alex,
   This is exactly what i want to look at . Async will definitely be
 something i will look at . Does it make sense to mix async and threaded
 server ( let say a threaded server accepting max 10 connections and
 dealing with client request asynchronously ). Does it sounds you a good
 design.

I would spawn a worker thread only for specific jobs that cannot be done
asynchronously, and would dispatch work requests to it from the main
thread, and get results back, via instances of Queue.Queue.  One example
might be interfacing with a database which does not directly support any
asynchronous operation: all work on that DB should be done by one
dedicated thread that does nothing else.  I have a whole chapter of the
Nutshell dedicated to multiprocessing (processes and threads), and in
that chapter I devote ample space (relative to the Nutshell's always
tight space constraints;-) to recommending the architectures based on
Queue instances that experience teaches me work best.

 
 Of course i will have a look a twisted that sounds me doing all the job
 ( for sure better that i can do ) .

It's a well-crafted and rich framework -- in particular, it already
wraps on your behalf some cases of the need for an auxiliary thread, as
sketched above.  On the other hand, learning in depth the bare metal
on which Twisted's elegant architecture rests is a highly recommended
endeavor: remember Spolsky's Law of Leaky Abstractions... ``all
abstractions leak'', and thus, to use abstractions for the best, you'd
better have a solid understanding of the underlying layers (I strongly
believe that having designed microchips makes me a better assembly
language programmer, having programmed in assembly language makes me a
better C programmer, having programmed in C makes me a better Python
programmer...!-).


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


Re: Syntax suggestion.

2006-09-04 Thread Alex Martelli
samir [EMAIL PROTECTED] wrote:
   ...
 That depends of your need to such tools. For example if you need to
 copy a file, then, resolve a linear system then chroot and set the
 password as de hexadecimal representation of the hash function of pi
 multiplied by the averge of the solution coordinations +_+, you'll need
 IPython ;)

GVIM (and the normal Python interpreter) work better for me: to perform
such a task, I would always write (and run) a script, of course (the
purpose of the chroot step is somewhat mysterious here, btw).  If I have
to perform a strange and complex task once, it's likely that I will have
to perform some variant of it again in the future, and having the script
around will make it easy to edit and tweak.  Furthermore, having the
script around can be a useful indicator when I'm later trying to
reconstruct exactly what it is that I did.


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


Re: threading support in python

2006-09-04 Thread [EMAIL PROTECTED]
Sandra-24 wrote:
 The trouble is there are some environments where you are forced to use
 threads. Apache and mod_python are an example. You can't make use of
 mutliple CPUs unless you're on *nux and run with multiple processes AND
 you're application doesn't store large amounts of data in memory (which
 mine does) so you'd have to physically double the computer's memory for
 a daul-core, or quadruple it for a quadcore.

You seem to be confused about the nature of multiple-process
programming.

If you're on a modern Unix/Linux platform and you have static read-only
data, you can just read it in before forking and it'll be shared
between the processes..

If it's read/write data or you're not on a Unix platform, you can use
shared memory to shared it between many processes.

Threads are way overused in modern multiexecution programming.  The
decision on whether to use processes or threads should come down to
whether you want to share everything, or whether you have specific
pieces of data you want to share.  With processes + shm, you can gain
the security of protected memory for the majority of your code + data,
only sacrificing it where you need to share the data.

The entire Windows programming world tends to be so biased toward
multithreading that they often don't even acknowledge the existence of
generally superior alternatives.  I think that's in large part because
historically on Windows 3.1/95/98 there was no good way to create
processes without running a new binary, and so a culture of threading
grew up.  Even today many Windows programmers are unfamiliar with using
CreateProcessEx with SectionHandle=NULL for efficient copy-on-write
process creation.

 And forget about running a
 windows server, apache will not even run with multiple processes.

It used to run on windows with multiple processes.  If it really won't
now, use an older version or contribute a fix.

Now, the GIL is independent of this; if you really need threading in
your situation (you share almost everything and have hugely complex
data structures that are difficult to maintain in shm) then you're
still going to run into GIL serialization.  If you're doing a lot of
work in native code extensions this may not actually be a big
performance hit, if not it can be pretty bad.

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


Re: Test for number?

2006-09-04 Thread George Sakkis
Dr. Pastor wrote:

 In the following code I would like to ascertain
 that x has/is a number. What the simplest TEST should be?
 (Could not find good example yet.)
 ---
 x=raw_input('\nType a number from 1 to 20')
 if TEST :
   Do_A
 else:
   Do_B
 ---
 Thanks for any guidance.

x=raw_input('\nType a number from 1 to 20')
try:
x = int(x)
if x1 or x20: raise ValueError()
except ValueError:
Do_B
else:
Do_A


If you want to distinguish between the two error cases (not a number vs
number not in [1,20]), handle the second one as Do_C instead of
raising ValueError.

HTH,
George

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


building helper executables with distutils

2006-09-04 Thread Eric S. Johansson
I have a module which needs to invoke a suid helper program in order to 
do what it needs to do.  This suid helper program needs to be built and 
installed at the same time as the module.

Is there any way to do this with distutils?  I've been looking through 
the documentation but haven't really found any way to do it except maybe 
by invoking a system call running a script to do the suid build process.

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


Re: methods and functions, instances and classes

2006-09-04 Thread David Isaac
 Alan Isaac wrote:
  are method calls actually calls of the class's functions?

Bruno Desthuilliers [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Depends on how the method was associated to the instance (you can set
 methods on a per-instance property), but in the general case (functions
 defined in the class body), yes.


[much useful stuff snipped]

Thanks!
Alan


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


Re: Test for number?

2006-09-04 Thread Peter Maas
Tim Williams wrote:
 On 04/09/06, Dr. Pastor [EMAIL PROTECTED] wrote:
 In the following code I would like to ascertain
 that x has/is a number. What the simplest TEST should be?

def isnumber(value):
try:
value/1
return true
except TypeError:
return false

I think this works for all builtin types. Of course one could
overload '/' for a non-numeric class. The best solution would
be to introduce a super class base_number for int, long, float
and decimal, similar to base_string for str and unicode.

This would probably be not too hard to implement and surely not
break old code :)

Peter Maas, Aachen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading support in python

2006-09-04 Thread Paul Rubin
[EMAIL PROTECTED] [EMAIL PROTECTED] writes:
 If it's read/write data or you're not on a Unix platform, you can use
 shared memory to shared it between many processes.
 
 Threads are way overused in modern multiexecution programming.  The
 decision on whether to use processes or threads should come down to
 whether you want to share everything, or whether you have specific
 pieces of data you want to share.

Shared memory means there's a byte vector (the shared memory region)
accessible to multiple processes.  The processes don't use the same
machine addresses to reference the vector.  Any data structures
(e.g. those containing pointers) shared between the processes have to
be marshalled in and out of the byte vector instead of being accessed
normally.  Any live objects such as open sockets have to be shared
some other way.  It's not a matter of sharing everything; shared
memory is a pain in the neck even to share a single object.  These
things really can be easier with threads.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web queries in Python

2006-09-04 Thread Steve Holden
Joseph wrote:
 Hi,
 Excel uses web queries to read data (like financial/weather data) from
 web. How to do the same in python? Even pointers to such would be of
 help.
 
[EMAIL PROTECTED] ~/hwb
$ python
Python 2.5b2 (trunk:50713, Jul 19 2006, 16:04:09)
[GCC 3.4.4 (cygming special) (gdc 0.12, using dmd 0.125)] on cygwin
Type help, copyright, credits or license for more information.
Started with C:/Steve/.pythonrc
   import urllib
   f = urllib.urlopen(http://www.google.com/;)
   data = f.read()
   print data
htmlheadmeta http-equiv=content-type content=text/html; 
charset=ISO-8859
-1titleGoogle/titlestyle!--
body,td,a,p,.h{font-family:arial,sans-serif}
.h{font-size:20px}
.q{color:#00c}
--/style
[...]
a
  href=/intl/en/ads/Advertisingnbsp;Programmes/a - a 
href=/services/Business Solutions/a - a 
href=/intl/en/about.htmlAbout Google/a - a 
href=http://www.google.com/ncrGo to Google.com/a/fontpfont 
size=-2copy;2006 Google/font/p/center/body/html
  

So that's an easy way to get hold of the raw data. Look at htmllib or 
BeautifulSoup to parse it intot he structures you want.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: What are super()'s semantics?

2006-09-04 Thread Carl Banks

Maric Michaud wrote:
 Le lundi 04 septembre 2006 13:48, Carl Banks a écrit :
  Essentially, it's objects that have MROs, not classes.
 Wrong, __mro__ is an attribute of types (subtypes of type) but like __class__
 it is not available in the instances.
 mro() is standard a method of type.

I agree that was misleading; I should have said something like, Type
of an object never changes, therefore the MRO used for an object is
fixed.

BTW, __class__ is available to instances.  (Were you thinking of
__bases__?)


Carl Banks

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


Re: Linear regression in 3 dimensions

2006-09-04 Thread [EMAIL PROTECTED]
Hi Robert,

I'm using the scipy package for such problems. In the submodule
scipy.optimize there is an implmentation of a least-square fitting
algorithm (Levenberg-Marquardt) called leastsq.

You have to define a function that computes the residuals between your
model and the data points:

import scipy.optimize

def model(parameter, x, y):
a, b, c = parameter
return a*x + b*y + c

def residual(parameter, data, x, y):
res = []
for _x in x:
for _y in y:
res.append(data-model(parameter,x,y)
return res

params0 = [1., 1.,1.]
result = scipy.optimize.leastsq(resdiual, params0, (data,x,y))
fittedParams = result[0]

If you haven't used numeric, numpy or scipy before, you should take a
look at an introduction. It uses some nice extended array objects,
where you can use some neat index tricks and compute values of array
items without looping through it.

Cheers! Bernhard



Robert Kern wrote:
 [EMAIL PROTECTED] wrote:
  Hi all,
 
  I am seeking a module that will do the equivalent of linear regression in
  3D to yield a best fit a plane through a set of points (X1, Y1, Z1), (X1,
  Y1, Z1),... (Xn, Yn, Zn).
 
  The resulting equation to be of the form:
 
   Z = aX + bY + c
 
  The function I need would take the set of points and return a,c  c Any
  pointers to existing code / modules would be very helpful.

 Well, that's a very unspecified problem. You haven't defined best.

 But if we make the assumption that you want to minimize the squared error in 
 Z,
 that is minimize

Sum((Z[i] - (a*X[i] + b*Y[i] + c)) ** 2)

 then this is a standard linear algebra problem.

 In [1]: import numpy as np

 In [2]: a = 1.0

 In [3]: b = 2.0

 In [4]: c = 3.0

 In [5]: rs = np.random.RandomState(1234567890)  # Specify a seed for 
 repeatability

 In [6]: x = rs.uniform(size=100)

 In [7]: y = rs.uniform(size=100)

 In [8]: e = rs.standard_normal(size=100)

 In [9]: z = a*x + b*y + c + e

 In [10]: A = np.column_stack([x, y, np.ones_like(x)])

 In [11]: np.linalg.lstsq?
 Type:   function
 Base Class: type 'function'
 String Form:function lstsq at 0x6df070
 Namespace:  Interactive
 File:
 /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/numpy-1.0b2.dev3002-py2.4-macosx-10.4-ppc.egg/numpy/linalg/linalg.py
 Definition: np.linalg.lstsq(a, b, rcond=1e-10)
 Docstring:
  returns x,resids,rank,s
  where x minimizes 2-norm(|b - Ax|)
resids is the sum square residuals
rank is the rank of A
s is the rank of the singular values of A in descending order

  If b is a matrix then x is also a matrix with corresponding columns.
  If the rank of A is less than the number of columns of A or greater than
  the number of rows, then residuals will be returned as an empty array
  otherwise resids = sum((b-dot(A,x)**2).
  Singular values less than s[0]*rcond are treated as zero.


 In [12]: abc, residuals, rank, s = np.linalg.lstsq(A, z)

 In [13]: abc
 Out[13]: array([ 0.93104714,  1.96780364,  3.15185125])

 --
 Robert Kern

 I have come to believe that the whole world is an enigma, a harmless enigma
   that is made terrible by our own mad attempt to interpret it as though it 
 had
   an underlying truth.
-- Umberto Eco

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


Re: py2exe and libxml

2006-09-04 Thread Amaury Forgeot d'Arc
Laszlo Nagy a écrit :
 
 I wrote a little win32 console application that uses libxml2. It is 
 working fine. If I create an .exe version, I get this error when I try 
 to start the program:
 
 Traceback (most recent call last):
  File MyProgram.py, line 3, in ?
  File mylib\item.pyc, line 5, in ?
 ImportError: dynamic module does not define init function (initlibxml2)
 
 What is wrong here?
 Thanks
 

A quick Google search reveals a thread in the py2exe-users list:

http://aspn.activestate.com/ASPN/Mail/Message/py2exe-users/3180430

It seems a regression since py2exe 0.6.5, already corrected in CVS trunk.
And according to another post, version 0.6.3 works fine:
http://permalink.gmane.org/gmane.comp.python.py2exe/1502

Hope this helps,

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


inaccuracy in the time module

2006-09-04 Thread alf
Hi,

can someone explane this:

  from time import *
  timezone
18000


  t=time()
  mktime(gmtime(t))-t
17999.680048942566


why there is a difference?

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


Tkinter window focusing or selecting

2006-09-04 Thread Bob Greschke
I have a program with many forms (Toplevel windows with entry fields). 
Sometimes when I .deiconify() and .lift() a form that is a child of another 
form, but that just got buried under other forms it comes up 'not active' 
(dimmed).  I have to click on the title bar (or anywhere in the window) 
before I can start entering stuff into the entry fields.  It doesn't seem to 
happen all of the time, which I don't understand.  Doing a .focus_set() 
after the .lift() fixes it, but then Tkinter loses track of which entry 
field the cursor was in when the window got covered up.  Is there something 
else I should be calling after the .deiconify() and .lift() to make sure the 
window get 'activated' (or what ever that state is)?  This is on Linux at 
this point.

Thanks!

Bob


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


  1   2   >