--enable-shared, how do i set the rpath?

2006-11-27 Thread Mark Harrison
I've built a python with --enable-shared in order to support mod_python,
but now I have to set LD_LIBRARY_PATH to $prefix/lib. 

Worse, it seems mod_python will die on some import statements,
I'm suspecting ones that need to pull in .so's.

Any clues appreciated...
Mark.

-- 
Mark Harrison
Pixar Animation Studios
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pending: A Mixin class for testing

2006-11-27 Thread Peter Otten
Scott David Daniels wrote:

> Here is a Mix-in class I just built for testing.
> It is quite simple, but illustrates how Mixins
> can be used.
> 
>  class Pending(object):
>  _pending = iter(())
>  def __new__(class_, *args, **kwargs):
>  try:
>  return class_._pending.next()
>  except StopIteration:
>  return super(Pending, class_).__new__(class_,
> *args, **kwargs)
> 
> Now for the use:
> 
>  class Float(Pending, float): pass
> 
>  Float._pending = iter(range(4,7))
> 
>  print [Float(x*(x+1)//2) for x in range(6)]
> 
> Possibly by using itertools functions such as chain as in:
>  Klass._pending = itertools.chain(generate_some(), Klass._pending)
> you can inject fixed values to simplify testing.

If you're willing to allow for issubclass() to fail you can do without a
mixin:

from itertools import chain, repeat

def preload(class_, iterable):
items = chain(
(lambda *args, **kw: item for item in iterable), repeat(class_))
return lambda *args, **kw: items.next()(*args, **kw)

float = preload(float, "ABC")
print [float(x) for x in range(6)]
issubclass(float, float) # TypeError

Argh :-)

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


Re: --enable-shared, how do i set the rpath?

2006-11-27 Thread Martin v. Löwis
Mark Harrison schrieb:
> I've built a python with --enable-shared in order to support mod_python,

Why do you think you have to build with --enable-shared to support
mod_python? I'd try to avoid --enable-shared if possible. It
has undesirable consequences...

> but now I have to set LD_LIBRARY_PATH to $prefix/lib. 

... this being one of them. Actually, if you can pass -Wl,-rpath
correctly to the linkage of mod_python, you don't need
LD_LIBRARY_PATH, unless you move libpython2.5.so around.

> Worse, it seems mod_python will die on some import statements,
> I'm suspecting ones that need to pull in .so's.

You should inspect sys.path to find out whether it ought to find
those modules.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading id3 tags with python

2006-11-27 Thread LaundroMat
On Nov 24, 5:42 pm, "jeff" <[EMAIL PROTECTED]> wrote:
[snip]
> and what do you mean by 'id3reader' cant do directories?
> my for loop just does each file in the dirextory

It's just a friendly warning that you shouldn't suppose that all that
is scanned are indeed files, and not directories.

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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread Michalis Giannakidis

> in general, methods on C objects are implemented in terms of operations
> on the internal data structures, not in terms of a subset of the methods
> already provided by the object.

But what is the reason that the assignment 
l[2] = 6 
call my function, but
l.append(3) 
doesn't ?

Also, why can't I override these functions (for example in order to get access 
to the list.sort() internals)? Or can I?


#!/usr/bin/env python
class L(list):
def __getitem__(self, i):
print 'G', i
return list.__getitem__(self, i)
def __setitem__(self, i, y):
print 'S:', i, y
return list.__setitem__(self, i, y)
def __setslice__(self, i, j, y):
print 'SL:', i, j, y
return list.__setslice__(self, i, j, y)
def __iter__(self, x):
print 'iter:', x
return list.__iter__(self, x)

l = L()
l.append(3) # this does not call my __setitem__
l.append(2)
l.append(1)
l[2] = 6 # this calls my __setitem__
l.sort(key=lambda x: x )
print l

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


Announcing: Keynote Speakers for PyCon 2007

2006-11-27 Thread Jeff Rush
The PyCon organizers would like to announce the slate of keynote speakers who 
have accepted our invitation to speak at PyCon 2007!

PyCon 2007 is taking place in Addison (Dallas), Texas on Feb 23-25 2007.

For photos, biographies and more, check out:

   http://us.pycon.org/TX2007/Keynotes


Ivan Krstić (speaking Friday AM)
Topic: "The Python machine: Python and One Laptop per Child"

Adele Goldberg (speaking Saturday AM)
Topic: TBD (probably something related to Zope 3 and Education)

Guido van Rossum (speaking Saturday Lunch)
Topic: "Python 3000"

Robert M. Lefkowitz ("r0ml") (speaking Sunday AM)
Topic: "The Importance of Programming Literacy"

-Jeff
Co-Chair PyCon 2007
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: synching with os.walk()

2006-11-27 Thread [EMAIL PROTECTED]


On Nov 24, 7:57 am, "Andre Meyer" <[EMAIL PROTECTED]> wrote:
>
> os.walk() is a nice generator for performing actions on all files in a
> directory and subdirectories. However, how can one use os.walk() for walking
> through two hierarchies at once? I want to synchronise two directories (just
> backup for now), but cannot see how I can traverse a second one. I do this
> now with os.listdir() recursively, which works fine, but I am afraid that
> recursion can become inefficient for large hierarchies.
>

I wrote a script to perform this function using the dircmp class in the
filecmp module. I did something similar to this:
import filecmp, os, shutil

def backup(d1,d2):
  print 'backing up %s to %s' % (d1,d2)
  compare = filecmp.dircmp(d1,d2)
  for item in compare.left_only:
fullpath = os.path.join(d1, item)
if os.path.isdir(fullpath):
  shutil.copytree(fullpath,os.path.join(d2,item))
elif os.path.isfile(fullpath):
  shutil.copy2(fullpath,d2)
  for item in compare.diff_files:
shutil.copy2(os.path.join(d1,item),d2)
  for item in compare.common_dirs:
backup(os.path.join(d1,item),os.path.join(d2,item))

if __name__ == '__main__':
  import sys
  if len(sys.argv) == 3:
backup(sys.argv[1], sys.argv[2])

My script has some error checking and keeps up to 5 previous versions
of a changed file. I find it very efficient, even with recursion, as it
only actually copies those files that have changed. I sync somewhere
around 5 GB worth of files nightly across the network and I haven't had
any trouble.

Of course, if I just had rsync available, I would use that.

Hope this helps,

Pete

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


Re: Generator question

2006-11-27 Thread Peter Otten
Mathias Panzenboeck wrote:

> Robert Kern wrote:
>> Timothy Wu wrote:
>>> Hi,
>>>
>>> Using generator recursively is not doing what I expect:
>>>
>>> def test_gen(x):
>>> yield x
>>> x = x - 1
>>> if x != 0:
>>> test_gen(x)
>> 
>> The only thing that the last line does is *create* a new generator
>> object. You need to actually iterate over it and yield its values. E.g.
>> 
>> 
>> In [2]: def test_gen(x):
>>...: yield x
>>...: x -= 1
>>...: if x != 0:
>>...: for y in test_gen(x):
>>...: yield y
>>...:
>>...:
>> 
>> In [3]: list(test_gen(3))
>> Out[3]: [3, 2, 1]
>> 
>> 
> 
> why not this?

Because it doesn't answer the OP's question about recursive generators?
 
> def test_gen(x):
> for y in xrange(x,0,-1):
> yield y
> 
> or even better/shorter:
> 
> test_gen = lambda x: xrange(x,0,-1)

That's not a generator:

>>> g = test_gen(2)
>>> g.next()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'xrange' object has no attribute 'next'
>>> list(g)
[2, 1]
>>> list(g)
[2, 1]

This is:

>>> g = iter(xrange(2, 0, -1))
>>> g.next()
2
>>> list(g)
[1]
>>> list(g)
[]

Unless you are using it in a single for loop, the difference is not so
subtle...

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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread Fredrik Lundh
Michalis Giannakidis wrote:

>> in general, methods on C objects are implemented in terms of operations
>> on the internal data structures, not in terms of a subset of the methods
>> already provided by the object.
> 
> But what is the reason that the assignment 
> l[2] = 6 
> call my function, but
> l.append(3) 

"obj[index] = value" maps to "obj.__setitem__(index, value)".  reading 
the documentation might help; start here:

 http://docs.python.org/ref/specialnames.html



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


A Call for Community Input re PyCon Slogans/Swag

2006-11-27 Thread Jeff Rush
The PyCon organizers have established a short online poll to collect input 
from the Python community regarding the shirts, tote bag and slogans to be 
used at PyCon 2007, being held in Addison (Dallas), Texas Feb 23-25 2007.

When we put out a prior call for slogan suggestions, we received 104 
submissions.  We've since reviewed them, narrowed them down to a number 
reasonable for voting on, and now you can help us decide the winner!  Actually 
we're looking for two winners, one slogan for the T-shirt and another for the 
tote bag.

Please take the poll at the following page.  We've tried to keep it short, to 
respect your time.

   http://us.pycon.org/swagpoll

Thanks!

Jeff Rush
Co-Chair PyCon 2007
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: --enable-shared, how do i set the rpath?

2006-11-27 Thread Robert Kern
Mark Harrison wrote:
> I've built a python with --enable-shared in order to support mod_python,
> but now I have to set LD_LIBRARY_PATH to $prefix/lib. 
> 
> Worse, it seems mod_python will die on some import statements,
> I'm suspecting ones that need to pull in .so's.

I find that most of my Apache problems stem from incorrect permissions. Make
sure that the user running the Apache process has "read" and "execute"
permissions for the .so's.

-- 
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


silent error in email module

2006-11-27 Thread rb . online
Hi all,

I rencently had trouble finding a bug in an email processing script
because of an error that pass silently in the email module.
The get_payload() method in the email.message module always return
something when the decode argument is set to True.
This behaviour is well documented, but is their a reason to catch the
decoding errors ?
Why not let them pop-up to the calling code ?
Do you think it's worth submitting a RFE ?

renaud

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


Re: Persistent Threads & Synchronisation

2006-11-27 Thread Matthew Tylee Atkinson
On Sun, 26 Nov 2006 19:38:20 +, Dennis Lee Bieber wrote:
>   Methods defined in a thread class but called from outside the
> running thread run in the environment of the caller, not as part of the
> thread (and if the method manipulates state you may run into conflicts).

Thanks very much; I'd arrived at this conclusion, but didn't know how to fix the
situation.

>   You CAN NOT restart threads... You have to recreate the whole thread
> object. .start() can only be called ONCE on any thread object.

That clears a lot up.

>   clean(), next(), and quit() will be called by the main thread as
> needed. The "preview thread" does nothing except wait for a command on
> the queue, then performs the operation requested. The main thread will
> have to ensure it calls the next() and clean() methods in proper
> sequence.

Excellent; thanks for the example.

> (How the main thread is informed of completion is something I
> don't know from your post).

Currently, I am using locks (as in threading.Lock()).

>   If you /need/ to have overlapped downloads and cleanups, you will
> need TWO threads, and much more complex interlocking.

I don't, but thanks for the advice.

best regards,


-- 
Matthew Tylee Atkinson <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Python Papers Edition One

2006-11-27 Thread Alan J. Salmoni
I heartily agree. pdf format has never been much of a problem for me.
Now that you have an ISSN, has it been submitted to Google Scholar or
other academic indexes?

http://scholar.google.com/intl/en/scholar/about.html for Google Scholar
http://citeseer.ist.psu.edu/submitDocument.html for Citeseer

These are two I can think of but there must be more. Any suggestions?

I think that this is great work guys - I'll see if I can take some time
to submit some of the code I developed a few years ago.

All the best!

Alan

Łukasz Langa wrote:

> Fredrik Lundh:
> > Tennessee Leeuwenburg wrote:
> >
> >
> >> If anyone has any good ideas for how to cope as a publisher with these
> >> difficulties, I'm all ears.
> >>
> >
> > has any of the format zealots posting to this thread actually
> > volunteered to produce any material for your publication?  if not, I
> > suggest ignoring them.  any bozo with a keyboard can contribute stop
> > energy to a project, but at the end, it's always the people *doing*
> > things that matters.
> >
> > 
>
> +1
>
> The Python Papers look very, very promising! I'm looking forward to
> reading next editions. Don't let whiners slow you down. PDF is a good
> choice, I personally like to print out longer things I read. IANAL, so I
> won't speak for or against CC licenses. They're used widely nowadays for
> a variety of applications (music, art, software, publications) so it
> seems they're doing their job.
> 
> Keep up the good work!
> 
> Best regards,
> Łukasz Langa

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

Re: Ruby/Python/REXX as a MUCK scripting language

2006-11-27 Thread Laurent Pointal
Fred Bayer a écrit :
> 
> Tony Belding wrote:
>> I'm interested in using an off-the-shelf interpreted language as a
>> user-accessible scripting language for a MUCK.  I'm just not sure if I
>> can find one that does everything I need.  The MUCK must be able to
>> call the interpreter and execute scripts with it, but the interpreter
>> must also be able to call functions in the MUCK code.  And then
>> there's the security issue that really worries me. . .  I have to be
>> able to limit what the interpreter can execute.  I can't have my users
>> running scripts that access the console, access the filesystem or
>> sockets directly, or call libraries or other binaries outside the MUCK.
>>
>> Is this practical?  I'm thinking of Ruby or Python for this, if they
>> can meet the requirements.
>>
> 
> Don't forget Lua: www.lua.org
> It fulfills your requirements and is easily embedable.
> 

I Agree with F.Bayer, when reading OP post, I immediatly think about Lua.



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


working with files and directories

2006-11-27 Thread halex2000
Hi all, I'm new with Python, and I thought to use it to automatically rename 
some files in a directory, but I don't know where should I search the 
functions: to get all the files of a directory, to rename the files and so 
on.
Thank you. 


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


Re: working with files and directories

2006-11-27 Thread Fredrik Lundh
"halex2000" wrote:

> Hi all, I'm new with Python, and I thought to use it to automatically rename 
> some files in a 
> directory, but I don't know where should I search the functions: to get all 
> the files of a 
> directory, to rename the files and so on.

see

http://effbot.org/pyfaq/how-do-i-delete-a-file-and-other-file-questions.htm
http://docs.python.org/tut/node12.html

and the relevant modules in the library reference.

 



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


Re: working with files and directories

2006-11-27 Thread Thomas Ploch
halex2000 schrieb:
> Hi all, I'm new with Python, and I thought to use it to automatically rename 
> some files in a directory, but I don't know where should I search the 
> functions: to get all the files of a directory, to rename the files and so 
> on.
> Thank you. 
> 
> 
Have you actually even tried to find some "documentation"?
Have you placed a google search "python directories rename files"?
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: working with files and directories

2006-11-27 Thread Bryan Olson
halex2000 wrote:
> Hi all, I'm new with Python, and I thought to use it to automatically rename 
> some files in a directory, but I don't know where should I search the 
> functions: to get all the files of a directory, to rename the files and so 
> on.

Python programmers are constantly looking at:

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

In this case, see 14.1.4, 11.1, and 11.10.

Happy hacking.

-- 
--Bryan

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


Re: working with files and directories

2006-11-27 Thread halex2000

"Thomas Ploch" <[EMAIL PROTECTED]> ha scritto nel messaggio 
news:[EMAIL PROTECTED]
> Have you actually even tried to find some "documentation"?
> Have you placed a google search "python directories rename files"?
> Thomas

Actually I did it on the documentation file provided with the windows 
distribution. I took a look at 11 ("File and Directory Access") but the 
listed functions doesn't appear to be what I need. 14.1.4 should do the job, 
but was not as intuitive to find as the previous one. 


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


Re: working with files and directories

2006-11-27 Thread halex2000

"Bryan Olson" <[EMAIL PROTECTED]> ha scritto nel messaggio 
news:[EMAIL PROTECTED]
> halex2000 wrote:
>> Hi all, I'm new with Python, and I thought to use it to automatically 
>> rename some files in a directory, but I don't know where should I search 
>> the functions: to get all the files of a directory, to rename the files 
>> and so on.
>
> Python programmers are constantly looking at:
>
> http://docs.python.org/lib/lib.html
>
> In this case, see 14.1.4, 11.1, and 11.10.
>
> Happy hacking.
>
> -- 
> --Bryan
>
Thank you very much :-) 


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


Re: working with files and directories

2006-11-27 Thread Duncan Booth
"halex2000" <[EMAIL PROTECTED]> wrote:
> "Thomas Ploch" <[EMAIL PROTECTED]> ha scritto nel messaggio 
> news:[EMAIL PROTECTED]
>> Have you actually even tried to find some "documentation"?
>> Have you placed a google search "python directories rename files"?
>> Thomas
> 
> Actually I did it on the documentation file provided with the windows 
> distribution. I took a look at 11 ("File and Directory Access") but
> the listed functions doesn't appear to be what I need. 14.1.4 should
> do the job, but was not as intuitive to find as the previous one. 
> 
Do you know about the search tab in windows help? Searching for "rename 
files", or indeed a search identical to the one suggested for Google will 
both find 14.1.4 as the top hit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How good is CORBA?

2006-11-27 Thread Chris Mellon
On 11/24/06, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
> > "Chris Mellon" <[EMAIL PROTECTED]> (CM) wrote:
>
> >CM> FYI: Ice is available under the GPL, so if by "pay" you mean "pay
> >CM> money" that's not your only option. You can also get a commercial
> >CM> license, similiar to Qt.
>
> >CM> I like Ice a lot, it's got hardly any of the ramp up time and learning
> >CM> curve that CORBA does, and it's extremely efficent. If GPL or cash are
> >CM> acceptable licensing options to you, then I encourage you to use it
> >CM> before you head to CORBA.
>
> OmniORB's author did some benchmarking and it appeared that omniORB was
> faster than Ice.

Nowhere did I say that Ice was faster than any given CORBA
implementation. People who want to do benchmark shootouts are on their
own. Ice is quick to learn, easy to use, and fast on the wire. That's
a good step up over CORBA to me.

> --
> Piet van Oostrum <[EMAIL PROTECTED]>
> URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
> Private email: [EMAIL PROTECTED]
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread Michalis Giannakidis
On Monday 27 November 2006 11:50, Fredrik Lundh wrote:

> "obj[index] = value" maps to "obj.__setitem__(index, value)".  reading
> the documentation might help; start here:
>
>  http://docs.python.org/ref/specialnames.html

In this documentation page it also says:
--snip---
then x[i] is equivalent3.2 to x.__getitem__(i). 
--snip--
This, and other statements, are only roughly true for instances of new-style 
classes. 
--snip--

So which statements are actually true for new style classes? 

Is l[0]=1 completely different from l.append(1) or maybe insert?

And is there a mechanism in Python that will allow me to override the 
operators of a class, for all its occurrences, even the ones implemented on C 
built-in objects?


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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread Duncan Booth
Michalis Giannakidis <[EMAIL PROTECTED]> wrote:

> On Monday 27 November 2006 11:50, Fredrik Lundh wrote:
> 
>> "obj[index] = value" maps to "obj.__setitem__(index, value)". 
>> reading the documentation might help; start here:
>>
>>  http://docs.python.org/ref/specialnames.html
> 
> In this documentation page it also says:
> --snip---
> then x[i] is equivalent3.2 to x.__getitem__(i). 
> --snip--
> This, and other statements, are only roughly true for instances of
> new-style classes. 
> --snip--
> 
> So which statements are actually true for new style classes? 

I think it means that the statements are true in general, but there may be 
specific corner cases which break them. Usually you can assume that the 
rough description will be good enough.

> 
> Is l[0]=1 completely different from l.append(1) or maybe insert?

Yes. It neither appends nor inserts.

> And is there a mechanism in Python that will allow me to override the 
> operators of a class, for all its occurrences, even the ones
> implemented on C built-in objects?

No.

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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread Fredrik Lundh
Michalis Giannakidis wrote:

>> "obj[index] = value" maps to "obj.__setitem__(index, value)".  reading
>> the documentation might help; start here:
>>
>>  http://docs.python.org/ref/specialnames.html
> 
> In this documentation page it also says:
> --snip---
> then x[i] is equivalent3.2 to x.__getitem__(i). 
> --snip--
> This, and other statements, are only roughly true for instances of new-style 
> classes. 
> --snip--
> 
> So which statements are actually true for new style classes? 
> 
> Is l[0]=1 completely different from l.append(1) or maybe insert?

l.append(1) is a method call.  L[0]=1 is syntactic sugar for a 
*different* method call.  why is this so hard to understand?



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


Re: About alternatives to Matlab

2006-11-27 Thread Rob Purser
Hi all,

I'm not going to touch the big picture issues here -- you need to pick the 
right tool for the job you're doing, and only you know what works best for 
your task.  However, since it didn't come up, I feel I need to add a piece 
of info to the mix, since I spend my days getting MATLAB working with data 
acquisition hardware.  To be clear, I'm the development lead for Data 
Acquisition Toolbox, which is MathWorks' add on product to MATLAB and 
Simulink to handle all the issues associated with interfacing data 
acquisition hardware without all the CMEX work, threading, DLLs, etc.  As 
Sturla points out, that's not trivial work in any language.

Anyway, I just wanted to call your attention to Data Acquisition Toolbox:
http://www.mathworks.com/products/daq/

I'm not sure what hardware you're using, Phil, so I can't say whether we 
support it.  We do add support for new hardware all the time, so I'd be 
interested in hearing about your application.

All the best,
-Rob

-- 
Rob Purser
Senior Team Lead, Connectivity Products
The MathWorks
[EMAIL PROTECTED]

"sturlamolden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> Phil Schmidt wrote:
>
>> Thanks for that list. I'm currently in the process of getting quotes
>> for a bunch of Matlab tools for hardware-in-the-loop simulation. Big
>> bucks.
>
> Yup, and better spent elsewhere...
>
>
>> I'd love to use Python, but I'm not comfortable with the hardware side
>> of that. I'm certain that most, if not all data acquisition hardware
>> comes with DLL drivers, which I could interface with using ctypes. I'm
>> concerned though about spending more time messing around with the
>> hardware interface than it's worth.
>
> Usually you have to mess equally much with Matlab, writing CMEX
> interfaces between the DLLs and Matlab. And afterwards you get the
> headache of Matlab's single-threaded environment and horrible
> pass-by-value sematics.
>
>
>> Do you have any experience with this side of the Matlab replacement
>> question? How about anyone else? Any recommendations?
>
> If you are afraid of doing some C coding or using ctypes, I'd say go
> for LabView. When it comes to data acquisition, LabView is far superior
> to Matlab. And data acquisition hardware usually comes with LabView
> drivers ready to run. LabView can also compile programs that you can
> run on real-time OS'es and common DSP chips, so you will not need to
> port your code to these targets if you need hard real-time constraints
> in your system.
>
> First find out what drivers or APIs are supplied with the hardware.
> Then do the decision of which language to use - including Python,
> Matlab, LabView, Java, C# .NET, C or C++. I would in any case get a
> quote for LabView as well, i does not cost you anything just to obtain
> the quote. Generally, development time is far more expensive than
> licenses, even with the ultra-expensive Matlab and LabView software.
> Using Python just for the sake of using Python is silly.
> 


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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread Carl Banks
Fredrik Lundh wrote:
> Michalis Giannakidis wrote:
>
> > Could someone please explain the reasoning/behabiour of these?
>
> in general, methods on C objects are implemented in terms of operations
> on the internal data structures, not in terms of a subset of the methods
> already provided by the object.

True, and it's also true for many Python classes.  Here's a very silly
example:

class Cons(object):
def __init__(self,car,cdr):
self.car = car
self.cdr = cdr
def __getitem__(self,key):
if key == "car":
return self.car
if key == "cdr":
return self.cdr
raise KeyError(key)
def __getitem__(self,key,value):
if key == "car":
self.car = value
if key == "cdr":
self.cdr = value
raise KeyError(key)
def swap(self):
self.car,self.cdr = self.cdr,self.car

So hooking into __getitem__ and __setitem__ won't let you inpect the
swap operation.  It's much the same with lists: they bypass __getitem__
and __setitem__ and go directly to their internal.

OTOH, I've written a few C types that deliberately go though slower
Python methods to allow overriding.  But that has to be deliberate (for
the most part); as Frederick said, most C classes don't do that.


Carl Banks

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


Re: Persistent Threads & Synchronisation

2006-11-27 Thread Paul McGuire
"Matthew Tylee Atkinson" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I appear to be having some problems with the isAlive() method of
> detecting if a thread is alive/active/running or not.  I'd be grateful
> for any advice.
>
Your comments about restartable threads got me thinking about generators. 
While this does not strictly do threading, this little example uses a list 
of generators, which save their state and pick up where they left off. 
(Also, look into simpy, which has a similar concept, but much more 
infrastructure support).

-- Paul


class Processor(object):
def __init__(self, id_):
self.id = id_
self.finished = False

def __str__(self):
return "Processor: %s" % self.id

def run(self):
def runImpl_(self):
runGen = self.runImpl()
while not self.finished:
try:
yield self.id,runGen.next()
except StopIteration:
self.finished = True
return runImpl_(self)

def runImpl(self):
times = 0
while times < self.id:
times += 1
yield times


import random

class RandomProcessor(Processor):
# just implement runImpl in subclass
def runImpl(self):
times = 0
while times < self.id:
times += 1
yield random.random()

def main():
# create list of processors
procList =[ (random.choice([True,False]) and
Processor(i) or RandomProcessor(i))
for i in range(10)]
procs = [ (p,p.run()) for p in procList ]

# context switch loop
while procs:

# cycle through all processors
for p in procs:
try:
ret = p[1].next()
print ret
except StopIteration:
pass

# remove any processors that have finished
procs = [ p for p in procs if not p[0].finished ]

main()



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


Is PyGTK only for local - not web?

2006-11-27 Thread walterbyrd
I have noticed that there is also pygtk-web project, I suppose that is
what you use for the web?

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


Re: Python v PHP: fair comparison?

2006-11-27 Thread Cameron Laird
In article <[EMAIL PROTECTED]>, I reported:
.
.
.
>I appreciate your clarification.  I can report back that we
>certainly move in different circles; I, for example, knew of
>people with multi-million-dollar budgets deciding on Python-
>based Web technology for *serious* applications in '96.  Ruby
.
.
.
Was Python really *such* big business so long ago?  Without put-
ting myself out to look through my notes, and make sure of what I
have permission to disclose, I can point, for instance, to http://www.opticality.com/Press/Opticality/LinuxMagazine/view >:
"By October 1998, Pedhazur had invested $750,000" in Digital Cre-
ations, the company behind Python-based Web framework Zope (modulo
a few name changes).  That's not the only case.  So, yes, I repeat:
Python-based Web business well beyond the scale of "parts we found
in a dumpster" has been going on for a decade.

I'm ready to grant Ruby on Rails has impacted cultural awareness
in a way Python doesn't yet touch.  I'm not a good judge of such 
matters.
-- 
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Nov 27)

2006-11-27 Thread Paul Boddie
QOTW:  "Given these criteria, my recommendations for a first programming
language would be Python or Scheme." - Peter Norvig (some time ago, but
referenced on comp.lang.lisp this week)
http://www.norvig.com/21-days.html

"however if you want more visual effect with less hassle, consider learning 
Python instead. with Python you can get some graphical stuff working almost 
out-of-the box, while with Lisp it's matter of luck if particular thing will 
work on your system :)." -- Alex Mizrahi (on comp.lang.lisp)
http://groups.google.com/group/comp.lang.lisp/msg/7a30146ff97f79b1


Those in California get to hear what Python's "benevolent dictator" 
does in his day job:

http://groups.google.com/group/comp.lang.python.announce/browse_frm/thread/f09ffd3e7200e06f/

...something which isn't fully explained in the Google Master Plan:
http://www.larsen-b.com/Article/246.html

And for the sake of intercontinental relevance, our European pick of 
events has to be the Plat_Forms Web development contest in Germany:

http://groups.google.com/group/pylons-discuss/browse_frm/thread/2330ada0c8e5605c/
... although RuPy also certainly deserves attention:
http://rupy.wmid.amu.edu.pl/

(November 30th is a big day: it's the Plat_Forms registration deadline
*and* Guido's talk, as well as the last day of Ingeniweb in Paris, ...)

"Pitivi is written in Python and as such should be an easy project for 
developers to get started with." Apparently, the non-linear video editor
in question could really move forward "if more python hackers came onboard
to help out":
http://blogs.gnome.org/view/uraeus/2006/11/22/0
http://www.pitivi.org/

Or if your interest is in audio editing, the Python/GTK/GNOME-based
Jokosher might welcome your contributions:
http://www.jokosher.org/contribute

A fledgling free PDF journal appears.
http://pythonpapers.org/ 

November's installment of the language popularity contest quickly leads
to an investigation into the coherency of Python's Web programming
options:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/02875f58a917c04d

Fundamental questions about the nature of time seem to arise when one is 
"blazin' some mad chronix":

http://groups.google.com/group/comp.lang.python/browse_frm/thread/95b64b889bef4c46

Meanwhile, potentially better use of time can sometimes be achieved by 
compiling inline C code at runtime, using cinpy (C in Python) and the 
remarkable tcc (Tiny C Compiler):
http://www.cs.tut.fi/~ask/cinpy/

And for those who want to pretend they're writing Python whilst really
writing C++, pyplus maintains the illusion:
http://www.imitationpickles.org/pyplus/

But without resorting to the joys of C++, some of those desirable
"compile-time" checks can be run on Python source code, too, thanks to
pylint:

http://groups.google.com/group/comp.lang.python.announce/browse_frm/thread/36a06d611e9a6363/

Advice about moving from Matlab to Python isn't in short supply this week:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/a71af37fd9372868/





Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mail

Re: Several entries on Tile and TableList at the Tkinter wiki

2006-11-27 Thread jim-on-linux
Thanks for posting this entry,

The fact that a wiki or help site doesn't get a 
lot of traffic is not an necessarily an indicator 
of it's usfulness.  It indicates to me that the 
product, in this case Tkinter, may be easy to use 
and understand, after working with it a little, A 
lot of help may not be necessary.

A good example is the py2exe help site.
At one time not to long ago there might be 8 to 12 
post per day, or more. Today by my unscientific 
count method, I don't think there are more than 3 
to 4 post per week.  Yet, py2exe and Tkinter is 
almost as valuable as Python. If we couldn't 
build programs for Windows, where would a python 
programmes's money come from?

Thanks again,

jim-on-linux
http://www.inqvista.com



On Sunday 26 November 2006 15:50, Kevin Walzer 
wrote:
> I'm not sure how often members of this list
> visit the Tkinter wiki at
> http://tkinter.unpythonic.net/wiki/FrontPage; 
> this wiki seems to have less traffic in general
> than the Tcl/Tk wiki at http://wiki.tcl.tk.
> Given that, I hope it's not out of line for me
> to call attention to several pages that I've
> posted about integrating Tile
> (http://tktable.sourceforge.net/tile) and
> TableList (http://www.nemethi.de,
> http://wiki.tcl.tk/5527) into Tkinter
> applications. I've noted a serious lack of
> resources/documentation about these two
> powerful Tk components. In addition to some
> documentation, screenshots, and sample
> applications, I've posted updated versions of
> the original TableList and Tile wrappers by
> Martin Franklin.
>
> I should take this moment to thank Mr. Franklin
> for his work on these wrappers; whatever I
> added to them was pretty minimal compared to
> the heavy lifting he did. He originally posted
> them on the Internet last year, but the site
> that hosted them has gone dark. Anyway, Mr.
> Franklin, if you are reading this, thank you
> for your hard work; it has been enormously
> helpful. I hope my own efforts extend your work
> and make it even more useful for other Tkinter
> developers.
>
> Here are the links:
>
> http://tkinter.unpythonic.net/wiki/UsingTile
> http://tkinter.unpythonic.net/wiki/TileWrapper
> http://tkinter.unpythonic.net/wiki/TableListWra
>pper
> http://tkinter.unpythonic.net/wiki/TableListTil
>eWrapper
> http://tkinter.unpythonic.net/wiki/PyLocateTile
> http://tkinter.unpythonic.net/wiki/PyLocate
>
> Hope these prove useful to others, as starting
> points for your own work if nothing else.
> Corrections and improvements are of course
> invited; it's a wiki!
>
>
> --
> Kevin Walzer
> Code by Kevin
> http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


shtoom complicated install

2006-11-27 Thread Croteam
Hello,

I have install problem about shtoom.How to I Install shtoom
correct,when I install shtoom
with setup.py (shtoom package setup file), it just make some directory
(shtoom-0.2) and
3 python files with them.But just tell me this,when I was manual make
folder by name "shtoom" (as write in shtoom package setup file) and in
that folder put folders: app,audio,multicast,ui ,now I must
"insert" python files from shtoom package into that folders but I don't
know where  I must put
every file?? In what folder.



 I will appreciate any help

 Regards,Vedran

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


Calling a thread asynchronously with a callback

2006-11-27 Thread Edwin Gomez
I'm a C# developer and I'm new to Python.  I would like to know if the concept 
of Asynchronous call-backs exists in Python.  Basically what I mean is that I 
dispatch a thread and when the thread completes it invokes a method from the 
calling thread.  Sort event driven concept with threads.


Thanks. 

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


Re: Active State and Komodo...

2006-11-27 Thread Trent Mick
Steve Thompson wrote:
> Hello all,
> 
> I was wondering the differnced there were betwee Active State's python and
> the open source version of python. 

Here is the best answer to that:
http://groups.google.com/group/comp.lang.python/tree/browse_frm/thread/e8291fcb1418e80/16f39060f654402f?rnum=1&hl=en&q=ActivePython+trent&_done=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2Fe8291fcb1418e80%2F98c87a6a5dc8f3c0%3Ftvc%3D1%26q%3DActivePython+trent%26hl%3Den%26#doc_b6f732ab2c8434ef
http://tinyurl.com/y7r47q


> Would I have to unistall my opend souce
> python? 

No. As BartlebyScrivener wrote you shouldn't do that. You can easily install 
ActivePython side-by-side with another Python install on Linux.


 > Additonally, how does Active State's Komodo IDE vs. the eric3 IDE
> unler SuSE Linux v. 10.i?
> 
> Addionally, is the eric IDE (version 3) an acceptible IDE or are there
> more easy and more productive IDE's for perl?

*I* like Komodo, but then I am biased because I am one of its developers. :)
I presume you meant Python instead of Perl there, but if not, Komodo does 
support Perl as well as Python (and PHP, JavaScript, Ruby, Tcl and XSLT too).

This is a pretty good review of Python IDEs (although note that most, if not 
all, of the IDEs reviewed there will have advanced a few versions).

http://spyced.blogspot.com/2005/09/review-of-6-python-ides.html


Komodo 4 is currently under public beta (Komodo 4 beta 1 is out now and beta 2 
should be released later this week). Try it out:

http://www.activestate.com/products/komodo/beta.plex#features


Cheers,
Trent

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: working with files and directories

2006-11-27 Thread halex2000

"Duncan Booth" <[EMAIL PROTECTED]> ha scritto nel messaggio 
news:[EMAIL PROTECTED]
> "halex2000" <[EMAIL PROTECTED]> wrote:
>> "Thomas Ploch" <[EMAIL PROTECTED]> ha scritto nel messaggio
>> news:[EMAIL PROTECTED]
>>> Have you actually even tried to find some "documentation"?
>>> Have you placed a google search "python directories rename files"?
>>> Thomas
>>
>> Actually I did it on the documentation file provided with the windows
>> distribution. I took a look at 11 ("File and Directory Access") but
>> the listed functions doesn't appear to be what I need. 14.1.4 should
>> do the job, but was not as intuitive to find as the previous one.
>>
> Do you know about the search tab in windows help? Searching for "rename
> files", or indeed a search identical to the one suggested for Google will
> both find 14.1.4 as the top hit.

I'm aware of it, thank you. I usually don't use to ask for infos that I 
could easily find myself in a few seconds, but I had not the time at the 
moment to even start a search (of course, If I knew it would have been so 
quick, I would have done it myself). I was just under the impression that I 
was looking in the wrong place. 


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


Re: Calling a thread asynchronously with a callback

2006-11-27 Thread Diez B. Roggisch
Edwin Gomez wrote:

> I'm a C# developer and I'm new to Python.  I would like to know if the
> concept of Asynchronous call-backs exists in Python.  Basically what I
> mean is that I dispatch a thread and when the thread completes it invokes
> a method from the calling thread.  Sort event driven concept with threads.

Counter question: does such a thing exist in C#, and if, is it bound to some
existing event loop? 

I'm really curious, because having code being interrupted at any time by a
asynchronous callback strikes me as dangerous. But then maybe I'm just a
whimp :)

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


Re: Calling a thread asynchronously with a callback

2006-11-27 Thread Bjoern Schliessmann
Edwin Gomez wrote:

> I'm a C# developer and I'm new to Python.  I would like to know if
> the concept of Asynchronous call-backs exists in Python.

Sure. Either with this:

http://twistedmatrix.com/projects/core/documentation/howto/async.html

Or manually using select().

> Basically what I mean is that I dispatch a thread and when the
> thread completes it invokes a method from the calling thread. 
> Sort event driven concept with threads.

What you describe here isn't the only way to do asynchronous
callbacks. See above for a simpler way.

Regards,


Björn

-- 
BOFH excuse #233:

TCP/IP UDP alarm threshold is set too low.

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


python skipping lines?

2006-11-27 Thread lisa . engblom
Hi,

I've just started programming in python, and have run into an
unexpected problem.  I am using python to pull text data from some csv
files.  I have one file that has the important identifiers (name, etc)
and other files with lots of other data.  I wrote a function that takes
the file name and identifiers as inputs, selects the data I need, and
outputs it to another file.  This function (PullData) seems to work
fine.

In the same .py file, but separate from the function, I entered used
"for line in file" to step through each line in my identifier file and
feed the identifiers into my PullData function.  It works fine for the
first entry in my identifier file, but it will not call the function
again.  It will execute lines before or after the appropriate number of
times given the number of lines in the identifier file.  i just put in
a dummy counter variable to try to figure out why it wasn't working)
... but it always skips the function call after the first line.

Any ideas of what could be the problem?

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


can't get cgi values

2006-11-27 Thread ronrsr
I'm having trouble extracting cgi parameters in my code - this is a web
application, so I only know the line that's causing the problem.

here's the info I know:

form = FieldStorage(None, None, [MiniFieldStorage('zid', '17'),
MiniFieldStorage('keywords', 'aAUA'), MiniFieldStorage('keywords',
'aBOS'), MiniFieldStorage('citation', 'The Earth Times Monthly,
April 2002\\r\\n   \\r\\n   \r\n   '),
MiniFieldStorage('quotation', 'Farm support goes mainly to a relatively
small number of agri-businesses, many of them large corps. Yet these
subsidies are 6 times what rich countries provide in foreign aid to a
developing world that includes 5 billion people.\\r\\n   \r\n
'), MiniFieldStorage('updatebutton', 'Update')])
form.has_key("citation") = True



 fileHandle.write("here aer the haskeys");
 fileHandle.write( str(form.has_key("citation")))
/* returns TRUE */

 temp = str(form("citation").value)
 /* python stops here,

form("citation appears to be undefined */



 print (str(form("citation").value))
  /* this doesn't work, either */




 if form.has_key("keywords"):  /*
neither does this */
 keywords = str(form["keywords"].value)
 else:
  keywords = "k"

  




any ideas on what the problem is? 

thank you so much. 

-rsr-

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


Re: can't get cgi values

2006-11-27 Thread Fredrik Lundh
ronrsr wrote:

> I'm having trouble extracting cgi parameters in my code - this is a web
> application, so I only know the line that's causing the problem.

seen this:

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

?

>  temp = str(form("citation").value)

did you perhaps mean form["citation"] ?



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


Re: can't get cgi values

2006-11-27 Thread Paul McGuire
form("citation").value

Is form some form of dict?  If so, then this should be something like:

form["citation"]

If not, then maybe value is a function, requiring ()'s to actually invoke 
it.

-- Paul 


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


super() and type()

2006-11-27 Thread Chris Mellon
I see super documented, and in use, as below (from the Python documentation)

class C(B):
def meth(self, arg):
super(C, self).meth(arg)

I'd like to not write C all the time, so is there any problem with writing:

class C(B):
def meth(self, arg):
super(type(self), self).meth(arg)


This seems to work in practice but I don't see it used anywhere and
I'm worried what I might be missing.

This was especially brought to my attention because pylint flags the
second usage as invalid, and I'm not sure if it should be considered a
false positive or not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python skipping lines?

2006-11-27 Thread Jordan Greenberg
[EMAIL PROTECTED] wrote:
> Hi,

> Any ideas of what could be the problem?
> 

Hard to say without seeing your code.

Jordan Greenberg

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: can't get cgi values

2006-11-27 Thread robert
ronrsr wrote:
> I'm having trouble extracting cgi parameters in my code - this is a web
> application, so I only know the line that's causing the problem.

if exceptions try "import cgitb; cgitb.enable()" to get a traces directly in 
HTML for testing; otherwise read the server log (logs of httpd etc.) for traces

> 
> here's the info I know:
> 
> form = FieldStorage(None, None, [MiniFieldStorage('zid', '17'),
> MiniFieldStorage('keywords', 'aAUA'), MiniFieldStorage('keywords',
> 'aBOS'), MiniFieldStorage('citation', 'The Earth Times Monthly,
> April 2002\\r\\n   \\r\\n   \r\n   '),
> MiniFieldStorage('quotation', 'Farm support goes mainly to a relatively
> small number of agri-businesses, many of them large corps. Yet these
> subsidies are 6 times what rich countries provide in foreign aid to a
> developing world that includes 5 billion people.\\r\\n   \r\n
> '), MiniFieldStorage('updatebutton', 'Update')])
> form.has_key("citation") = True
> 
> 
> 
>  fileHandle.write("here aer the haskeys");
>  fileHandle.write( str(form.has_key("citation")))
> /* returns TRUE */
> 
>  temp = str(form("citation").value)
>  /* python stops here,
> 
> form("citation appears to be undefined */
> 
> 
> 
>  print (str(form("citation").value))
>   /* this doesn't work, either */
> 


try "form['citation']"

why the Python cgi module and the documentation is a horror, read: <[EMAIL 
PROTECTED]>


Robert

> 
> 
>  if form.has_key("keywords"):  /*
> neither does this */
>  keywords = str(form["keywords"].value)
>  else:
>   keywords = "k"
> 
>   
> 
> 
> 
> 
> any ideas on what the problem is? 
> 
> thank you so much. 
> 
> -rsr-
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python skipping lines?

2006-11-27 Thread lisa . engblom
thats easy enough to solve

"""test text.py
for playing around with my text editing task
"""

UnitList = open('/Python25/working/FacList.txt', 'r')
RawData = open('/Python25/working/data.txt', 'r')
Output = open('/Python25/working/output.txt', 'a')

def PullHourlyData(filename, facility, unit):
for line in filename:
data = line.split('","')
CurrentFacility = data[1]
CurrentUnit = data[3]
CurrentSO2Mass = data[9]#in lb/hour
#print CurrentFacility
#print CurrentUnit

if facility == CurrentFacility and unit == CurrentUnit:

#print >> Output, '"%s", "%s", "%s"' %
(CurrentFacility, CurrentUnit, CurrentSO2Mass)
print '"%s", "%s", "%s"' % (CurrentFacility,
CurrentUnit, CurrentSO2Mass)
else:
print facility
print unit
print CurrentFacility
print CurrentUnit
print "\n"


counter = 0

for combos in UnitList:
print counter
FandU = combos.split('","')
#print combos
FacilityName = FandU[0]
UnitName = FandU[1]
#print FacilityName
#print UnitName
FacilityName = FacilityName.strip('"')
UnitName = UnitName.strip('",\n')
print FacilityName
print UnitName

PullHourlyData(RawData, FacilityName, UnitName)
counter += 1


UnitList.close()
RawData.close()
Output.close()
print "Done!"

Jordan Greenberg wrote:
> [EMAIL PROTECTED] wrote:
> > Hi,
> 
> > Any ideas of what could be the problem?
> >
>
> Hard to say without seeing your code.
>
> Jordan Greenberg
> 
> -- 
> Posted via a free Usenet account from http://www.teranews.com

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


Re: python skipping lines?

2006-11-27 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> thats easy enough to solve
> 
> """test text.py
> for playing around with my text editing task
> """
> 
> UnitList = open('/Python25/working/FacList.txt', 'r')
> RawData = open('/Python25/working/data.txt', 'r')
> Output = open('/Python25/working/output.txt', 'a')
> 
> def PullHourlyData(filename, facility, unit):
> for line in filename:
> data = line.split('","')
> CurrentFacility = data[1]
> CurrentUnit = data[3]
> CurrentSO2Mass = data[9]#in lb/hour
> #print CurrentFacility
> #print CurrentUnit
> 
> if facility == CurrentFacility and unit == CurrentUnit:
> 
> #print >> Output, '"%s", "%s", "%s"' %
> (CurrentFacility, CurrentUnit, CurrentSO2Mass)
> print '"%s", "%s", "%s"' % (CurrentFacility,
> CurrentUnit, CurrentSO2Mass)
> else:
> print facility
> print unit
> print CurrentFacility
> print CurrentUnit
> print "\n"
> 
> 
> counter = 0
> 
> for combos in UnitList:
> print counter
> FandU = combos.split('","')
> #print combos
> FacilityName = FandU[0]
> UnitName = FandU[1]
> #print FacilityName
> #print UnitName
> FacilityName = FacilityName.strip('"')
> UnitName = UnitName.strip('",\n')
> print FacilityName
> print UnitName
> 
> PullHourlyData(RawData, FacilityName, UnitName)
> counter += 1
> 
> 
> UnitList.close()
> RawData.close()
> Output.close()
> print "Done!"
> 
> Jordan Greenberg wrote:
>> [EMAIL PROTECTED] wrote:
>>> Hi,
>> 
>>> Any ideas of what could be the problem?
>>>
>> Hard to say without seeing your code.
>>
>> Jordan Greenberg
>>
>> -- 
>> Posted via a free Usenet account from http://www.teranews.com
> 

The first time through the loop you read through RawData and are at
the bottom of the file.  You either need to seek back to the beginning
or you need to close and reopen the file each time through the loop.

Suggestions:

1) In PullHourData the first argument is filename.  In fact
it is not a filename but rather a file pointer.  Just a little
confusing for anyone coming along behind you.

2) If the data is well-formed CSV you should probably take a look
at the csv module.  It handles CSV data better than splitting on
commas (which can be dangerous as there can be commas inside of
literal data).

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


Passing com object from simple xmlrpc server to client

2006-11-27 Thread tsjuan
Hello python users,

I am just learning on how to use xmlrpc and stumbled upon how to pass
com object
from server to client side.

The client side complain about can't marshall the com object. I don't
know what type
of marshall command I should use to pass the object.

Below are my scripts, any help / comments are greatly appreciated:

# Server Side script
# ===

import win32com.client
import SimpleXMLRPCServer
import pythoncom

class ServerFunctions(object):

   def call_com_object(self):
   pythoncom.CoInitialize()
   return win32com.client.Dispatch('excel.application')

if __name__ == '__main__'
server =
SimpleXMLRPCServer.SimpleXMLROCServer(('hostname',portnumber))
server.register_instance(ServerFunctions())


# Client Side Script
# ==

import xmlrpclib
client = xmlrpclib.Server('http://hostname:portname";)
excel_object = client.call_com_object()



Regards,
Tanto Sugiarto

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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread OKB (not okblacke)
Duncan Booth wrote:

>> And is there a mechanism in Python that will allow me to override
>> the operators of a class, for all its occurrences, even the ones
>> implemented on C built-in objects? 
> 
> No.

For what it's worth, which is undoubtedly nothing, this is 
something that I think needs to change.  All this talk about new-style 
classes and class-type unification is empty words if you can't override 
anything on any type without having to know whether it's written in C or 
Python.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python skipping lines?

2006-11-27 Thread Jussi Salmela
[EMAIL PROTECTED] wrote:

> RawData = open('/Python25/working/data.txt', 'r')

You open this file only once. The first time in here:

> def PullHourlyData(filename, facility, unit):
> for line in filename:

reads all of the file - nothing left for the other function calls!

A better way would be to read the file in once to a list and give that 
lkist to the function to process.

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


Re: python skipping lines?

2006-11-27 Thread Tim Chase
I'm not sure if this will /solve/ your problem, but it's 
something I noticed...

> UnitList = open('/Python25/working/FacList.txt', 'r')
> RawData = open('/Python25/working/data.txt', 'r')

Here, you open RawData once...

> Output = open('/Python25/working/output.txt', 'a')
> 
> def PullHourlyData(filename, facility, unit):
> for line in filename:
[cut]
> counter = 0
> 
> for combos in UnitList:
[cut]
> PullHourlyData(RawData, FacilityName, UnitName)
> counter += 1

and your first pass through this loop, you exhaust RawData by 
reading to the end.  The second pass through the UnitList loop, 
you pass the exhausted RawData to PullHourlyData().  I'm thinking 
you'd need to RawData.seek(0) or some such "rewind" ability.  A 
slightly ugly alternative would be just opening/closing the 
RawData file for each pass through the loop.  Another, possibly 
cleaner option (depending on the size of RawData's contents) 
would be to just read the whole thing into an in-memory list with 
something like

data = RawData.readlines()

and then just pass "data" to PullHourlyData() each time...no need 
to rewind (like VHS vs. DVD :)

Part of the confusion stems from the fact that what you refer to 
as "filename" (sounds like it should be a string containing the 
path to the file) is actually a file object that contains state.

-tkc




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


Re: python skipping lines?

2006-11-27 Thread lisa . engblom
Thanks, everyone for replying so promptly.  I got it to work the way I
intended, and have some ideas for how to make it much cleaner.

- Lisa

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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread Carsten Haese
On Mon, 2006-11-27 at 19:14 +, OKB (not okblacke) wrote:
> Duncan Booth wrote:
> 
> >> And is there a mechanism in Python that will allow me to override
> >> the operators of a class, for all its occurrences, even the ones
> >> implemented on C built-in objects? 
> > 
> > No.
> 
>   For what it's worth, which is undoubtedly nothing,

Correct.

>  this is 
> something that I think needs to change.  All this talk about new-style 
> classes and class-type unification is empty words if you can't override 
> anything on any type without having to know whether it's written in C or 
> Python.

Duncan's "No" response was not referring to overriding in general, it
was referring to the OP's original question which amounted to "Can I
affect the behavior of method Z by overriding methods X and Y".

The inability to influence a method by overriding completely different
methods has nothing to do with whether that method is implemented in C
or Python; it has to with whether the method in question calls the
overridden methods, and in general it won't.

You can change the behavior of a list's sort method by overriding sort.
You can't change the behavior of sort by overriding __getitem__ and
__setitem__, because sort does not call __getitem__ or __setitem__.

Hope this helps,

Carsten.


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


Re: case insensitive dictionary

2006-11-27 Thread J. Clifford Dyer
John Henry wrote:
>print pets.keys()
> 
> should print:
> 
> "Cat", "Dog"

If you do:

Py> pets['Cat'] = 2
Py> pets['Dog'] = 3
Py> pets['DOG'] = 4
Py> pets['cat'] += 5
Py> pets.keys()

What should the result be?

"['Cat', 'Dog']" or "['cat', 'DOG']"?


That is to say, if you use a new case in redefining the values of your
case insensitive dictionary, does the key take on the new case, or will
it always and forever be the case originally given to it?

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


pyxpcom

2006-11-27 Thread hg
Hi,

Can one tell me what the status of this project is ?. I did google ...
but not much out there.

Regards,

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


Re: can't get cgi values

2006-11-27 Thread ronrsr
Thank you, all.  that was very helpful, and did solve many of my
problems.  I was addressing the dict with () rather than [].

I'm still having one problem, though -- extracting the keywords. NOw,
if you check the value for Form below, you'll see there is more than
one keyword entry.  When I do:  keywords = form["keywords"] - what sort
of data structure do I get back?

th anks  so much again.

-rsr-


if form.has_key("keywords"):
 keywords = str(form["keywords"].value)
 else:
  keywords = "k"
 fileHandle.write("here comes keywords:")
 fileHandle.write(str(keywords))

 fileHandle.write("keyword info");
 fileHandle.write(str(form.has_key("keywords")))
 fileHandle.flush()

> here's the info I know:
>
> form = FieldStorage(None, None, [MiniFieldStorage('zid', '17'),
> MiniFieldStorage('keywords', 'aAUA'), MiniFieldStorage('keywords',
> 'aBOS'), MiniFieldStorage('citation', 'The Earth Times Monthly,
> April 2002\\r\\n   \\r\\n   \r\n   '),
> MiniFieldStorage('quotation', 'Farm support goes mainly to a relatively
> small number of agri-businesses, many of them large corps. Yet these
> subsidies are 6 times what rich countries provide in foreign aid to a
> developing world that includes 5 billion people.\\r\\n   \r\n
> '), MiniFieldStorage('updatebutton', 'Update')])
> form.has_key("citation") = True
> 
>

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


Re: Passing com object from simple xmlrpc server to client

2006-11-27 Thread Diez B. Roggisch
tsjuan schrieb:
> Hello python users,
> 
> I am just learning on how to use xmlrpc and stumbled upon how to pass
> com object
> from server to client side.
> 
> The client side complain about can't marshall the com object. I don't
> know what type
> of marshall command I should use to pass the object.

you can't do that. COM is a interprocess-communication facility that 
doesn't have a value - which is what marshalling tries to accomplish: 
create a wire-representation of a value.

If you are using COM anyway, why don't you use DCOM instead of XMLRPC - 
then things could work.

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


Re: can't get cgi values

2006-11-27 Thread ronrsr
Thank you, all.  that was very helpful, and did solve many of my
problems.  I was addressing the dict with () rather than [].

I'm still having one problem, though -- extracting the keywords. NOw,
if you check the value for Form below, you'll see there is more than
one keyword entry.  When I do:  keywords = form["keywords"] - what sort
of data structure do I get back?

th anks  so much again.

-rsr-


if form.has_key("keywords"):
 keywords = str(form["keywords"].value)
 else:
  keywords = "k"
 fileHandle.write("here comes keywords:")
 fileHandle.write(str(keywords))

 fileHandle.write("keyword info");
 fileHandle.write(str(form.has_key("keywords")))
 fileHandle.flush()

> here's the info I know:
>
> form = FieldStorage(None, None, [MiniFieldStorage('zid', '17'),
> MiniFieldStorage('keywords', 'aAUA'), MiniFieldStorage('keywords',
> 'aBOS'), MiniFieldStorage('citation', 'The Earth Times Monthly,
> April 2002\\r\\n   \\r\\n   \r\n   '),
> MiniFieldStorage('quotation', 'Farm support goes mainly to a relatively
> small number of agri-businesses, many of them large corps. Yet these
> subsidies are 6 times what rich countries provide in foreign aid to a
> developing world that includes 5 billion people.\\r\\n   \r\n
> '), MiniFieldStorage('updatebutton', 'Update')])
> form.has_key("citation") = True
> 
>

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


Re: Generating header information using ElementTree

2006-11-27 Thread metaperl
And dont forget that you can use triple quotes to get rid of all the
quote-escaping you are using:

$ python
>>> """
... 
... ho
... 
... """
'\n\nho\n\n'
>>>


Craig wrote:
> John Machin wrote:
>
> > Craig wrote:
> >
> > > Great.  Got that sorted.  The problem I have now is that some of the
> > > XML data is not copied across to the file when I have the text
> > > information included.  The number of characters that is lost is equal
> > > to the number of characters that is in the block of text I entered
> > > before.  The code I am using is:
> > >
> > > def WriteXMLRecord ( record, XMLFileBaseName, root):
> > > RecordName = SubElement(root, "Log")
> > > #iterate through all the fields in the record
> > > for key in record:
> > > # write the key and its data
> > > test = SubElement(RecordName, key)
> > > test.text = str(record[key])
> > > tree = ElementTree(root)
> > > tree.write(XMLFileBaseName)
> >
> > I'm guessing, based on reading the docs for the write method, that you
> > should be using the file handle, rather than the file name, if the file
> > is already opened. So (1) change the name of the 2nd arg to
> > XMLFileHandle or somesuch, and in the caller, use outFile (the handle)
> > instead of "record.xml".
> >
> > >
> > > def main():
> > > outFile = open("record.xml", 'w')
> > > outFile.write("""
> > > 
> > > \n\n""")
> > >
> > > root = Element("Log")
> > > WriteXMLRecord(data1, "record.xml", root)
> > > WriteXMLRecord(data2, "record.xml", root)
> > > WriteXMLRecord(data3, "record.xml", root)
> > > outFile.close()
> > >
> > HTH,
> > John
> 
> Great.  Got it.  Thanks so much for all your help.
> 
> 
> Craig

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


Re: can't get cgi values

2006-11-27 Thread robert
ronrsr wrote:
> Thank you, all.  that was very helpful, and did solve many of my
> problems.  I was addressing the dict with () rather than [].
> 
> I'm still having one problem, though -- extracting the keywords. NOw,
> if you check the value for Form below, you'll see there is more than
> one keyword entry.  When I do:  keywords = form["keywords"] - what sort
> of data structure do I get back?


there is another func to get multiple values - see the docs.
Basically, one can iterate all over form.list (which is not documented) to get 
the original order of all the fields.

Robert


> th anks  so much again.
> 
> -rsr-
> 
> 
> if form.has_key("keywords"):
>  keywords = str(form["keywords"].value)
>  else:
>   keywords = "k"
>  fileHandle.write("here comes keywords:")
>  fileHandle.write(str(keywords))
> 
>  fileHandle.write("keyword info");
>  fileHandle.write(str(form.has_key("keywords")))
>  fileHandle.flush()
> 
>> here's the info I know:
>>
>> form = FieldStorage(None, None, [MiniFieldStorage('zid', '17'),
>> MiniFieldStorage('keywords', 'aAUA'), MiniFieldStorage('keywords',
>> 'aBOS'), MiniFieldStorage('citation', 'The Earth Times Monthly,
>> April 2002\\r\\n   \\r\\n   \r\n   '),
>> MiniFieldStorage('quotation', 'Farm support goes mainly to a relatively
>> small number of agri-businesses, many of them large corps. Yet these
>> subsidies are 6 times what rich countries provide in foreign aid to a
>> developing world that includes 5 billion people.\\r\\n   \r\n
>> '), MiniFieldStorage('updatebutton', 'Update')])
>> form.has_key("citation") = True
>>
>>
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Several entries on Tile and TableList at the Tkinter wiki

2006-11-27 Thread Gheorghe Postelnicu
Hi,

Thanks for pointing out this resource. I have indeed used Tkinter in a
couple of applications, but I knew nothing about this wiki. This is
very helpful.

Thanks,
-- 
Gheorghe Postelnicu, PhD
MGH, Harvard Medical School
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super() and type()

2006-11-27 Thread Carl Banks
Chris Mellon wrote:
> I see super documented, and in use, as below (from the Python documentation)
>
> class C(B):
> def meth(self, arg):
> super(C, self).meth(arg)
>
> I'd like to not write C all the time, so is there any problem with writing:
>
> class C(B):
> def meth(self, arg):
> super(type(self), self).meth(arg)
>
>
> This seems to work in practice but I don't see it used anywhere and
> I'm worried what I might be missing.
>
> This was especially brought to my attention because pylint flags the
> second usage as invalid, and I'm not sure if it should be considered a
> false positive or not.

PyLint is right.  Try running this:


class A(object):
def meth(self,arg):
print "hello"

class B(A):
def meth(self,arg):
super(type(self), self).meth(arg)

class C(B):
 def meth(self,arg):
super(type(self), self).meth(arg)

print C().meth(1)


The reason this type(self) returns the type of the object (which
doesn't change), NOT the type of the class it was defined in.  That is,
type(self) returns C even in the function B.meth.  Since C's superclass
is B, B.meth ends up calling B.meth again, and you get infinite
recursion.

Unfortunately, short of hackery, you're stuck with having to write out
super(C,self).


Carl Banks

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


Re: super() and type()

2006-11-27 Thread Rob Williscroft
Chris Mellon wrote in
news:[EMAIL PROTECTED] in
comp.lang.python: 

> I see super documented, and in use, as below (from the Python
> documentation) 
> 
> class C(B):
> def meth(self, arg):
> super(C, self).meth(arg)
> 
> I'd like to not write C all the time, so is there any problem with
> writing: 
> 
> class C(B):
> def meth(self, arg):
> super(type(self), self).meth(arg)
> 
> 
> This seems to work in practice but I don't see it used anywhere and
> I'm worried what I might be missing.

Have you considered what happens if somebody writes:

class D(C):
  def meth(self, arg):
super( D, self ).meth( arg )

> 
> This was especially brought to my attention because pylint flags the
> second usage as invalid, and I'm not sure if it should be considered a
> false positive or not.

Nope, the type argument to super tells it where you are in the 
type hierarchy, type(self) is always the top of the hierarchy.

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


Re: Python-list Digest, Vol 38, Issue 390

2006-11-27 Thread Edwin Gomez
Regarding Topic number 3: 3. Calling a thread asynchronously with a callback 
(Edwin Gomez):
Thanks Bjorn for you quick answer and by the way, that works.  Diez, in answer 
to your question regarding async callbacks in C#; C# runs in a multi threaded 
apartments.  Many times we'll setup listener objects in a dictionary and each 
member is responsible for monitoring and manipulating it's own data.  In the 
case where data is shared, then of course, we use a locking machanism.
> - Original Message -
> From: [EMAIL PROTECTED]
> To: python-list@python.org
> Subject: Python-list Digest, Vol 38, Issue 390
> Date: Mon, 27 Nov 2006 19:45:03 +0100
> 
> 
> Send Python-list mailing list submissions to
>   python-list@python.org
> 
> To subscribe or unsubscribe via the World Wide Web, visit
>   http://mail.python.org/mailman/listinfo/python-list
> or, via email, send a message with subject or body 'help' to
>   [EMAIL PROTECTED]
> 
> You can reach the person managing the list at
>   [EMAIL PROTECTED]
> 
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Python-list digest..."
> 
> Today's Topics:
> 
> 1. Re: Several entries on Tile and TableList at the Tkinter wiki
>(jim-on-linux)
> 2. shtoom complicated install (Croteam)
> 3. Calling a thread asynchronously with a callback (Edwin Gomez)
> 4. Re: Active State and Komodo... (Trent Mick)
> 5. Re: working with files and directories (halex2000)
> 6. Re: Calling a thread asynchronously with a callback
>(Diez B. Roggisch)
> 7. Re: Calling a thread asynchronously with a callback
>(Bjoern Schliessmann)
> 8. python skipping lines? ([EMAIL PROTECTED])
> 9. can't get cgi values (ronrsr)
>10. Re: can't get cgi values (Fredrik Lundh)
>11. Re: can't get cgi values (Paul McGuire)
> 
> From: jim-on-linux <[EMAIL PROTECTED]>
> To: python-list@python.org
> Cc: Kevin Walzer <[EMAIL PROTECTED]>
> Subject: Re: Several entries on Tile and TableList at the Tkinter wiki
> Date: Mon, 27 Nov 2006 12:29:58 -0500
> 
> 
> Thanks for posting this entry,
> 
> The fact that a wiki or help site doesn't get a
> lot of traffic is not an necessarily an indicator
> of it's usfulness.  It indicates to me that the
> product, in this case Tkinter, may be easy to use
> and understand, after working with it a little, A
> lot of help may not be necessary.
> 
> A good example is the py2exe help site.
> At one time not to long ago there might be 8 to 12
> post per day, or more. Today by my unscientific
> count method, I don't think there are more than 3
> to 4 post per week.  Yet, py2exe and Tkinter is
> almost as valuable as Python. If we couldn't
> build programs for Windows, where would a python
> programmes's money come from?
> 
> Thanks again,
> 
> jim-on-linux
> http://www.inqvista.com
> 
> 
> 
> On Sunday 26 November 2006 15:50, Kevin Walzer
> wrote:
> > I'm not sure how often members of this list
> > visit the Tkinter wiki at
> > http://tkinter.unpythonic.net/wiki/FrontPage; this wiki seems to 
> > have less traffic in general
> > than the Tcl/Tk wiki at http://wiki.tcl.tk.
> > Given that, I hope it's not out of line for me
> > to call attention to several pages that I've
> > posted about integrating Tile
> > (http://tktable.sourceforge.net/tile) and
> > TableList (http://www.nemethi.de,
> > http://wiki.tcl.tk/5527) into Tkinter
> > applications. I've noted a serious lack of
> > resources/documentation about these two
> > powerful Tk components. In addition to some
> > documentation, screenshots, and sample
> > applications, I've posted updated versions of
> > the original TableList and Tile wrappers by
> > Martin Franklin.
> >
> > I should take this moment to thank Mr. Franklin
> > for his work on these wrappers; whatever I
> > added to them was pretty minimal compared to
> > the heavy lifting he did. He originally posted
> > them on the Internet last year, but the site
> > that hosted them has gone dark. Anyway, Mr.
> > Franklin, if you are reading this, thank you
> > for your hard work; it has been enormously
> > helpful. I hope my own efforts extend your work
> > and make it even more useful for other Tkinter
> > developers.
> >
> > Here are the links:
> >
> > http://tkinter.unpythonic.net/wiki/UsingTile
> > http://tkinter.unpythonic.net/wiki/TileWrapper
> > http://tkinter.unpythonic.net/wiki/TableListWra
> > pper
> > http://tkinter.unpythonic.net/wiki/TableListTil
> > eWrapper
> > http://tkinter.unpythonic.net/wiki/PyLocateTile
> > http://tkinter.unpythonic.net/wiki/PyLocate
> >
> > Hope these prove useful to others, as starting
> > points for your own work if nothing else.
> > Corrections and improvements are of course
> > invited; it's a wiki!
> >
> >
> > --
> > Kevin Walzer
> > Code by Kevin
> > http://www.codebykevin.com
> 
> From: Croteam <[EMAIL PROTECTED]>
> To: python-list@python.org
> Subject: shtoom complicated install
> Date: 27 Nov 2006 09:35:55 -0800
> 

Re: case insensitive dictionary

2006-11-27 Thread Fuzzyman

John Henry wrote:
> I believe the standard dictionary should be amened to allow the use of
> case insensitive keys - as an option.  I found some work done by others
> to do that at:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/283455
>
> but the problem with that approach is that they lowercase the keys
> immediately when you create the dictionary and so the true identity of
> the key is lost.

A later version of this class does give you access to the original case
:

http://www.voidspace.org.uk/python/archive.shtml#caseless

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


Re: case insensitive dictionary

2006-11-27 Thread John Henry
I believe that if you redefine the value, the key should not change.
So, yes, I would expect that they value of the key to remain as they
were.


J. Clifford Dyer wrote:
> John Henry wrote:
> >print pets.keys()
> >
> > should print:
> >
> > "Cat", "Dog"
>
> If you do:
>
> Py> pets['Cat'] = 2
> Py> pets['Dog'] = 3
> Py> pets['DOG'] = 4
> Py> pets['cat'] += 5
> Py> pets.keys()
>
> What should the result be?
>
> "['Cat', 'Dog']" or "['cat', 'DOG']"?
>
>
> That is to say, if you use a new case in redefining the values of your
> case insensitive dictionary, does the key take on the new case, or will
> it always and forever be the case originally given to it?
> 
> Cheers,
> Cliff

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


Re: How good is CORBA?

2006-11-27 Thread Ravi Teja
On Nov 21, 11:20 am, "Sai Krishna M" <[EMAIL PROTECTED]> wrote:
> there are certainly client/server interactions.

But are they cross-language interactions?

This is how I would choose to distribute code.
Same machine, all in Python - organize in modules in Python path.
Different machines, all in Python - Pyro
Different machines, different languages, stateless calls, simple use -
XMLRPC/ReST
Different machines, different languages, stateless calls, more complex
requirements - SOAP
Different machines, different languages, statelful, typed - CORBA
(omniORB is the best bet at Python end)

ICE
A lot of the CORBA folks have been mad with ICE because it is subtly
discrediting CORBA while not being a standard. It is cleaner, comes
with good documentation, supports more languages than any single ORB
(however you are stuck with only those languages that ZeroC implements
support for). For simple apps, I would stick with omniORBPy. It is not
any more complicated than ICE. While ICE is simpler on the whole, you
will likely use only a fraction of the CORBA/ICE feature set. So the
difference won't necessarily show.

I like my tools to be simple. Lately, I have been happily using JSON
over HTTP.

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


Re: bz2.readline() slow ?

2006-11-27 Thread Jack Diederich
On Fri, Nov 24, 2006 at 10:11:06AM +, Soeren Sonnenburg wrote:
> Dear all,
> 
> I am a bit puzzled, as
> 
> -snip-
> import bz2
> f=bz2.BZ2File('data/data.bz2');
> 
> while f.readline():
> pass
> -snip-
> 
> takes twice the time (10 seconds) to read/decode a bz2 file
> compared to
> 
> -snip-
> import bz2
> f=bz2.BZ2File('data/data.bz2');
> x=f.readlines()
> -snip-
> 
> (5 seconds). This is even more strange as the help(bz2) says:
> 
>  |  readlines(...)
>  |  readlines([size]) -> list
>  |  
>  |  Call readline() repeatedly and return a list of lines read.
>  |  The optional size argument, if given, is an approximate bound on 
> the
>  |  total number of bytes in the lines returned.
> 
> This happens on python2.3 - python2.5 and it does not help to specify a
> maximum line size.
> 
> Any ideas ?

The bz2 module is implemented in C so calling "f.readline()" repeatedly
has extra Python => C call overhead that "f.readlines()" doesn't have
because it stays in a tight C loop the whole time.

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


Re: Calling a thread asynchronously with a callback

2006-11-27 Thread Fuzzyman

Diez B. Roggisch wrote:
> Edwin Gomez wrote:
>
> > I'm a C# developer and I'm new to Python.  I would like to know if the
> > concept of Asynchronous call-backs exists in Python.  Basically what I
> > mean is that I dispatch a thread and when the thread completes it invokes
> > a method from the calling thread.  Sort event driven concept with threads.
>
> Counter question: does such a thing exist in C#, and if, is it bound to some
> existing event loop?
>
> I'm really curious, because having code being interrupted at any time by a
> asynchronous callback strikes me as dangerous. But then maybe I'm just a
> whimp :)
>

I've used them with Windows Forms,. The callback puts a message in the
event loop. It doesn't actually interrupt the code.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Diez

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


Re: windows background process

2006-11-27 Thread Podi

Gabriel Genellina wrote:
> os.spawnl(os.P_NOWAIT, 'mycmd.exe', 'mycmd.exe', 'first_arg', 'second_arg')
> That is, you must provide explicitely the value for argv[0] (executable)
> Remember to quote appropiately any parameter with embedded spaces
> (including the executable). On Python 2.5 you could use 
> subprocess.list2cmdline
>
Right, this works. Before, I didn't realize that the full path goes to
the 2nd and 3rd argument of spawnl.

Thanks for the help.
P

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


Can you fix up wrapper function argument signatures?

2006-11-27 Thread Gerard Brunick
Consider:

 >>> def negate(func):
... def wrapper(*args, **kwargs):
... return not func(*args, **kwargs)
... return wrapper
...
 >>> def f(x):
... return x > 10
...
 >>> g = negate(f)
 >>> g(20)
False
 >>> g(5)
True

Now g has the argument signature of (*args, **kwargs).  Pop-up help in 
Python
Scripter(which is great by the way) tells me this, as does

 >>> g.func_code.co_varnames
('args', 'kwargs')

Is there anyway to fix this in negate?  I assume that I can't just start
changing things in g.func_code since the bytecodes depend on the order
of variables and lots of other stuff that I don't claim to understand.

Please note: From the new functools module, I see that one can set/update
__module__, __name__, __doc__, and __dict__ using the corresponding 
attributes
from the wrapped function; however, none these fix up the argument signature
do they?  (I'm still running 2.4, so I haven't tried it.)

Thanks,
Gerard

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


Re: Can you fix up wrapper function argument signatures?

2006-11-27 Thread Diez B. Roggisch
Gerard Brunick schrieb:
> Consider:
> 
>  >>> def negate(func):
> ... def wrapper(*args, **kwargs):
> ... return not func(*args, **kwargs)
> ... return wrapper
> ...
>  >>> def f(x):
> ... return x > 10
> ...
>  >>> g = negate(f)
>  >>> g(20)
> False
>  >>> g(5)
> True
> 
> Now g has the argument signature of (*args, **kwargs).  Pop-up help in 
> Python
> Scripter(which is great by the way) tells me this, as does
> 
>  >>> g.func_code.co_varnames
> ('args', 'kwargs')
> 
> Is there anyway to fix this in negate?  I assume that I can't just start
> changing things in g.func_code since the bytecodes depend on the order
> of variables and lots of other stuff that I don't claim to understand.
> 
> Please note: From the new functools module, I see that one can set/update
> __module__, __name__, __doc__, and __dict__ using the corresponding 
> attributes
> from the wrapped function; however, none these fix up the argument 
> signature
> do they?  (I'm still running 2.4, so I haven't tried it.)

You can use Michele Simionato's decorator-module.

http://www.phyast.pitt.edu/~micheles/python/documentation.html

HTH,

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


Re: The Python Papers Edition One

2006-11-27 Thread [EMAIL PROTECTED]

Alan J. Salmoni wrote:
> I heartily agree. pdf format has never been much of a problem for me.
> Now that you have an ISSN, has it been submitted to Google Scholar or
> other academic indexes?
>
> http://scholar.google.com/intl/en/scholar/about.html for Google Scholar
> http://citeseer.ist.psu.edu/submitDocument.html for Citeseer
>
> These are two I can think of but there must be more. Any suggestions?
>
> I think that this is great work guys - I'll see if I can take some time
> to submit some of the code I developed a few years ago.
>
> All the best!
>
> Alan

We haven't hit Google Scholar yet, but we are publishing to other
online archives.

I'm in the middle of finding a semi-permanent location with a good URL
for keeping archives, and once that is done, we can get them indexed in
Google Search and Google Scholar.

Unfortunately, the domain name is currently a redirect which prevents
the indexing from working properly. We need a better home, but we are
working on it. We should have this by the next edition.

Thanks for the props.

Cheers,
-T
(Editor-In-Chief)

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


"fork and exit" needed?

2006-11-27 Thread Vincent Delporte
Hi

I'm a Python newbie, and would like to rewrite this Perl scrip
to be run with the Asterisk PBX:

http://www.voip-info.org/wiki/view/Asterisk+NetCID

Anyone knows if those lines are necessary, why, and what their
alternative is in Python?

---
open STDOUT, '>/dev/null'; 
fork and exit;
---

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


Re: About alternatives to Matlab

2006-11-27 Thread sturlamolden

Rob Purser wrote:

> Anyway, I just wanted to call your attention to Data Acquisition Toolbox:
> http://www.mathworks.com/products/daq/

Absolutely. If the hardware is supported by this toolbox, there is no
need to reinvent the wheel. The license is expensive, but development
time can be far more expensive. Matlab is an excellent tool for
numerical work.

However, Matlab is only single-threaded and does not optimize its
pass-by-value semantics with proper 'escape analysis'. (Yes, Matlab
does lazy copy-on-write to optimize function calls, but functions have
return values as well.)  I have (temporarily?) stopped using Matlab
because I constantly got annoyed by the limitations of the language. I
still use Matlab as an advanced desktop calculator though. Somehow I
find it easier to type in an expression in Matlab than NumPy, probably
because I am more accustomed to the syntax.

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


Python script and C++

2006-11-27 Thread Thuan Seah Tan
Hi all,

I am new to python  and currently I am working on a traffic simulation 
which I plan to define the various agents using scripting. It's kind of like 
scripting for non-playable character in games. I am thinking of using python 
for this but I am concerned with running time. Is scripting a lot slower 
compared to direct implementation in C++? Does compiling the script help in 
any way? Also, can anyone recommend me a book that covers python in general 
as well as C++ binding? Thanks.


Thuan Seah Tan 


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


Re: "fork and exit" needed?

2006-11-27 Thread [EMAIL PROTECTED]
Vincent Delporte wrote:
> Hi
>
>   I'm a Python newbie, and would like to rewrite this Perl scrip
> to be run with the Asterisk PBX:
>
> http://www.voip-info.org/wiki/view/Asterisk+NetCID
>
> Anyone knows if those lines are necessary, why, and what their
> alternative is in Python?

> open STDOUT, '>/dev/null';

Either redefine stdout to an open file object for /dev/null or run the
script as "script.py >/dev/null"

> fork and exit;
something like:

if os.fork():
   sys.exit(0)

Tells the parent to exit after the fork while the child keeps running.
These are both steps in becoming a daemon (the comp.unix.programmer
FAQ, while skewed toward C, explains why some of these steps are
needed).

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


Re: Python script and C++

2006-11-27 Thread nepBabu.cx
Thuan Seah Tan wrote:
> Hi all,
> 
> I am new to python  and currently I am working on a traffic simulation 
> which I plan to define the various agents using scripting. It's kind of like 
> scripting for non-playable character in games. I am thinking of using python 
> for this but I am concerned with running time. Is scripting a lot slower 
> compared to direct implementation in C++? Does compiling the script help in 

"Learning Python" is a good book to start learning Python. I don't think
you'll be better off in C++. If speed is of utmost importance for the
whole implementation, then I suggest C++ but well coded Python runs
atleast/near to C++ implementation. Otherwise, you can atleast code the
speed-savvy part of the implementation in C++. Ofcourse, Python object
model is based on a virtual machine (called PVM) which accounts for
slower start-up due to native function call conversion but you'll find
that learning curve is only a tiny fraction compared to C++.  And you'll
surely love Python. =)

> any way? Also, can anyone recommend me a book that covers python in general 
> as well as C++ binding? Thanks.

"Progamming in Python" is another excellent book that might be of help.
If you are developing on windows machine then
http://aspn.activestate.com/ASPN/Python has some helpful recipes.

C++ bindings in Python are handled by extending python objects and
manipulating it from C++ codes using the Python headers.

Also, http://python.org/docs should be a good reference.
Also Google for "vaults of parnassus" and Fredrik lundh's guide on Python.

Goodluck!


-- 
thanks,
nepBabu.cx
  c c
 .-.,;(")
.'`~C.-.c =W=

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


Re: urllib2 spinning CPU on read

2006-11-27 Thread John J. Lee
"kdotsky" <[EMAIL PROTECTED]> writes:

> Hello All,
> I've ran into this problem on several sites where urllib2 will hang
> (using all the CPU) trying to read a page.  I was able to reproduce it
> for one particular site.  I'm using python 2.4
> 
> import urllib2
> url = 'http://www.wautomas.info'
[...]
> Also, where should I go to see if something like this has already been
> reported as a bug?

I didn't try looking at your example, but I think it's likely a bug
both in that site's HTTP server and in httplib.  If it's the same one
I saw, it's already reported, but nobody fixed it yet.

http://python.org/sf/1411097


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


MIME encoding change in Python 2.4.3 (or 2.4.2? 2.4.1?) - problem and solution

2006-11-27 Thread Nobody
I have an application that processes MIME messages. It reads a message from a 
file,
looks for a text/html and text/plain parts in it, performs some processing on 
these
parts, and outputs the new message.

Ever since I recently upgraded my Python to 2.4.3, the output messages started 
to
come out garbled, as a block of junk characters.

I traced the problem back to a few lines that were removed from the email 
package:
The new Python no longer encodes the payload when converting the MIME message 
to a
string.

Since my program must work on several computers, each having a different 
version of
Python, I had to find a way to make it work correctly no matter if 
msg.as_string()
encodes the payload or not.

Here is a piece of code that demonstrates how to work around this problem:

.. code start 
import email
import email.MIMEText
import email.Charset

def do_some_processing(s):
"""Return the input text or HTML string after processing it in some way."""
# For the sake of this example, we only do some trivial processing.
return s.replace('foo','bar')

msg = email.message_from_string(file('input_mime_msg','r').read())
utf8 = email.Charset.Charset('UTF-8')
for part in msg.walk():
if part.is_multipart():
continue
if part.get_content_type() in ('text/plain','text/html'):
s = part.get_payload(None, True) # True means decode the payload, which 
is normally base64-encoded.
# s is now a sting containing just the text or html of the part, not 
encoded in any way.

s = do_some_processing(s)

# Starting with Python 2.4.3 or so, msg.as_string() no longer encodes 
the payload
# according to the charset, so we have to do it ourselves here.
# The trick is to create a message-part with 'x' as payload and see if 
it got
# encoded or not.
should_encode = (email.MIMEText.MIMEText('x', 'html', 
'UTF-8').get_payload() != 'x')
if should_encode:
s = utf8.body_encode(s)

part.set_payload(s, utf8)
# The next two lines may be necessary if the original input message 
uses a different encoding
# encoding than the one used in the email package. In that case we have 
to replace the
# Content-Transfer-Encoding header to indicate the new encoding.
del part['Content-Transfer-Encoding']
part['Content-Transfer-Encoding'] = utf8.get_body_encoding()

file('output_mime_msg','w').write(msg.as_string())
.. code end 

Hope this helps someone out there.
(Permission is hereby granted for anybody to use this piece of code for any 
purpose whatsoever)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python script and C++

2006-11-27 Thread George Sakkis
Thuan Seah Tan wrote:
> Hi all,
>
> I am new to python  and currently I am working on a traffic simulation
> which I plan to define the various agents using scripting. It's kind of like
> scripting for non-playable character in games. I am thinking of using python
> for this but I am concerned with running time. Is scripting a lot slower
> compared to direct implementation in C++? Does compiling the script help in
> any way? Also, can anyone recommend me a book that covers python in general
> as well as C++ binding? Thanks.

Even if pure python turns out to be slow for some critical parts of
your application, there are quite a few ways to deal with it: psyco,
pyrex, weave/blitz, ctypes, SWIG, Boost-python, SIP, CXX, SCXX,
hand-written C extensions and perhaps more. Visit
http://www.scipy.org/PerformancePython for an example of taking a
simple pure Python function and boosting it using several different
tools. Check out the final comparison table first; the pyrex version is
less than half a second slower than the C++.

George

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


Re: combining the path and fileinput modules SOLVED

2006-11-27 Thread Gabriel Genellina

At Sunday 26/11/2006 01:29, wo_shi_big_stomach wrote:


for line in fileinput.input(g, inplace=1, backup='.bak'):
# just print 2nd and subsequent lines
if not fileinput.isfirstline():
print line.rstrip('\n')
# check first line only
elif fileinput.isfirstline():
if not re.search('^From ',line):
print line.rstrip('\n')


Just a note: the elif is redundant, use a simple else clause.


--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Floating Exception

2006-11-27 Thread Jeremy
Hi,

I just changed some previously-working Python program to add a C++ 
extension.

Now, when I call __init__() in a Python class I did not change and with the 
same arguments passed, I get the screen message 'Floating exception' and the 
program seems to stop. The exact point of the crash in __init__() seems to 
depend on from which directory I run the Python program.

What is wrong? And what is a floating exception?

Thanks,
Jeremy 


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


Re: NFS server

2006-11-27 Thread Stuart D. Gathman
On Fri, 24 Nov 2006 05:00:53 -0800, srj wrote:

> i wish to develop an NFS server usin python from scratch( some wise guy
> told me i'ts easy!).
> can i get any kinda tutorial for this??
> 
> any suggestions on how 2 begin?

NFS is an RPC based protocol.  The first step is to be able to do
SunRCP/ONCRPC. Python has an 'xdrlib' which is how parameters are
marshalled, unmarshalled in sunrpc.  If allowed under "from scratch", you
could wrap the C rpc lib for python - they handle retries and other low
level stuff.  You could look "Remote Tea" for Java, and translate to
python to get a pure python oncrpc lib.  Or you could look for such a
package already written (a quick search didn't reveal any).

Once you have rpc, then it is "just" a matter of having your python server
implement the set of calls specified for NFS.  BTW, apparently python was
used for quickly building test rigs while developing NFS v4.

Having a framework for python NFS server could be useful - think custom
filesystem.  Although a python binding for fuse + C NFS server would
be more general (use locally as well as remotely).

-- 
  Stuart D. Gathman <[EMAIL PROTECTED]>
Business Management Systems Inc.  Phone: 703 591-0911 Fax: 703 591-6154
"Confutatis maledictis, flamis acribus addictis" - background song for
a Microsoft sponsored "Where do you want to go from here?" commercial.

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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread OKB (not okblacke)
Carsten Haese wrote:

> You can change the behavior of a list's sort method by overriding
> sort. You can't change the behavior of sort by overriding
> __getitem__ and __setitem__, because sort does not call __getitem__
> or __setitem__. 

Why doesn't it?

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: super() and type()

2006-11-27 Thread Delaney
Carl Banks wrote:

> Unfortunately, short of hackery, you're stuck with having to write out
> super(C,self).

For my version of that particular hackery ...
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286195

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


Re: About alternatives to Matlab

2006-11-27 Thread Niels L Ellegaard
Filip Wasilewski wrote:
> As far as the speed comparison is concerned I totally agree that NumPy
> can easily outperform Matlab in most cases. Of course one can use
> compiled low-level extensions to speed up specific computations in
> Matlab, but it's a lot easier and/or cheaper to find very good tools
> for Python.

These benchmarks are interesting. Perhaps someone could elaborate: When
is python faster than Matlab and when is it slower? As far as I
understand, recent versions of Matlab include a jit, but cpython does
not (unless you use psyco). Can python do faster do-loops than matlab?
Does the matrix backend of python perform faster than a the matrix
backend of Matlab? What is going on?

Thanks in advance

  Niels

BTW: I feel obliged to provide a small link to your upcoming wavelet
code for scipy. It looks promising:
http://wavelets.scipy.org/moin/

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


Re: Python script and C++

2006-11-27 Thread Ravi Teja
Thuan Seah Tan wrote:
> Hi all,
>
> I am new to python  and currently I am working on a traffic simulation
> which I plan to define the various agents using scripting. It's kind of like
> scripting for non-playable character in games. I am thinking of using python
> for this but I am concerned with running time. Is scripting a lot slower
> compared to direct implementation in C++? Does compiling the script help in
> any way?

Python is perfectly suitable for this use. Python was in use in video
games in this way when computers were a lot slower. I doubt that you
will need to bother compiling the script or see any observable
enhancement if you do.

One example I can remember is Kingdom Under Fire (2001).

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


splitting a long string into a list

2006-11-27 Thread ronrsr
I have a single long string - I'd like to split it into a list of
unique keywords. Sadly, the database wasn't designed to do this, so I
must do this in Python - I'm having some trouble using the .split()
function, it doesn't seem to do what I want it to - any ideas?

thanks very much for your help.

r-sr-


longstring = 'Agricultural subsidies; Foreign aidAgriculture;
Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
Childhood Development, Birth Defects; Toxic ChemicalsAntibiotics,
AnimalsAgricultural Subsidies, Global TradeAgricultural
SubsidiesBiodiversityCitizen ActivismCommunity
GardensCooperativesDietingAgriculture, CottonAgriculture, Global
TradePesticides, MonsantoAgriculture, SeedCoffee, HungerPollution,
Water, FeedlotsFood PricesAgriculture, WorkersAnimal Feed, Corn,
PesticidesAquacultureChemical
WarfareCompostDebtConsumerismFearPesticides, US, Childhood Development,
Birth DefectsCorporate Reform,  Personhood (Dem. Book)Corporate Reform,
 Personhood, Farming (Dem. Book)Crime Rates, Legislation,
EducationDebt, Credit CardsDemocracyPopulation, WorldIncomeDemocracy,
Corporate Personhood, Porter Township (Dem. Book)Disaster
ReliefDwellings, SlumsEconomics, MexicoEconomy, LocalEducation,
ProtestsEndangered Habitat, RainforestEndangered SpeciesEndangered
Species, Extinctionantibiotics, livestockAgricultural subsidies;
Foreign aid;Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals;Antibiotics, Animals;Agricultural Subsidies, Global
Trade;Agricultural Subsidies;Biodiversity;Citizen Activism;Community
Gardens;Cooperatives;Dieting;Agriculture, Cotton;Agriculture, Global
Trade;Pesticides, Monsanto;Agriculture, Seed;Coffee, Hunger;Pollution,
Water, Feedlots;Food Prices;Agriculture, Workers;Animal Feed, Corn,
Pesticides;Aquaculture;Chemical
Warfare;Compost;Debt;Consumerism;Fear;Pesticides, US, Childhood
Development, Birth Defects;Corporate Reform,  Personhood (Dem.
Book);Corporate Reform,  Personhood, Farming (Dem. Book);Crime Rates,
Legislation, Education;Debt, Credit Cards;Democracy;Population,
World;Income;Democracy, Corporate Personhood, Porter Township (Dem.
Book);Disaster Relief;Dwellings, Slums;Economics, Mexico;Economy,
Local;Education, Protests;Endangered Habitat, Rainforest;Endangered
Species;Endangered Species, Extinction;antibiotics,
livestock;Pesticides, Water;Environment, Environmentalist;Food, Hunger,
Agriculture, Aid, World, Development;Agriculture, Cotton
Trade;Agriculture, Cotton, Africa;Environment, Energy;Fair Trade (Dem.
Book);Farmland, Sprawl;Fast Food, Globalization, Mapping;depression,
mental illness, mood disorders;Economic Democracy, Corporate
Personhood;Brazil, citizen activism, hope, inspiration, labor
issues;citizen activism, advice, hope;Pharmaceuticals, Medicine,
Drugs;Community Investing;Environment, Consumer Waste Reduction,
Consumer Behavior and Taxes;Hunger, US, Poverty;FERTILITY,
Women;Agricultural subsidies; Foreign aid;Agriculture; Sustainable
Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood
Development, Birth Defects; Toxic Chemicals;Antibiotics,
Animals;Agricultural Subsidies, Global Trade;Agricultural
Subsidies;Biodiversity;Citizen Activism;Community
Gardens;Cooperatives;Dieting;Agricultural subsidies; Foreign
aid;Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals;Antibiotics, Animals;Agricultural Subsidies, Global
Trade;Agricultural Subsidies;Biodiversity;Citizen Activism;Community
Gardens;Cooperatives;Dieting;Agriculture, Cotton;Agriculture, Global
Trade;Pesticides, Monsanto;Agriculture, Seed;Coffee, Hunger;Pollution,
Water, Feedlots;Food Prices;Agriculture, Workers;Animal Feed, Corn,
Pesticides;Aquaculture;Chemical
Warfare;Compost;Debt;Consumerism;Fear;Pesticides, US, Childhood
Development, Birth Defects;Corporate Reform,  Personhood (Dem.
Book);Corporate Reform,  Personhood, Farming (Dem. Book);Crime Rates,
Legislation, Education;Debt, Credit Cards;'

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


splitting a long string into a list

2006-11-27 Thread ronrsr
I have a single long string - I'd like to split it into a list of
unique keywords. Sadly, the database wasn't designed to do this, so I
must do this in Python - I'm having some trouble using the .split()
function, it doesn't seem to do what I want it to - any ideas?

thanks very much for your help.

r-sr-


longstring = 'Agricultural subsidies; Foreign aidAgriculture;
Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
Childhood Development, Birth Defects; Toxic ChemicalsAntibiotics,
AnimalsAgricultural Subsidies, Global TradeAgricultural
SubsidiesBiodiversityCitizen ActivismCommunity
GardensCooperativesDietingAgriculture, CottonAgriculture, Global
TradePesticides, MonsantoAgriculture, SeedCoffee, HungerPollution,
Water, FeedlotsFood PricesAgriculture, WorkersAnimal Feed, Corn,
PesticidesAquacultureChemical
WarfareCompostDebtConsumerismFearPesticides, US, Childhood Development,
Birth DefectsCorporate Reform,  Personhood (Dem. Book)Corporate Reform,
 Personhood, Farming (Dem. Book)Crime Rates, Legislation,
EducationDebt, Credit CardsDemocracyPopulation, WorldIncomeDemocracy,
Corporate Personhood, Porter Township (Dem. Book)Disaster
ReliefDwellings, SlumsEconomics, MexicoEconomy, LocalEducation,
ProtestsEndangered Habitat, RainforestEndangered SpeciesEndangered
Species, Extinctionantibiotics, livestockAgricultural subsidies;
Foreign aid;Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals;Antibiotics, Animals;Agricultural Subsidies, Global
Trade;Agricultural Subsidies;Biodiversity;Citizen Activism;Community
Gardens;Cooperatives;Dieting;Agriculture, Cotton;Agriculture, Global
Trade;Pesticides, Monsanto;Agriculture, Seed;Coffee, Hunger;Pollution,
Water, Feedlots;Food Prices;Agriculture, Workers;Animal Feed, Corn,
Pesticides;Aquaculture;Chemical
Warfare;Compost;Debt;Consumerism;Fear;Pesticides, US, Childhood
Development, Birth Defects;Corporate Reform,  Personhood (Dem.
Book);Corporate Reform,  Personhood, Farming (Dem. Book);Crime Rates,
Legislation, Education;Debt, Credit Cards;Democracy;Population,
World;Income;Democracy, Corporate Personhood, Porter Township (Dem.
Book);Disaster Relief;Dwellings, Slums;Economics, Mexico;Economy,
Local;Education, Protests;Endangered Habitat, Rainforest;Endangered
Species;Endangered Species, Extinction;antibiotics,
livestock;Pesticides, Water;Environment, Environmentalist;Food, Hunger,
Agriculture, Aid, World, Development;Agriculture, Cotton
Trade;Agriculture, Cotton, Africa;Environment, Energy;Fair Trade (Dem.
Book);Farmland, Sprawl;Fast Food, Globalization, Mapping;depression,
mental illness, mood disorders;Economic Democracy, Corporate
Personhood;Brazil, citizen activism, hope, inspiration, labor
issues;citizen activism, advice, hope;Pharmaceuticals, Medicine,
Drugs;Community Investing;Environment, Consumer Waste Reduction,
Consumer Behavior and Taxes;Hunger, US, Poverty;FERTILITY,
Women;Agricultural subsidies; Foreign aid;Agriculture; Sustainable
Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood
Development, Birth Defects; Toxic Chemicals;Antibiotics,
Animals;Agricultural Subsidies, Global Trade;Agricultural
Subsidies;Biodiversity;Citizen Activism;Community
Gardens;Cooperatives;Dieting;Agricultural subsidies; Foreign
aid;Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals;Antibiotics, Animals;Agricultural Subsidies, Global
Trade;Agricultural Subsidies;Biodiversity;Citizen Activism;Community
Gardens;Cooperatives;Dieting;Agriculture, Cotton;Agriculture, Global
Trade;Pesticides, Monsanto;Agriculture, Seed;Coffee, Hunger;Pollution,
Water, Feedlots;Food Prices;Agriculture, Workers;Animal Feed, Corn,
Pesticides;Aquaculture;Chemical
Warfare;Compost;Debt;Consumerism;Fear;Pesticides, US, Childhood
Development, Birth Defects;Corporate Reform,  Personhood (Dem.
Book);Corporate Reform,  Personhood, Farming (Dem. Book);Crime Rates,
Legislation, Education;Debt, Credit Cards;'

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


Re: splitting a long string into a list

2006-11-27 Thread Cameron Walsh
ronrsr wrote:
> I have a single long string - I'd like to split it into a list of
> unique keywords. Sadly, the database wasn't designed to do this, so I
> must do this in Python - I'm having some trouble using the .split()
> function, it doesn't seem to do what I want it to - any ideas?
> 
> thanks very much for your help.
> 
> r-sr-
> 
> 
> longstring = ''

What do you want it to do?  Split on each semicolon?

a = longstring.split(";")
for element in a:
  print element

Agricultural subsidies
 Foreign aidAgriculture
Sustainable Agriculture - Support
 Organic Agriculture
 Pesticides, US,Childhood Development, Birth Defects
 Toxic ChemicalsAntibiotics,AnimalsAgricultural Subsidies, Global
TradeAgriculturalSubsidiesBiodiversityCitizen
ActivismCommunityGardensCooperativesDietingAgriculture,
CottonAgriculture, GlobalTradePesticides, MonsantoAgriculture,
SeedCoffee, HungerPollution,Water, FeedlotsFood PricesAgriculture,
WorkersAnimal Feed,
Corn,PesticidesAquacultureChemicalWarfareCompostDebtConsumerismFearPesticides,
US, Childhood Development,Birth DefectsCorporate Reform,  Personhood
(Dem. Book)Corporate Reform, Personhood, Farming (Dem. Book)Crime Rates,
Legislation,EducationDebt, Credit CardsDemocracyPopulation,
WorldIncomeDemocracy,Corporate Personhood, Porter Township (Dem.
Book)DisasterReliefDwellings, SlumsEconomics, MexicoEconomy,
LocalEducation,ProtestsEndangered Habitat, RainforestEndangered
SpeciesEndangeredSpecies, Extinctionantibiotics, livestockAgricultural
subsidies
Foreign aid
Agriculture
 Sustainable Agriculture - Support
 OrganicAgriculture
 Pesticides, US, Childhood Development, Birth Defects
Toxic Chemicals


I think the problem arises because your string has the following problems:

1.)  Inconsistent spaces between words (some are non-existent)
2.)  Inconsistent separators between elements (sometimes semi-colons,
sometimes commas, but commas appear to belong to elements, sometimes no
clear separator at all)

Basically, this problem is not solvable by computer with currently
available resources.  There is no way Python or anything else can know
which words are meant to be together and which are not, when there are
no separators between elements and no separators between words within
those elements.

You need to find a new way of generating the string, or do it by hand.

How did you get the string?

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


Re: splitting a long string into a list

2006-11-27 Thread Robert Kern
ronrsr wrote:
> I have a single long string - I'd like to split it into a list of
> unique keywords. Sadly, the database wasn't designed to do this, so I
> must do this in Python - I'm having some trouble using the .split()
> function, it doesn't seem to do what I want it to - any ideas?

Did you follow the recommendations given to you the last time you asked this
question? What did you try? What results do you want to get?

-- 
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: splitting a long string into a list

2006-11-27 Thread Raphael
What exactly seems to be the problem?


"ronrsr" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I have a single long string - I'd like to split it into a list of
> unique keywords. Sadly, the database wasn't designed to do this, so I
> must do this in Python - I'm having some trouble using the .split()
> function, it doesn't seem to do what I want it to - any ideas?
>
> thanks very much for your help.
>
> r-sr- 


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


Re: Inheritance from builtin list and override of methods.

2006-11-27 Thread Fredrik Lundh
OKB (not okblacke) wrote:

 > Why doesn't it?

because whoever wrote the class didn't do things that way, mostly for 
efficiency reasons.  there's nothing in Python that keeps you from using 
template methods if you want, but that's a costly approach, so it's not 
very common.

I suggest reading up on OO design patterns.



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


Re: splitting a long string into a list

2006-11-27 Thread ronrsr
still having a heckuva time with this.

here's where it stand - the split function doesn't seem to work the way
i expect it to.


longkw1,type(longkw):   Agricultural subsidies; Foreign
aid;Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
 1

longkw.replace(',',';')

Agricultural subsidies; Foreign aid;Agriculture; Sustainable
Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood
Development


 kw = longkw.split("; ,")#kw is now a list of len 1

kw,typekw= ['Agricultural subsidies; Foreign aid;Agriculture;
Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
Childhood Development, Birth Defects; Toxic Chemicals;Antibiotics,
Animals;Agricultural Subsidies


what I would like is to break the string into a list of the delimited
words, but have had no luck doing that - I thought split wuld do that,
but it doens't.

bests,

-rsr-


Robert Kern wrote:
> ronrsr wrote:
> > I have a single long string - I'd like to split it into a list of
> > unique keywords. Sadly, the database wasn't designed to do this, so I
> > must do this in Python - I'm having some trouble using the .split()
> > function, it doesn't seem to do what I want it to - any ideas?
>
> Did you follow the recommendations given to you the last time you asked this
> question? What did you try? What results do you want to get?
>
> --
> 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


How to increase the speed of this program?

2006-11-27 Thread HYRY
I want to join two mono wave file to a stereo wave file by only using
the default python module.
Here is my program, but it is much slower than the C version, so how
can I increase the speed?
I think the problem is at line #1, #2, #3.

import wave
import array
lfile = wave.open(lfilename)
rfile = wave.open(rfilename)
ofile = wave.open(ofilename, "w")
lformat = lfile.getparams()
rformat = rfile.getparams()
lframes = lfile.readframes(lformat[3])
rframes = rfile.readframes(rformat[3])
lfile.close()
rfile.close()
larray = array.array("h", lframes)
rarray = array.array("h", rframes)
oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1
oarray[0::2] = larray#2
oarray[1::2] = rarray#3
ofile.setnchannels(2)
ofile.setsampwidth(2)
ofile.setframerate(lformat[2])
ofile.setnframes(len(larray))
ofile.writeframes(oarray.tostring())
ofile.close()

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


Re: splitting a long string into a list

2006-11-27 Thread Tim Roberts
"ronrsr" <[EMAIL PROTECTED]> wrote:

>I have a single long string - I'd like to split it into a list of
>unique keywords. Sadly, the database wasn't designed to do this, so I
>must do this in Python - I'm having some trouble using the .split()
>function, it doesn't seem to do what I want it to - any ideas?
>
>thanks very much for your help.
>
>r-sr-
>
>
>longstring = 'Agricultural subsidies; Foreign aidAgriculture;
>Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
>Childhood Development, Birth Defects; Toxic ChemicalsAntibiotics,
>AnimalsAgricultural Subsidies, Global TradeAgricultural
>SubsidiesBiodiversityCitizen ActivismCommunity...

What do you want out of this?  It looks like there are several levels
crammed together here.  At first blush, it looks like topics separated by
"; ", so this should get you started:

  topics = longstring.split("; ")
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Porting Tkinter application to JYthon

2006-11-27 Thread Tim N. van der Leeuw
Hi Sandip,

sandip desale wrote:
> Dear All,
>
> We have a Tcl/Tk application written using Python 2.2. Using this application 
> we want to call some customizable Java APIs. I tried porting Tcl/Tk 
> application to Jython but not able to do the same as TKinter library is not 
> available with JYthon.
>
> Can you please help me in porting Tkinter application to Jython? Also kindly 
> let me know how to do the same.
>
>
> Thanks & Regards,
> Sandip Desale
>

In response to my previous post I got an e-mail suggesting to look at
JPype; however that message wasn't posted to the list, despite a CC: to
[EMAIL PROTECTED] And it seems that you haven't received the
message either.

Anyways, here's the URL for the JPype project which allows the use of
Java libraries from Python:

http://jpype.sourceforge.net/

I downloaded it for windows and it seems to work quite OK, although I
only did some toy-testing (opening a Swing filechooser window from
within PythonWin, for instance).

The purpose of the project is calling Java code from Python, and it has
some limited facilities to allow callbacks from Java to Python. I think
therefore that it fits very well what you and I would need: integration
of Java libraries into Python projects.

It does not, however, allow subclassing of Java classes in Python or
the other way round, and it does not allow calling of arbitrary Python
code from the JVM.

Cheers,

--Tim

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


Re: splitting a long string into a list

2006-11-27 Thread John Machin

ronrsr wrote:
> I have a single long string - I'd like to split it into a list of
> unique keywords. Sadly, the database wasn't designed to do this, so I
> must do this in Python - I'm having some trouble using the .split()
> function, it doesn't seem to do what I want it to - any ideas?
>
> thanks very much for your help.
>
> r-sr-
>
>
> longstring = 'Agricultural subsidies; Foreign aidAgriculture;
> Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
[snip most of VERY long string]
> Book);Corporate Reform,  Personhood, Farming (Dem. Book);Crime Rates,
> Legislation, Education;Debt, Credit Cards;'


Hi ronster,

As far as I recall, without digging in the archives:

We would probably agree (if shown the schema) that the database wasn't
designed.  However it seems to have changed. Last time you asked, it
was at least queryable and producing rows, each containing one column
(a string of structure unknown to us and not divulged by you). You were
given extensive advice: how to use split(), plus some questions to
answer about the data e.g. the significance (if any) of semicolon
versus comma. You were also asked about the SQL that was used. You were
asked to explain what you meant by "keywords". All of those questions
were asked so that we could understand your problem, and help you.
Since then, nothing.

Now you have what appears to be something like your previous results
stripped of newlines and smashed together (are the newlines of no
significance at all?), and you appear to be presenting it as a new
problem.

What's going on?

Regards,
John

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


  1   2   >