Re: do i need to create new rgbimage class

2007-12-30 Thread Gabriel Genellina
On 29 dic, 12:42, [EMAIL PROTECTED] wrote:

> am a beginner in python and PIL  .I need to read an RGB 8 bit image
> (am using jpeg )and pack the rgb color values into a double value so i
> can store the image as a list of pixelvalues.From my application i
> should be able to call rgbimage1.getpixellist() to retrieve the double
> values of an image.

(May I ask why an accessor like getpixellist() instead of simply
rgbimage1.pixellist?)

> Do i need to create a new class for this?I made something like
>
> class myrgbimage:
>       def  __init__(self,filename):
>
>       def _readimage(self):
>           im=Image.open(filename)
>           self._readImage(filename)
>           self._wd,self._ht=im.size
>           for y in range(self._ht):
>                for x in range(self._wd):
>                      r,g,b=im.getpixel((x,y))
>                      pval=self.rgbTodoubleval((r,g,b))
>                      self._pixellist.append(pval)

The PIL docs at [1] say that using getpixel is very slow, and suggest
to use getdata instead. And you want a flat representation anyway,
just like getdata. So replace the for loops above with:

  rgbTodoubleval = self.rgbTodoubleval
  self._pixellist = [rgbTodoubleval(pix) for pix in
im.getdata()]

I've not tested it, but should be faster.

>   def rgbTodoubleval(self,(r,g,b)):
>   alpha=255
>   pixelvalue=(alpha<<24)|(r<<16 )|( g<<8) | b
>   return pixelvalue

I don't get the name - why "rgb to double"? This does not return a
"double", but a long integer, even if you intended to return a 32 bit
integer.
This version returns an integer:

from struct import pack, unpack
def rgbTodoubleval((r,g,b)):
  alpha=255
  return unpack("l", pack("", b, g, r, alfa))[0]

It *may*, or not, be what you want...

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


Re: do i need to create new rgbimage class

2007-12-30 Thread Gabriel Genellina
On 30 dic, 04:57, Gabriel Genellina <[EMAIL PROTECTED]> wrote:

> The PIL docs at [1] say that using getpixel is very slow, and suggest

Sorry, dropped the reference:

[1] http://www.effbot.org/imagingbook/image.htm#tag-Image.Image.getpixel

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


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Marc 'BlackJack' Rintsch
On Sat, 29 Dec 2007 15:10:24 -0800, Raymond Hettinger wrote:

> These thoughts reflect my own experience with the itertools module.
> It may be that your experience with them has been different.  Please
> let me know what you think.

I seem to be in a minority here as I use both functions from time to time.
One "recipe" is extracting blocks from text files that are delimited by a
special start and end line.

def iter_block(lines, start_marker, end_marker):
return takewhile(lambda x: not x.startswith(end_marker),
 dropwhile(lambda x: not x.startswith(start_marker),
   lines))

Maybe these functions usually don't turn up in code that can be called
"recipes" so often but are useful for themselves.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: difference between `x in list` and `list.index(x)` for instances of a new-style class

2007-12-30 Thread Riccardo Murri
[EMAIL PROTECTED] writes:

> On 28 dic, 20:12, Riccardo Murri <[EMAIL PROTECTED]> wrote:
>
>> The list `self.base` contains "canonical" forms of the graphs and the
>> `graph` object must compare equal to some item of the list, which
>> indeed it does::
>>
>>   (Pydb) p graph == self.base[27]  
>>   True
>>
>>   (Pydb) p graph in self.base
>>   True
>>
>> However, I cannot directly get the index of the canonical graph (the
>> number "27" above was found by manual inspection)::
>>
>>   (Pydb) self.base.index(graph)
>>   *** ValueError: list.index(x): x not in list
>>
>> All graphs are instances of a `Graph` new-style class that implements
>> comparison operators `__eq__` and `__ne__`, but no other rich-compare
>> stuff.
>>
>> I'm using Python 2.5::
>>
>>   Python 2.5 (release25-maint, Dec  9 2006, 16:17:58)
>>   [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2
>>
>> So my question is: what are the implementation differences between `x
>> in list` and `list.index(x)` and why can one report that an item is in
>> the list while the other cannot find its index?  Should I add
>> something to the `Graph` class so that `index` works?
>
> (I've checked on 2.5.1 but I don't see any relevant differences with
> the 2.5 version). Looking at the source for both methods, they only
> use the __eq__ operator, but there is a slight difference: while one
> evaluates list[i]==x, the other reverses the operands. If your __eq__
> is not reflexive, that could explain the difference.
>

That was indeed the reason: a bug in Graph.__eq__ broke reflexivity in
certain cases.

Thank you very much!!

-- 
Riccardo Murri, via Galeazzo Alessi 61, 00176 Roma

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

Re: sqlobject question...

2007-12-30 Thread Markus Gritsch
Hi,

you should ask SQLObject related questions better at
"SQLObject discussion" <[EMAIL PROTECTED]>

Oleg Broytman and others are very helpful there.

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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread thebjorn
On Dec 29, 7:17 pm, Istvan Albert <[EMAIL PROTECTED]> wrote:
> On Dec 29, 12:50 pm, bukzor <[EMAIL PROTECTED]> wrote:
>
> > Is this functionality intended? It seems very unintuitive. This has
> > caused a bug in my programs twice so far, and both times I was
> > completely mystified until I realized that the default value was
> > changing.
>
> it is only unintuitive when you do not know about it
>
> once you realize how it works and what it does it can actually be very
> useful
>
> i.

I agree it is a potentially useful feature, yet it can still bite you
even after a decade of Python... Scenario: long running server
process, Bug report: "people aren't getting older", Code:

   def age(dob, today=datetime.date.today()):
   ...

None of my unit tests caught that one :-)

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


Re: Choosing a new language

2007-12-30 Thread Joachim Durchholz
John Thingstad schrieb:
> Skrev Joachim Durchholz <[EMAIL PROTECTED]>:
> 
>> However, for web applications, I found a far easier variant: I just 
>> reload the page being debugged. (I have to make sure that the backend 
>> is in the same state when reloading, but that's usually easy to 
>> accomplish.)
>> So web pages are one area where code modification during debugging is 
>> less important.
> 
> Haveyou looked at selenium?

Yes. I couldn't get it to work.
I think it's more regression testing than debugging though. If that's 
correct, it's less pertinent to this subthread (which is already well 
off-topic already).

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


Unexpected __metaclass__ method behavior

2007-12-30 Thread anne . nospam01
Dear fellow Pythonians,

I just stumbled upon the following unexpected behavior:

class TestType(type):
def Foo(self): return 'TestType Foo'
class Test(object):
__metaclass__ = TestType
def Foo(self): return 'Test Foo'
t = Test()
print t.Foo()
print Test.Foo()

This will produce:
Test Foo
Traceback (most recent call last):
  File "test.py", line 8, in 
print Test.Foo()
TypeError: unbound method Foo() must be called with Test instance as
first argument (got nothing instead)

I can imagine why this is happening, and that there is no easy
solution, but it is not what I was expecting.

Anybody willing to explain the details of what's exactly going on
during the method lookup of Test.Foo?

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


Re: Unexpected __metaclass__ method behavior

2007-12-30 Thread Michele Simionato


[EMAIL PROTECTED] wrote:
> Dear fellow Pythonians,
>
> I just stumbled upon the following unexpected behavior:
>
> class TestType(type):
> def Foo(self): return 'TestType Foo'
> class Test(object):
> __metaclass__ = TestType
> def Foo(self): return 'Test Foo'
> t = Test()
> print t.Foo()
> print Test.Foo()
>
> This will produce:
> Test Foo
> Traceback (most recent call last):
>   File "test.py", line 8, in 
> print Test.Foo()
> TypeError: unbound method Foo() must be called with Test instance as
> first argument (got nothing instead)
>
> I can imagine why this is happening, and that there is no easy
> solution, but it is not what I was expecting.
>
> Anybody willing to explain the details of what's exactly going on
> during the method lookup of Test.Foo?

The regular method is checked for *before* the metaclass method.
You must use

type(Test).Foo(Test)

to call the method. It is clear that it must be that way: when you do
(for instance)
SomeClass.__init__ you do not expect to have type.__init__(SomeClass)
called.
Notice that *all* classes have a metaclass, by default "type" for new-
style
classes and "ClassType" for old-style ones.

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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread Istvan Albert
On Dec 30, 5:23 am, thebjorn <[EMAIL PROTECTED]>
wrote:

>def age(dob, today=datetime.date.today()):
>...
>
> None of my unit tests caught that one :-)

interesting example I can see how it caused some trouble. A quick fix
would be to write it:

def age(dob, today=datetime.date.today ):

and inside the definition invoke it as today() rather than just today.
That way it still keeps the original spirit of the definition.

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


Re: do i need to create new rgbimage class

2007-12-30 Thread jimgardener
> (May I ask why an accessor like getpixellist() instead of simply
> rgbimage1.pixellist?)

sorry,
bad style of coding on my part..was doing java stuff..

>
> I don't get the name - why "rgb to double"? This does not return a
> "double", but a long integer,

actually it was to be of 'long' type not double..sorry again

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


Re: difference between `x in list` and `list.index(x)` for instances of a new-style class

2007-12-30 Thread Gabriel Genellina
On 30 dic, 06:24, Riccardo Murri <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] writes:
>
> >>   (Pydb) p graph == self.base[27]  
> >>   True
> >>   (Pydb) p graph in self.base
> >>   True
> >>   (Pydb) self.base.index(graph)
> >>   *** ValueError: list.index(x): x not in list

> > Looking at the source for both methods, they only
> > use the __eq__ operator, but there is a slight difference: while one
> > evaluates list[i]==x, the other reverses the operands. If your __eq__
> > is not reflexive, that could explain the difference.
>
> That was indeed the reason: a bug in Graph.__eq__ broke reflexivity in
> certain cases.

Combined with some other WTF bugs I've found at work, lately I feel
more like a detective than a software developer :)

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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread Istvan Albert
On Dec 29, 11:21 pm, bukzor <[EMAIL PROTECTED]> wrote:

> The standard library is not affected because

the people who wrote code into it know how python works.

Programming abounds with cases that some people think should work
differently:

a = b = []
a.append(1)

is b empty or not at this point? Get informed, remember the rules, be
happy and move on to write some cool code.

There is little new in what you say. Every so often someone is having
a confusing time with a feature and therefore proposes that the
language be changed to match his/her expectations.

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


Re: do i need to create new rgbimage class

2007-12-30 Thread Gabriel Genellina
On 30 dic, 10:53, [EMAIL PROTECTED] wrote:

> > I don't get the name - why "rgb to double"? This does not return a
> > "double", but a long integer,
>
> actually it was to be of 'long' type not double..sorry again

Notice that a Python 'long' is an infinite range integer; the C 'long'
type maps to Python 'int'. Perhaps you want the latter.

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


Redirecting STDOUT using C calls.

2007-12-30 Thread Tom Gaudasinski
Greetings,
I'm trying to redirect python's stdout to another location. The 
reason for this is that I'm embedding python in an application. Now, 
originally my code was developed for Linux and that did not require 
redirection due to the fact that every X11 application can have an 
STDOUT associated with it. I then proceeded to take interest in making 
my code portable and looked at compiling it on windows, however Win32 
GUI applications are not given an STDOUT by default. One has to first 
AllocConsole() and then reassign the handles using magic tokens 
"CON(IN|OUT)$" such as freopen("CONOUT$", "w", stdout). I like to keep 
code clean and would like to stick to the C API as much as possible.
I dived into the source and figured out two ways of doing it:


#include 
#include 

// Demonstrates redirection after initialisation.
int main() {
Py_Initialize();
FILE* afile = fopen("zig.txt", "w+");
PySys_SetObject("stdout", PyFile_FromFile(afile, "zig.txt", 
"wb", fclose));
// I would be using boost::python::exec, but let's stick to basics.
PyRun_SimpleString("print(\"pytest1\")");
Py_Finalize();
fclose(afile);
return 0;
}

#include 
#include 
#include 

// Demonstrates redirection before initialisation.
int main() {
FILE* afile = fopen("zig.txt", "w+");
// All of this program's output to file.
stdout = afile;
Py_Initialize();
PyRun_SimpleString("print(\"pytest2\")");
Py_Finalize();
fclose(afile);
return 0;
}


For exemplary purposes, i've used files as the target for 
redirection, however the actual target in windows would be the FILE* 
gained from opening the "CONOUT$" virtual file. Both of these examples 
compile and work fine on linux, however I get an illegal access 
exception (a SIGSEGV equivalent i think) on Windows (XP). Why? The 
illegal access happens on the line that executed the python print() 
function. What is the cause for this and how can i fix it?
It may also help to mention that the following *Python* code works 
in Windows:

import sys
sys.stdout = open("CONOUT$", "w", 0)
print("foo")

So if this works, there must be a difference between how the inbuilt 
open() opens and assigns the pointers than how the C API does it. Any ideas?

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


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Istvan Albert
On Dec 30, 3:29 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

> One "recipe" is extracting blocks from text files that are delimited by a
> special start and end line.

Neat solution!

I actually need such functionality every once in a while.

Takewhile + dropwhile to the rescue!

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


The Tears Of Finding The Truth

2007-12-30 Thread abdo911

Through The Internet
INTRODUCTION
The following story occurred on the Internet
through one of the chat programs (Freetel) in January 1999. It is a
real dialogue between a Christian and a Muslim. The story centers on
Derek's realization of today's Christianity and his subsequent
conversion to lslam. This Christian-Muslim dialogue has been edited
for readability and for the clarity of its message.

ABDULLAH: Hello there! How are you man?
 DEREK:  Hello! Well, how are you?
 ABDULLAH: I'm fine and you?
 DEREK:  I'm fine thanks.
 ABDULLAH: Where are you from?
 DEREK:  I'm from L.A. (Los Angeles).
 ABDULLAH: The land of Hollywood!
 DEREK:  Well that's right. Have you ever been to L.A.?
 ABDULLAH: No, never. Why are you calling yourself the Black Magic?
 DEREK:  It's just a nickname, man!
 ABDULLAH: I see.
 DEREK:  Where are you from? Are you an Arab?
 ABDULLAH: Yes, I am from Saudi Arabia but I'm in Qatar now. What is
your name?
 DEREK:  My name is Derek. What's your name?
 ABDULLAH: My name is Abdullah.
 DEREK:  What does Abdullah mean?
 ABDULLAH: Abdullah means the servant of Allah and it is the function
of each individual on the face of the earth to serve llah according to
what Allah wants from us. By the way, Allah is the proper name of
God.
 DEREK:  How do we know what God or Allah wants from us?
 ABDULLAH: All of this is outlined in the Qur'an and the Sunnah (Ways
of Prophet Muhammad; his sayings, actions and aprovals). These are the
two major sources of guidance in lslam. Could you please tell me more
about yourself? How ol are you?
DEREK:   I am 19 years old, black and very uch interested in
knowing more about lslam. First of all, what should a person do or
believe in to become a Muslim?
ABDULLAH: Very easy, you just say that there is no god worthy of
worshi but Allah and Muhammad is His Messenger, and you become
Muslim,
DEREK:  You mean Muhammad is his apostle? But a a Christian or non-
Muslim, this sentence is not enough to make it clear to me.
ABDULLAH: Ok Allah sent Muhammad a His last Prophet and Messenger and
revealed the Qur'an to him as the final revelation to mankind. Allah
said that He perected His religion and called it lslam (see Qur'an
5:3). Islam means peaceful submission to the Will of Allah.
DEREK:  I see.
ABDULLAH: Yes, and unfortunately most Christians don't know or they
deny that the coming of Prophet Muhammad is foretold in their
scriptures (See Deuternomy 18:18; 21: 21; Psalms 1 18:22-23; Isiah
42:1-13; Habakuk 3:3-4; Matthew 21:42-43; John 14:12-17,15:26,27;
1:5-16). Muslim theologians have stated that the person who is
described by Jesus to come after him (in the above verses) is Mhammed
(peace be upon him).
DEREK: OK Fine, but why was there a need for another prophet after
Jesus and  another revelation after the Bible?
 ABDULLAH: All of the Prophets came to teach their peoples the Oneness
of God. In the case of Jesus, he was only sent as a Messenger to the
lost sheep of the house of Israel (see Matt. 15:24). What happened was
that all of these prophets were not well received by the majority of
the people. For instance, they started tampering with the teachings of
Moses and Jesus, peace be upon them (see Qur'an 2:79). That is why
Allah sent Muhammad with the last Message, (i.e., the Qur'an), to
bring all of mankind back to the belief in and worship of One God,
without partners or intermediaries.
DEREK: Is the Qur'an similar to the Bible? I mean, what is it composed
of?
ABDULLAH: The Qur'an came as the last code emphasizing the same pure
monotheistic teachings of Jesus peace be upon him, defending all the
previous pure teachings of monotheistic beliefs and clarifying who
Jesus was and who his mother was, showing that they were no more than
great people.
 DEREK: OK then, how-can we be sure that the Qur'an has remained the
same since the time of Prophet Muhammad?
 ABDULLAH: Allah Himself has guaranteed that He would guard the Qur'an
from corruption (see Qur'an 15:9). Hence, the real and pure words of
Allah are found in the Qur'an, which was revealed in Arabic, the
language of Mohammed's people. Since then, not an iota has changed.
This is unlike what has happened in the other religions. For example,
if you look at the Bible, you find a lot of versions; the name Bible
itself is indicative of those changes because Bible means a collection
of books from different writers.
DEREK:  But didn't God call it the Bible?
ABDULLAH: God calls the Scripture revealed to Jesus "Injeel" in the
Qur'an for which the closest name in the Bible would be the word
Gospel. The Bible was written may years after the time of Jesus in a
language that was alien to Jesus; it was Latin Vulgate, a language
that he never spoke. Isn't this strange? Interestingly, most of what
was written in the New Testament was authored by Paul, who, according
to James, the brother of Jesus in the Bible, had a polluted mind
because he changed and contradicted most of the teachings of Jesus.
DER

What is the best way to do dynamic imports ?

2007-12-30 Thread marcroy . olsen
Hi list and python gurus :-)

I'm playing with some mod_python and web development. And in me code I
need to do som dynamic imports.
Right now I just do a:

exec 'import '+some_modulename

But it seems to easy, is there a "dark side" to doing it this way?
(memory use,processing ,etc)
And have to I check if the modul is already loaded?


Another thing is how to call my dynamic imported moduls.
Now I use exec (as with my modules), like this:

exec 'newclass = '+classname+'()'
newclass.somefunction()

Again it seems to easy. Is there a better/proper way to do it?


Do anybody now a good howto or tutorial to this?


Many thanks and hope you all have a happy new year :-)

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


Re: Redirecting STDOUT using C calls.

2007-12-30 Thread Christian Heimes
Tom Gaudasinski wrote:
> Greetings,
> I'm trying to redirect python's stdout to another location. The 
> reason for this is that I'm embedding python in an application. Now, 
> originally my code was developed for Linux and that did not require 
> redirection due to the fact that every X11 application can have an 
> STDOUT associated with it. I then proceeded to take interest in making 
> my code portable and looked at compiling it on windows, however Win32 
> GUI applications are not given an STDOUT by default. One has to first 
> AllocConsole() and then reassign the handles using magic tokens 
> "CON(IN|OUT)$" such as freopen("CONOUT$", "w", stdout). I like to keep 
> code clean and would like to stick to the C API as much as possible.

Why don't you use the appropriate C api to redirect the standard streams?

freopen("filename", "w", stdout);

See
http://www.gnu.org/software/libc/manual/html_mono/libc.html#Standard-Streams

Christian

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


Re: What is the best way to do dynamic imports ?

2007-12-30 Thread Benjamin
On Dec 30, 8:24 am, [EMAIL PROTECTED] wrote:
> Hi list and python gurus :-)
>
> I'm playing with some mod_python and web development. And in me code I
> need to do som dynamic imports.
> Right now I just do a:
>
> exec 'import '+some_modulename
The correct way to do this is use the __import__ function. It takes
the string name of the module you want to import and returns the
module.
new_mod = __import__(some_modulename)
>
> But it seems to easy, is there a "dark side" to doing it this way?
> (memory use,processing ,etc)
Well, it's generally frowned on to use exec and eval.
> And have to I check if the modul is already loaded?
sys.modules is a list of all imported modules, but python won't import
a module if it's already been loaded.
>
> Another thing is how to call my dynamic imported moduls.
> Now I use exec (as with my modules), like this:
>
> exec 'newclass = '+classname+'()'
> newclass.somefunction()
>
> Again it seems to easy. Is there a better/proper way to do it?
If you just have the string name of a class, you have to use eval or
exec:
newclass = eval(classname)

However, if you have the class object, you can just instantiate that:
class LargeClass:
def meth(): pass
some_class = LargeClass
new_class = some_class()
some_class.meth()
>
> Do anybody now a good howto or tutorial to this?
>
> Many thanks and hope you all have a happy new year :-)
You, too!
>
> /marc

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


Re: What is the best way to do dynamic imports ?

2007-12-30 Thread Torsten Bronger
Hallöchen!

[EMAIL PROTECTED] writes:

> I'm playing with some mod_python and web development. And in me
> code I need to do som dynamic imports.  Right now I just do a:
>
> exec 'import '+some_modulename
>
> But it seems to easy, is there a "dark side" to doing it this way?
> (memory use,processing ,etc) And have to I check if the modul is
> already loaded?

I use the imp module for this:

try:
file, pathname, description = imp.find_module(full_name)
my_module = imp.load_module(full_name, file, pathname, description)
finally:
file.close()

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the best way to do dynamic imports ?

2007-12-30 Thread Gabriel Genellina
En Sun, 30 Dec 2007 12:24:53 -0200, <[EMAIL PROTECTED]> escribi�:

> I'm playing with some mod_python and web development. And in me code I
> need to do som dynamic imports.
> Right now I just do a:
>
> exec 'import '+some_modulename
>
> But it seems to easy, is there a "dark side" to doing it this way?
> (memory use,processing ,etc)

Use __import__, specially if some_modulename comes from the outside.
What if some_modulename contains "modulename\nsome_nasty_function_call()"

> And have to I check if the modul is already loaded?

Not needed; the standard import machinery already does that.

> Another thing is how to call my dynamic imported moduls.
> Now I use exec (as with my modules), like this:
>
> exec 'newclass = '+classname+'()'
> newclass.somefunction()
>
> Again it seems to easy. Is there a better/proper way to do it?

Use getattr to obtain the desired class from the containing module, then  
use it as any other class:
the_module = __import__(some_modulename)
the_class = getattr(the_module, classname)
o = the_class()
o.somefunction()

Never use exec/eval and friends - and never ever use them in a web  
application!

> Do anybody now a good howto or tutorial to this?

No... what do you want covered?

> Many thanks and hope you all have a happy new year :-)

Thanks, and a happy new year for you too!

-- 
Gabriel Genellina

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

Re: What is the best way to do dynamic imports ?

2007-12-30 Thread marcroy . olsen
First of thanks to all for you, especially for the quick replys.

Just need to walk the dog then I giv it a short.


On Dec 30, 3:57 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
>
> > Do anybody now a good howto or tutorial to this?
>
> No... what do you want covered?

Nothing, think you reply coved it all.

Otherwise I will be back ;-)

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


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread George Sakkis
On Dec 30, 4:12 pm, Istvan Albert <[EMAIL PROTECTED]> wrote:
> On Dec 30, 3:29 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> > One "recipe" is extracting blocks from text files that are delimited by a
> > special start and end line.
>
> Neat solution!
>
> I actually need such functionality every once in a while.
>
> Takewhile + dropwhile to the rescue!
>
> i.

On at least one thread and a recipe for this task (http://
aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877), the proposed
solutions involved groupby() with an appropriate key function. The
takewhile/dropwhile solution seems shorter and (maybe) easier to read
but perhaps not as flexible and general. Regardless, it's a good
example of takewhile/dropwhile.

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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread StephenRFerg
This is a well-known python gotcha.  See:
http://www.ferg.org/projects/python_gotchas.html#contents_item_6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread George Sakkis
On Dec 29, 9:14 pm, bukzor <[EMAIL PROTECTED]> wrote:
> Here's the answer to the 
> question:http://www.python.org/doc/faq/general/#why-are-default-values-shared-...
>
> It looks like Guido disagrees with me, so the discussion is closed.

Note that the FAQ mainly explains *what* happens, not *why* was this
decision taken. Although it shows an example where "this feature can
be useful", it's neither the only way to do it nor is memoization as
common as wanting fresh default arguments on every call.

> For the record, I still think the following would be an improvement to
> py3k:
>
> In python25:
> def f(a=None):
> if a is None: a = []
> ...
>
> In py3k becomes:
> def f(a=[])
> ...
>
> In python25 (this function from the FAQ linked above):
> def f(a, _cache={}):
> # Callers will never provide a third parameter for this function.
> (then why is it an argument?)
> ...
>
> In py3k becomes:
> _cache = {}
> def f(a):
> global _cache
> ...
>
> This follows the "explicit is better" and "one best way" principles of
> Python, and greatly improves the intuitiveness. Also since the first
> example is much more common, it reduces the overall verbosity of the
> language.

I'm with you on this one; IMHO it's one of the relatively few language
design missteps of Python, favoring the rare case as the default
instead of the common one. Unfortunately, many Pythoneers become so
immersed with the language and whatever the current status quo is that
they rarely question the rationale of the few counter-intuitive design
choices.

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


Re: Tab indentions on different platforms?

2007-12-30 Thread Thorsten Kampe
* Steven D'Aprano (Sun, 30 Dec 2007 00:37:32 -)
> On Sat, 29 Dec 2007 15:29:25 +, Thorsten Kampe wrote:
> > I'd personally go for spaces because:
> > 
> > 1. I don't like things I cannot see (control characters)
> 
> You can see spaces but not tabs? Your editor is pretty weird. In all the 
> editors I've every used, both spaces and tabs show up as empty white 
> space.

That's because the editor displays those invisible tab control 
characters as something they're not: spaces.

> > 2. I never had problems with spaces but plenty with tabs
> 
> What problems have you had with tabs that aren't related to buggy 
> applications or users that mix tabs and spaces?

Fortunately I don't remember every incident when I stumbled about 
something weird behaving or looking. One thing I do remember is 
reading python source code (not my own) with a pager. The source code 
was badly indented. The pager was not "buggy".

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


Re: Tab indentions on different platforms?

2007-12-30 Thread Thorsten Kampe
* Ben Finney (Sun, 30 Dec 2007 15:36:12 +1100)
> Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > On Sat, 29 Dec 2007 15:29:25 +, Thorsten Kampe wrote:
> > > I'd personally go for spaces because:
> > > 
> > > 1. I don't like things I cannot see (control characters)
> > 
> > You can see spaces but not tabs? Your editor is pretty weird. In all
> > the editors I've every used, both spaces and tabs show up as empty
> > white space. (Or coloured space if I set the editor to use a
> > coloured background.)
> 
> Though Thorsten could have been clearer, "thing that is not a space
> character but shows up as white space" is a near-enough approximation
> of "thing I cannot see".
> 
> > > 2. I never had problems with spaces but plenty with tabs
> > 
> > Periodically, I ask on this list what problems people have with
> > tabs. (I'm fully aware that mixing tabs and spaces is a Bad Thing.)
> > I've had little luck getting any answer except "Tabs are bad,
> > m'kay?".
> 
> Posit: White space is most often achieved by the user inserting a
> sequence of space characters (U+0020).
> 
> Posit: Tab characters (U+0009) are, in a majority of environments,
> rendered visually indistinguishable from a sequence of space
> characters.
> 
> Corollary: most readers will, when seeing a stretch of white space on
> a line, default to assuming that it represents a sequence of space
> (U+0020) characters.
> 
> Corollary: So when a file containing either spaces or tabs is edited
> in such an environment, the common way chosen by the user to get to
> the same indentation level as existing lines is to prepend space
> characters (using the spacebar or the Tab key or whatever facility the
> editor provides) until the indentation lines up visually --
> remembering the caveat that tabs and space-sequences are visually
> indistinguishable in many environments.
> 
> Argument: The user will get an unexpected result when they do the
> obvious thing (prepend space characters) in a tabs-only file. With
> existing spaces-only files, the obvious way to get matching
> indentation gives the expected result.
> 
> Conclusion: Thus, using tabs-only is inferior to using spaces-only for
> indentation, because it violates the Principle of Least Astonishment
> http://en.wikipedia.org/wiki/Principle_of_least_astonishment>.

Man, how did you know what I wanted to say (but failed to to express) 
:-) ? Anyway: the consequence of your well done argumentation is that 
someone editing Python code has to use a specialised editor to prevent 
screwing up tab indented code - and that's bad.

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


Re: error on importing variable value

2007-12-30 Thread int32bit
On Dec 29, 6:05 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sat, 29 Dec 2007 15:31:30 -0800 (PST), [EMAIL PROTECTED] declaimed
> the following in comp.lang.python:
>
>
>
> > I can't figure out why this doesn't work. Any ideas appreciated.
>
> > conn = MySQLdb.connect (db = "vocab")
>
> This is a keyword parameter association, the parameter named "db" is
> given the string value "vocab".
>
> > import defs
> > conn = MySQLdb.connect (defs.connect)
> > where defs.py is
>
> > connect = 'db = "vocab"'
>
> This is a string.  You'd get the same error using:
>
> conn = MySQLdb.connect('db="vocab"')
>
> as you are giving the entire string to whatever the first defined
> parameter in .connect() is...
>
> Change defs.py to:
>
> -=-=-=-=-
> connect = { "db" : "vocab" }
>
> and change the connection to read:
>
> -=-=-=-=-
> conn = MySQLdb.connect(**defs.connect)
>
> to force keyword unpacking of the dictionary
>
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED]  [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/


Thanks. This works great. As a side note, it can also be extended so
that if defs.py is

connect = { "host" : "localhost", "user" : "joey", "db" : "vocab" }

the MySQLdb.connect(**defs.connect) still works.





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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread thebjorn
On Dec 30, 2:45 pm, Istvan Albert <[EMAIL PROTECTED]> wrote:
> On Dec 30, 5:23 am, thebjorn <[EMAIL PROTECTED]>
> wrote:
>
> >def age(dob, today=datetime.date.today()):
> >...
>
> > None of my unit tests caught that one :-)
>
> interesting example I can see how it caused some trouble. A quick fix
> would be to write it:
>
> def age(dob, today=datetime.date.today ):
>
> and inside the definition invoke it as today() rather than just today.
> That way it still keeps the original spirit of the definition.
>
> i.

The purpose of the argument was to be able to calculate the age at a
given point in time -- i.e. was the person 18 y/o at the time of the
incident?

Our coding standard now dictates:

   def foo(arg=None):
   if arg is None:
   arg = 

(unless there's a very good reason to do it otherwise :-)

a close runner-up, that we specifically opted not to allow was

   def foo(arg={}):
   arg = arg or {}

even though it looks sexy and it's perhaps a bit more self-documenting
in some IDEs, it was rejected because it prevents "false" overrides of
the default argument.

For purely practical reasons we couldn't consider

   def foo(arg=None):
   arg =  if arg is None else arg

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


Push to Make (Single Pole) Button running a loop

2007-12-30 Thread Jon Todd
Happy holidays all!

I'm developing an application and, as a relative newbie to Python, have come 
across a stumbling block with Tkinter.

I'd like to have a button that when pressed executes a loop (this could be a 
thread) and then stops execution when it's released (Push to Make - Single 
Pole in electronics terms).

I've tried the regular way of associating the procedure with a callback and 
tried using  and  bindings but am getting nowhere 
fast (in the latter case the button release event seems to occur anyhows).

So my question is: Is there a neat way of doing this? And would it 
necessarily involve creating a custom widget?

...

Also, while I'm here, what's the state of play regarding non-ASCII in 
Tkinter widgets. I've been trying to get our currency symbol, £, to display 
but didn't have much luck even playing with the coding: settings.

TIA

jon 


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

Re: Why does __builtins__ mean different things...

2007-12-30 Thread Dustan
On Dec 22, 1:59 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> Dustan wrote:
> > On Dec 21, 8:11 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> >> I swear there is another thread going on here of which I am not aware.
>
> > You just keep on telling yourself that.
>
> Is there a cricket here?

No, but you can tell yourself that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Sub-classing unicode: getting the unicode value

2007-12-30 Thread Torsten Bronger
Hallöchen!

I sub-classed unicode in an own class called "Excerpt", and now I
try to implement a __unicode__ method.  In this method, I want to
get the actual value of the instance, i.e. the unicode string:

def __unicode__(self):
"""Returns the Unicode representation of Excerpt.  Note that this is 
buffered,
so don't be afraid of calling it many times.

:Return:
  - Unicode representation of ``self``

:rtype: unicode
"""
if not hasattr(self, "__unicode"):
self.__unicode = super(Excerpt, self).__unicode__()
return self.__unicode

Unfortunately, unicode objects don't have a __unicode__ method.
However, unicode(super(Excerpt, self)) is also forbidden because
super() allows attribute access only (why by the way?).

How does my object get its own value?

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread bukzor
On Dec 30, 2:23 am, thebjorn <[EMAIL PROTECTED]>
wrote:
> Scenario: long running server process,
> Bug report: "people aren't getting older", Code:
>
>def age(dob, today=datetime.date.today()):
>...

A very interesting example, thanks.

On Dec 30, 8:25 am, [EMAIL PROTECTED] wrote:
> This is a well-known python gotcha.  
> See:http://www.ferg.org/projects/python_gotchas.html#contents_item_6

Just because it's well known doesn't mean we shouldn't think about it.
For example, in the same list you linked, "3. Integer division" is
being fixed in py3k.


On Dec 30, 8:26 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> I'm with you on this one; IMHO it's one of the relatively few language
> design missteps of Python, favoring the rare case as the default
> instead of the common one.

Well put. Although I've seen 'potentially useful' often used about
this, I havn't found an instance of its use in production code.

On Dec 30, 9:57 am, thebjorn <[EMAIL PROTECTED]>
wrote:
> Our coding standard now dictates:
>
>def foo(arg=None):
>if arg is None:
>arg = 
>
> (unless there's a very good reason to do it otherwise :-)

I believe this is very similar to most people's coding practices. It's
the one I adopted, it's in the above FAQ, the above 'gotchas' list,
and it's all over the standard library. This is a case of a language
feature requiring coding practices to prevent bugs, with very little
value added elsewhere.

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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread Istvan Albert
On Dec 30, 11:26 am, George Sakkis <[EMAIL PROTECTED]> wrote:

> I'm with you on this one; IMHO it's one of the relatively few language
> design missteps of Python, favoring the rare case as the default
> instead of the common one.

George, you pointed this out this link in a different thread

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877

how would you rewrite the code below if you could not use mutable
default arguments (global variables not accepted)? Maybe there is a
way, but I can't think of it as of now.

---

def blocks(s, start, end):
def classify(c, ingroup=[0]):
klass = c==start and 2 or c==end and 3 or ingroup[0]
ingroup[0] = klass==1 or klass==2
return klass
return [tuple(g) for k, g in groupby(s, classify) if k == 1]

print blocks('the {quick} brown {fox} jumped', start='{', end='}')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread bukzor
On Dec 30, 12:32 pm, Istvan Albert <[EMAIL PROTECTED]> wrote:
> On Dec 30, 11:26 am, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > I'm with you on this one; IMHO it's one of the relatively few language
> > design missteps of Python, favoring the rare case as the default
> > instead of the common one.
>
> George, you pointed this out this link in a different thread
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877
>
> how would you rewrite the code below if you could not use mutable
> default arguments (global variables not accepted)? Maybe there is a
> way, but I can't think of it as of now.
>
> ---
>
> def blocks(s, start, end):
> def classify(c, ingroup=[0]):
> klass = c==start and 2 or c==end and 3 or ingroup[0]
> ingroup[0] = klass==1 or klass==2
> return klass
> return [tuple(g) for k, g in groupby(s, classify) if k == 1]
>
> print blocks('the {quick} brown {fox} jumped', start='{', end='}')

Extremely simple

def blocks(s, start, end):
ingroup=[0]
def classify(c):
klass = c==start and 2 or c==end and 3 or ingroup[0]
ingroup[0] = klass==1 or klass==2
return klass
return [tuple(g) for k, g in groupby(s, classify) if k == 1]

print blocks('the {quick} brown {fox} jumped', start='{', end='}')


No globals, as you specified. BTW, it's silly not to 'allow' globals
when they're called for, otherwise we wouldn't need the 'global'
keyword.

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


Re: Sub-classing unicode: getting the unicode value

2007-12-30 Thread Gabriel Genellina
On 30 dic, 17:25, Torsten Bronger <[EMAIL PROTECTED]>
wrote:

> I sub-classed unicode in an own class called "Excerpt", and now I
> try to implement a __unicode__ method.  In this method, I want to
> get the actual value of the instance, i.e. the unicode string:

The "actual value of the instance", given that it inherits from
unicode, is... self.
Are you sure you *really* want to inherit from unicode? Don't you want
to store an unicode object as an instance attribute?

> Unfortunately, unicode objects don't have a __unicode__ method.

Because it's not needed; unicode objects are already unicode objects,
and since they're immutable, there is no need to duplicate them. If it
existed, would always return self.

> However, unicode(super(Excerpt, self)) is also forbidden because
> super() allows attribute access only (why by the way?).

(because its purpose is to allow cooperative methods in a multiple
inheritance hierarchy)

> How does my object get its own value?

"its own value" is the instance itself

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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread Istvan Albert
On Dec 30, 3:41 pm, bukzor <[EMAIL PROTECTED]> wrote:

> No globals, as you specified. BTW, it's silly not to 'allow' globals
> when they're called for, otherwise we wouldn't need the 'global'
> keyword.

okay, now note that you do not actually use the ingroup list for
anything else but getting and setting its first element. So why would
one really need it be a list? Let's replace it with a variable called
ingroup that is not a list anymore. See it below (run it to see what
happens):

--

def blocks(s, start, end):
ingroup = 0
def classify(c):
klass = c==start and 2 or c==end and 3 or ingroup
ingroup = klass==1 or klass==2
return klass
return [tuple(g) for k, g in groupby(s, classify) if k == 1]

print blocks('the {quick} brown {fox} jumped', start='{', end='}')




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


Re: MySQL-python Error

2007-12-30 Thread godavemon
Hopefully you've found it by now and didn't have a frustrating
christmas :).

Get the source from sourceforge and then follow the instructions here.

http://www.davidcramer.net/code/57/mysqldb-on-leopard.html

Worked perfectly for me on OSX 10.5, python 2.5.  Was frustrating to
find.  Good luck!



On Dec 23, 3:09 pm, Steve Ametjan <[EMAIL PROTECTED]> wrote:
> I've been trying to get MySQL-python to install on Leopard for the
> past couple of days, and I keep running into relatively the same
> error. I'm hoping that someone on this list will be able to help me
> out in solving the issue. I'd like to get this solved so I can
> continue developing with Django using MySQL since that's what my web
> server uses as well. I'd hate to have to develop using a different
> database engine on my local machine.
>
> Here's what happens when I try to do an easy_install:
>
> W8743145X91:~ stevea$ sudo easy_install MySQL-python
> Searching for MySQL-python
> Readinghttp://pypi.python.org/simple/MySQL-python/
> Readinghttp://sourceforge.net/projects/mysql-python
> Readinghttp://sourceforge.net/projects/mysql-python/
> Best match: MySQL-python 1.2.2
> Downloadinghttp://osdn.dl.sourceforge.net/sourceforge/mysql-python/MySQL-python-...
> Processing MySQL-python-1.2.2.tar.gz
> Running MySQL-python-1.2.2/setup.py -q bdist_egg --dist-dir /tmp/
> easy_install-DYH0yq/MySQL-python-1.2.2/egg-dist-tmp-zpJkox
> In file included from _mysql.c:35:
> /usr/include/mysql/my_config.h:1030:2: warning: #warning defining
> SIZEOF_CHARP = 4
> /usr/include/mysql/my_config.h:1044:2: warning: #warning defining
> SIZEOF_LONG = 4
> /usr/include/mysql/my_config.h:1151:1: warning: "WORDS_BIGENDIAN"
> redefined
> In file included from /System/Library/Frameworks/Python.framework/
> Versions/2.5/include/python2.5/Python.h:8,
>   from pymemcompat.h:10,
>   from _mysql.c:29:
> /System/Library/Frameworks/Python.framework/Versions/2.5/include/
> python2.5/pyconfig.h:928:1: warning: this is the location of the
> previous definition
> In file included from /usr/include/mysql/mysql.h:43,
>   from _mysql.c:40:
> /usr/include/sys/types.h:92: error: duplicate 'unsigned'
> /usr/include/sys/types.h:92: error: two or more data types in
> declaration specifiers
> In file included from _mysql.c:35:
> /usr/include/mysql/my_config.h:1030:2: warning: #warning defining
> SIZEOF_CHARP = 4
> /usr/include/mysql/my_config.h:1044:2: warning: #warning defining
> SIZEOF_LONG = 4
> In file included from /usr/include/mysql/mysql.h:43,
>   from _mysql.c:40:
> /usr/include/sys/types.h:92: error: duplicate 'unsigned'
> /usr/include/sys/types.h:92: error: two or more data types in
> declaration specifiers
> lipo: can't open input file: /var/tmp//ccg4YkGM.out (No such file or
> directory)
> error: Setup script exited with error: command 'gcc' failed with exit
> status 1

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


Re: Sub-classing unicode: getting the unicode value

2007-12-30 Thread Torsten Bronger
Hallöchen!

Gabriel Genellina writes:

> On 30 dic, 17:25, Torsten Bronger <[EMAIL PROTECTED]>
> wrote:
>
>> I sub-classed unicode in an own class called "Excerpt", and now I
>> try to implement a __unicode__ method.  In this method, I want to
>> get the actual value of the instance, i.e. the unicode string:
>
> The "actual value of the instance", given that it inherits from
> unicode, is... self.

But then it is not unicode but Excerpt which I don't want.  The idea
is to buffer the unicode representation in order to gain efficiency.
Otherwise, a lot of unicode conversion would take place.

> Are you sure you *really* want to inherit from unicode? Don't you
> want to store an unicode object as an instance attribute?

No, I need many unicode operations (concatenating, slicing, ...).

> [...]
>
>> However, unicode(super(Excerpt, self)) is also forbidden because
>> super() allows attribute access only (why by the way?).
>
> (because its purpose is to allow cooperative methods in a multiple
> inheritance hierarchy)

It would be more useful, however, if it returned full-fledged
objects.  Or if there was another way to get a full-fledged mother
object.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sub-classing unicode: getting the unicode value

2007-12-30 Thread Gabriel Genellina
On 30 dic, 19:08, Torsten Bronger <[EMAIL PROTECTED]>
wrote:
> Gabriel Genellina writes:
> > On 30 dic, 17:25, Torsten Bronger <[EMAIL PROTECTED]>
> > wrote:
>
> >> I sub-classed unicode in an own class called "Excerpt", and now I
> >> try to implement a __unicode__ method.  In this method, I want to
> >> get the actual value of the instance, i.e. the unicode string:
>
> > The "actual value of the instance", given that it inherits from
> > unicode, is... self.
>
> But then it is not unicode but Excerpt which I don't want.  The idea
> is to buffer the unicode representation in order to gain efficiency.
> Otherwise, a lot of unicode conversion would take place.

Still I don't see why you want to inherit from unicode.

> > Are you sure you *really* want to inherit from unicode? Don't you
> > want to store an unicode object as an instance attribute?
>
> No, I need many unicode operations (concatenating, slicing, ...).

If you don't redefine __add__, __iadd__, __getitem__ etc. you'll end
up with bare unicode objects anyway; Excerpt + unicode = unicode. So
you'll have to redefine all required operators; then, why inherit from
unicode at all?
An example may help:

class Excerpt(object):
  def __init__(self, value):
self.value = value # anything
  def __str__(self):
return "%s(%r)" % (self.__class__.__name__, self.value)
  def __unicode__(self):
if not hasattr(self, "_unicode"):
  self._unicode = unicode(self.value)
return self._unicode
  def __add__(self, other):
return Excerpt(unicode(self)+unicode(other))
  def __getitem__(self, index):
return Excerpt(unicode(self)[index])

py> e1 = Excerpt((1,2,3))
py> e2 = Excerpt("Hello")
py> print e1
Excerpt((1, 2, 3))
py> print unicode(e1)
(1, 2, 3)
py> e3 = e1+e2
py> print e3
Excerpt(u'(1, 2, 3)Hello')
py> e3._unicode
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'Excerpt' object has no attribute '_unicode'
py> print e3[7:10]
Excerpt(u'3)H')
py> e3._unicode
u'(1, 2, 3)Hello'

> >> However, unicode(super(Excerpt, self)) is also forbidden because
> >> super() allows attribute access only (why by the way?).
> > (because its purpose is to allow cooperative methods in a multiple
> > inheritance hierarchy)
> It would be more useful, however, if it returned full-fledged
> objects.  Or if there was another way to get a full-fledged mother
> object.

There is no such "mother object", in Python an instance is usually a
whole unique object, not an onion-like structure.

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


Re: Redirecting STDOUT using C calls.

2007-12-30 Thread Tom Gaudasinski
Christian Heimes wrote:
> Tom Gaudasinski wrote:
>   
>> Greetings,
>> I'm trying to redirect python's stdout to another location. The 
>> reason for this is that I'm embedding python in an application. Now, 
>> originally my code was developed for Linux and that did not require 
>> redirection due to the fact that every X11 application can have an 
>> STDOUT associated with it. I then proceeded to take interest in making 
>> my code portable and looked at compiling it on windows, however Win32 
>> GUI applications are not given an STDOUT by default. One has to first 
>> AllocConsole() and then reassign the handles using magic tokens 
>> "CON(IN|OUT)$" such as freopen("CONOUT$", "w", stdout). I like to keep 
>> code clean and would like to stick to the C API as much as possible.
>> 
>
> Why don't you use the appropriate C api to redirect the standard streams?
>
> freopen("filename", "w", stdout);
>
> See
> http://www.gnu.org/software/libc/manual/html_mono/libc.html#Standard-Streams
>
> Christian
>
>   
That is what I will be using in my final solution, however it makes no 
difference for exemplary purposes in the samplecode i supplied. Using 
freopen() still causes an invalid access exception exception in Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sub-classing unicode: getting the unicode value

2007-12-30 Thread Torsten Bronger
Hallöchen!

Gabriel Genellina writes:

> On 30 dic, 19:08, Torsten Bronger <[EMAIL PROTECTED]>
> wrote:
>
>> [...]
>>
>> But then it is not unicode but Excerpt which I don't want.  The
>> idea is to buffer the unicode representation in order to gain
>> efficiency.  Otherwise, a lot of unicode conversion would take
>> place.
>
> Still I don't see why you want to inherit from unicode.

Because I want to use some of its functionality and override the
rest.  And now, all I want to do is to convert the current Excerpt
object into a real unicode object that represents the same string.
Outside the object, I'd simply say unicode(my_excerpt), but this
doesn't work within the __unicode__ method of Excerpt.

> [...]
>
 However, unicode(super(Excerpt, self)) is also forbidden
 because super() allows attribute access only (why by the way?).
>>>
>>> (because its purpose is to allow cooperative methods in a
>>> multiple inheritance hierarchy)
>>
>> It would be more useful, however, if it returned full-fledged
>> objects.  Or if there was another way to get a full-fledged
>> mother object.
>
> There is no such "mother object", in Python an instance is usually
> a whole unique object, not an onion-like structure.

But the mother object could be created.

I simply see no reason why "super(MotherClass, self)[key]" must
fail, except maybe because it's harder to realise in the underlying
implementation of Python.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sub-classing unicode: getting the unicode value

2007-12-30 Thread Martin v. Löwis
> How does my object get its own value?

  def __unicode__(self):
return unicode(self)

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


Re: Sub-classing unicode: getting the unicode value

2007-12-30 Thread John Machin
On Dec 31, 8:08 am, Torsten Bronger <[EMAIL PROTECTED]>
wrote:
> Hallöchen!
>
> Gabriel Genellina writes:
> > On 30 dic, 17:25, Torsten Bronger <[EMAIL PROTECTED]>
> > wrote:
>
> >> I sub-classed unicode in an own class called "Excerpt", and now I
> >> try to implement a __unicode__ method.  In this method, I want to
> >> get the actual value of the instance, i.e. the unicode string:
>
> > The "actual value of the instance", given that it inherits from
> > unicode, is... self.
>
> But then it is not unicode but Excerpt which I don't want.  The idea
> is to buffer the unicode representation in order to gain efficiency.
> Otherwise, a lot of unicode conversion would take place.
>

I'm confused: you are subclassing unicode, and want to use several
unicode methods, but the object's value appears to be an 8-bit
string!?!?

Care to divulge the code for your __init__ method?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the best way to do dynamic imports ?

2007-12-30 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> First of thanks to all for you, especially for the quick replys.
> 
> Just need to walk the dog then I giv it a short.

Please, don't kill your dog! We're a peace-loving community here that 
respects dogs, and snakes and even trolls.

SCNR,

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


Re: Sub-classing unicode: getting the unicode value

2007-12-30 Thread Torsten Bronger
Hallöchen!

Martin v. Löwis writes:

>> How does my object get its own value?
>
>   def __unicode__(self):
> return unicode(self)

I get an endless recursion with this.

I must admit, though, that I probably overestimate the costs
connected with unicode(my_excerpt) because Gabriel is probably right
that no real conversion takes place.  A mere attribute lookup may
still be cheaper, but only very slightly.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sub-classing unicode: getting the unicode value

2007-12-30 Thread Torsten Bronger
Hallöchen!

John Machin writes:

> On Dec 31, 8:08 am, Torsten Bronger <[EMAIL PROTECTED]>
> wrote:
>
>> [...]
>>
>> But then it is not unicode but Excerpt which I don't want.  The
>> idea is to buffer the unicode representation in order to gain
>> efficiency.  Otherwise, a lot of unicode conversion would take
>> place.
>
> I'm confused: you are subclassing unicode, and want to use several
> unicode methods, but the object's value appears to be an 8-bit
> string!?!?

No, a unicode.  Never said something else ...

> Care to divulge the code for your __init__ method?

It has no __init__, only a __new__.  But I doubt that it is of much
use here:

def __new__(cls, excerpt, mode, url=None,
pre_substitutions=None, post_substitutions=None):
if mode == "NONE":
instance = unicode.__new__(cls, excerpt)
elif mode == "PRE":
preprocessed_text, original_positions, escaped_positions = \
cls.apply_pre_input_method(excerpt, url, pre_substitutions)
instance = unicode.__new__(cls, preprocessed_text)
instance.original_text = unicode(excerpt)
instance.original_positions = original_positions
instance.escaped_positions = escaped_positions
instance.post_substitutions = post_substitutions
elif mode == "POST":
postprocessed_text, original_positions, escaped_positions = \
cls.apply_post_input_method(excerpt)
instance = unicode.__new__(cls, postprocessed_text)
instance.original_positions = original_positions
instance.escaped_positions = escaped_positions
instance.original_text = excerpt.original_text
instance.post_substitutions = post_substitutions
instance.__escaped_text = None
instance.__unicode = None
return instance


Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected __metaclass__ method behavior

2007-12-30 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Dear fellow Pythonians,
|
| I just stumbled upon the following unexpected behavior:
|
| class TestType(type):
|def Foo(self): return 'TestType Foo'
| class Test(object):
|__metaclass__ = TestType
|def Foo(self): return 'Test Foo'
| t = Test()
| print t.Foo()
| print Test.Foo()
|
| This will produce:
| Test Foo
| Traceback (most recent call last):
|  File "test.py", line 8, in 
|print Test.Foo()
| TypeError: unbound method Foo() must be called with Test instance as
| first argument (got nothing instead)
|
| I can imagine why this is happening, and that there is no easy
| solution, but it is not what I was expecting.

Regardless of which Foo you expect to be called, both require an instance 
argument to be bound to the paramenter 'self'.

print Test.Foo(t) # will print same as t.Foo()

tjr



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


Re: Tab indentions on different platforms?

2007-12-30 Thread Steven D'Aprano
On Sun, 30 Dec 2007 20:33:19 +, Thorsten Kampe wrote:

> * Steven D'Aprano (Sun, 30 Dec 2007 00:37:32 -)
>> On Sat, 29 Dec 2007 15:29:25 +, Thorsten Kampe wrote:
>> > I'd personally go for spaces because:
>> > 
>> > 1. I don't like things I cannot see (control characters)
>> 
>> You can see spaces but not tabs? Your editor is pretty weird. In all
>> the editors I've every used, both spaces and tabs show up as empty
>> white space.
> 
> That's because the editor displays those invisible tab control
> characters as something they're not: spaces.

Editors display tab characters as "indent to next tab stop". That's what 
they're for, and any editor that doesn't behave that way is buggy. 

Tab characters are no more invisible than space characters. How can you 
see space characters but not tabs? Why aren't space characters invisible 
too? Why do you dislike tabs *specifically* because they are invisible, 
but like invisible spaces?



>> > 2. I never had problems with spaces but plenty with tabs
>> 
>> What problems have you had with tabs that aren't related to buggy
>> applications or users that mix tabs and spaces?
> 
> Fortunately I don't remember every incident when I stumbled about
> something weird behaving or looking. One thing I do remember is reading
> python source code (not my own) with a pager. The source code was badly
> indented. The pager was not "buggy".

Given the constraints of the typical pager one-line display, and the 
tendency of pagers I've seen to arbitrarily drop leading whitespace *of 
any sort* from the start of lines, I'd like to know how you could tell 
the indentation was wrong.

If the source code was correctly indented, but displayed wrongly by the 
pager, then of course the pager was buggy. And if the source code was 
incorrectly indented and the pager showed it as it was, well, that can 
happen with spaces too:

x = 1  
 for i in range(20):   
 x += i   
print x


No tabs there, all the indentation is done with spaces. How would you 
expect a pager to display that?



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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread Steven D'Aprano
On Sun, 30 Dec 2007 12:41:57 -0800, bukzor wrote:

> BTW, it's silly not to 'allow' globals when they're called for,
> otherwise we wouldn't need the 'global' keyword.

Nobody argues against allowing globals variables *when they're called 
for*, just pointing out that ninety-nine times out of a hundred, people 
use them when they're not called for and are positively harmful.

And according to functional programmers, they're NEVER called for.


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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread Steven D'Aprano
On Sun, 30 Dec 2007 13:34:07 -0800, Dennis Lee Bieber wrote:

> On Sun, 30 Dec 2007 12:11:50 -0800 (PST), bukzor
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> 
> 
>> Just because it's well known doesn't mean we shouldn't think about it.
>> For example, in the same list you linked, "3. Integer division" is
>> being fixed in py3k.
>>
>   IMHO -- Py3K is /breaking/ integer division... as the division of
> two integers will differ from what happens in all the other languages I
> have used... All the others, to get a floating result from dividing two
> integers requires one to explicitly convert at least one term to a float
> first

You need to use more languages :)

Prolog uses / for division and // for integer division, just like Python.

Apple's Hypertalk (and derivatives) don't distinguish between integer and 
floating point division. The / operator returns an integer result if the 
floating point result happens to be an integer.

e.g. 10.0/5.0 => 2 while 11.0/5.0 => 2.2)

I believe that Javascript behaves the same way.

According to this table here:
http://msdn2.microsoft.com/en-us/library/2hxce09y.aspx

VisualBasic uses / for floating point division and \ for integer 
division, and both JScript and Visual FoxPro don't even offer integer 
division at all.

No doubt there are others...



> -- as I would do with the current Python. The forthcoming change
> is going to require one to remember that if they want an integer result
> from two integers, they must use a different operator instead.

How is that different from needing to remember to use a different 
algorithm if you want a floating point result?



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


Re: Tab indentions on different platforms?

2007-12-30 Thread Steven D'Aprano
On Sun, 30 Dec 2007 20:41:09 +, Thorsten Kampe wrote:

> Anyway: the consequence of your well done argumentation is that
> someone editing Python code has to use a specialised editor to prevent
> screwing up tab indented code - and that's bad.

You just need to use an editor that inserts tab characters when the tab 
key is pressed, just like you use an editor that inserts s characters 
when the s key is pressed. If people didn't insist on using spaces where 
tabs are called for, there would be no problem, and you wouldn't need a 
specialized editor to prevent screwing up space-indented code.



-- 
Steven

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


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Raymond Hettinger
[bearophile]
> Here are my usages (every sub-list is
> sorted by inverted frequency usage):
>
> I use often or very often:
> groupby( iterable[, key])
> imap( function, *iterables)
> izip( *iterables)
> ifilter( predicate, iterable)
> islice( iterable, [start,] stop [, step])
>
> I use once in while:
> cycle( iterable)
> chain( *iterables)
> count( [n])
> repeat( object[, times])
>
> I have used probably one time or few times:
> starmap( function, iterable)
> tee( iterable[, n=2])
> ifilterfalse( predicate, iterable)
>
> Never used so far:
> dropwhile( predicate, iterable)
> takewhile( predicate, iterable)

Thank you for the useful and informative response.


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


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Raymond Hettinger
[Michele Simionato]
> in my code
> base I have exactly zero occurrences of takewhile and
> dropwhile, even if I tend to use the itertools quite
> often. That should be telling.

Thanks for the additional empirical evidence.

> I presume you did scans of
> large code bases and you did not find occurrences of
> takewhile and dropwhile, right?

Yes.


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


Re: What is the best way to do dynamic imports ?

2007-12-30 Thread Graham Dumpleton
On Dec 31, 1:24 am, [EMAIL PROTECTED] wrote:
> Hi list and python gurus :-)
>
> I'm playing with somemod_pythonand web development. And in me code I
> need to do som dynamic imports.
> Right now I just do a:
>
> exec 'import '+some_modulename
>
> But it seems to easy, is there a "dark side" to doing it this way?
> (memory use,processing ,etc)
> And have to I check if the modul is already loaded?
>
> Another thing is how to call my dynamic imported moduls.
> Now I use exec (as with my modules), like this:
>
> exec 'newclass = '+classname+'()'
> newclass.somefunction()
>
> Again it seems to easy. Is there a better/proper way to do it?
>
> Do anybody now a good howto or tutorial to this?
>
> Many thanks and hope you all have a happy new year :-)
>
> /marc

If using mod_python, you should use mod_python's own dynamic module
importer. See the documentation for mod_python.apache.import_module()
in:

  http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html

There is no need to use __import__ directly. By using mod_python's way
of doing things you can benefit from automatic module reloading
provided certain constraints met.

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


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Raymond Hettinger
[Marc 'BlackJack' Rintsch]
> I use both functions from time to time.
> One "recipe" is extracting blocks from text files that are delimited by a
> special start and end line.
>
> def iter_block(lines, start_marker, end_marker):
>     return takewhile(lambda x: not x.startswith(end_marker),
>                      dropwhile(lambda x: not x.startswith(start_marker),
>                                lines))

Glad to hear this came from real code instead of being contrived for
this discussion.  Thanks for the contribution.

Looking at the code fragment, I wondered how that approach compared to
others in terms of being easy to write, self-evidently correct,
absence of awkward constructs, and speed.  The lambda expressions are
not as fast as straight C calls or in-lined code, and they also each
require a 'not' to invert the startswith condition.  The latter is a
bit problematic in that it is a bit awkward, and it is less self-
evident whether the lines with the markers are included or excluded
from the output (the recipe may in fact be buggy -- the line with the
start marker is included and the line with the end marker is
excluded). Your excellent choice of indentation helps improve the
readability of the nested takewhile/dropwhile calls.

In contrast, the generator version is clearer about whether the start
and end marker lines get included and is easily modified if you want
to change that choice.  It is easy to write and more self-evident
about how it handles the end cases.  Also, it avoids the expense of
the lambda function calls and the awkwardness of the 'not' to invert
the sense of the test:

def iter_block(lines, start_marker, end_marker):
inblock = False
for line in lines:
if inblock:
if line.startswith(end_marker):
break
yield line
elif line.startswith(start_marker):
yield line
inblock = True

And, of course, for this particular application, an approach based on
regular expressions makes short work of the problem and runs very
fast:

re.search('(^beginmark.*)^endmark', textblock, re.M |
re.S).group(1)


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


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Raymond Hettinger
FWIW, here is an generator version written without the state flag:

def iter_block(lines, start_marker, end_marker):
lines = iter(lines)
for line in lines:
if line.startswith(start_marker):
yield line
break
for line in lines:
if line.startswith(end_marker):
return
yield line

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


Re: Tab indentions on different platforms?

2007-12-30 Thread Ben Finney
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> On Sun, 30 Dec 2007 20:41:09 +, Thorsten Kampe wrote:
> 
> > Anyway: the consequence of your well done argumentation is that
> > someone editing Python code has to use a specialised editor to prevent
> > screwing up tab indented code - and that's bad.
> 
> You just need to use an editor that inserts tab characters when the
> tab key is pressed, just like you use an editor that inserts s
> characters when the s key is pressed.

No, that's not all you need to do. You also need to keep your code
away from the majority of programmers, who use their default editor in
its default settings, and who expect that horizontal whitespace is
produced by the U+0020 space character (even if they don't know the
specifics of the character coding).

Saying that the tabs-only argument and the spaces-only argument are of
equal value is philosophically true, but practically worthless.
They're of equal value *only* in isolated environments where you can
control the expectations of *every* programmer who will *ever* edit
the file.

To form an indentation policy based only on hypothetical
fully-controlled isolated environments is foolish, to say the least.

-- 
 \  "If you can't beat them, arrange to have them beaten."  -- |
  `\ George Carlin |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


evolution-python

2007-12-30 Thread eloi-ribeiro.blogspot.com
Hi everyone,

I would like to use a python script to export (save as...) all my
contacts in Evolution to VCard format (.vcf). I am a beginner so I
don't knock how to use evolution-python module. The second part of the
script would be to make inserts to a database, at these second part, I
think I can menage my self.

Thanks in advance and happy new year to everyone,

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


Help please with code to find and move files.

2007-12-30 Thread inFocus
Hello,

I am new to python and wanted to write something for myself where
after inputing two words it would search entire drive and when finding
both names in files name would either copy or move thoe files to a
specified directory.

But couple of attempts did not work as desired this is one of them.
Could someone help fix it or maybe give a better example.

 Thank you very much.


import os, os.path, shutil

path = r"c:\\"
dest_file = 'C:\\files'
name_search = raw_input('Please enter name searchs : ').split()
dup = []


for root, dirs, files in os.walk(path):
for name in files:
file_name = os.path.join(root, name)
if (name_search[0] in file_name) and (name_search[1]
in file_name):
#if os.path.join(root, name) in dest_file:
if file_name in dup:
break
else:
print "copied %s to %s" % (name,
dest_file)
shutil.copy(os.path.join(root, name),
dest_file)
dup.append(file_name)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help please with code to find and move files.

2007-12-30 Thread infixum

> path = r"c:\\"

I don't know if this is the whole problem, but this line should read
r'c:\' (one backslash).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Paul Hankin
On Dec 31, 1:25 am, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> FWIW, here is an generator version written without the state flag:
>
>     def iter_block(lines, start_marker, end_marker):
>         lines = iter(lines)
>         for line in lines:
>             if line.startswith(start_marker):
>                 yield line
>                 break
>         for line in lines:
>             if line.startswith(end_marker):
>                 return
>             yield line

Here's a (stateful) version that generates all blocks...

import itertools

def iter_blocks(lines, start_marker, end_marker):
inblock = [False]
def line_in_block(line):
inblock[0] = inblock[0] and not line.startswith(end_marker)
inblock[0] = inblock[0] or line.startswith(start_marker)
return inblock[0]
return (block for is_in_block, block in
itertools.groupby(lines, line_in_block) if is_in_block)

If you just want the first block (as the original code did), you can
just take it...

for line in iter_blocks(lines, start_marker, end_marker).next():
... process lines of first block.

I'm not happy about the way the inblock state has to be a 1-element
list to avoid the non-local problem. Is there a nicer way to code it?
Otherwise, I quite like this code (if I do say so myself) as it neatly
separates out the logic of whether you're inside a block or not from
the code that yields blocks and lines. I'd say it was quite readable
if you're familiar with groupby.

And back on topic... I use itertools regularly (and have a functional
background), but have never needed takewhile or dropwhile. I'd be
happy to see them deprecated.

--
Paul Hankin

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


Re: Help please with code to find and move files.

2007-12-30 Thread inFocus
On Sun, 30 Dec 2007 18:42:50 -0800 (PST), infixum <[EMAIL PROTECTED]>
wrote:

>
>> path = r"c:\\"
>
>I don't know if this is the whole problem, but this line should read
>r'c:\' (one backslash).


after changing i got this

path = r"c:\"
^
SyntaxError: EOL while scanning single-quoted string

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


Re: Help please with code to find and move files.

2007-12-30 Thread infixum

>
> after changing i got this
>
>     path = r"c:\"
>                 ^
> SyntaxError: EOL while scanning single-quoted string

Sorry about that.  You can't end with a backslash - my bad.  I just
tried this in the interpreter and 'c:' works.

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


Re: Help please with code to find and move files.

2007-12-30 Thread John Machin
On Dec 31, 1:04 pm, [EMAIL PROTECTED] wrote:
> Hello,
>
> I am new to python and wanted to write something for myself where
> after inputing two words it would search entire drive and when finding
> both names in files name would either copy or move thoe files to a
> specified directory.
>
> But couple of attempts did not work as desired this is one of them.

Care to provide some more details than "did not work as desired"? Do
you think the problem is in the finding or in the copying? I've given
some comments below, but you really need to think through what "as
desired" means ...

Suppose your search words are "foo" and "bar", that C:\files is an
empty folder, and the following 3 files exist:
C:\a\foobar.txt
C:\b\foobar.txt
C:\b\barfoo.txt

What do you want to happen the first time you run the script? ... if
you run it a second time? If it's your intention not to make a copy of
C:\b\foobar.txt (because its "basename" is the same as that of C:\a
\foobar.txt), consider the desirability of warning yourself when this
situation happens.

> Could someone help fix it or maybe give a better example.
>
>  Thank you very much.
>
> import os, os.path, shutil
>
> path = r"c:\\"

Leave out the "r"; you are getting TWO backslashes:

>>> path = r"c:\\"
>>> len(path)
4
>> import os
>>> wkr = os.walk('rd:\\')
>>> wkr.next()
Traceback (most recent call last):
  File "", line 1, in 
StopIteration
# Nothing inside your for statement would be executed
>>> wkr = os.walk('d:\\')
>>> wkr.next()
('d:\\', a list of folders, a list of files)


> dest_file = 'C:\\files'

Presumably that would be better named dest_dir ...

> name_search = raw_input('Please enter name searchs : ').split()
> dup = []

In the (unlikely) event that an in-memory structure with no knowledge
of what happened on previous runs will do what you really want to do,
then consider a set instead of a list.

>
> for root, dirs, files in os.walk(path):
>     for name in files:
>                 file_name = os.path.join(root, name)
>                 if (name_search[0] in file_name) and (name_search[1]
> in file_name):
>                         #if os.path.join(root, name) in dest_file:
>                         if file_name in dup:

What do you really intend to do here? dup contains the FULL PATH of
each file that you have found; if you come across another instance of
one of those, either os.walk is horribly broken or your filesystem has
a loop in its directory structure.

If you really mean "am I about to try to copy over the top of an
existing file", attack the problem head-on: make the full path of the
file you are about to try to create, and use os.path.exists on it.

>                                 break

Why break?

You also want to avoid trying to copy files in the backup
("dest_file") directory, perhaps including ones that you have just
copied there. Try a simple test
if root == dest_file:
continue
very early in your outer loop. It's probably a good idea to wrap
os.path.abspath() around root and destfile.

>                         else:
>                                 print "copied %s to %s" % (name,
> dest_file)
>                                 shutil.copy(os.path.join(root, name),
> dest_file)

You may prefer the results of copy2 to those of copy.

>                                 dup.append(file_name)

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


ElementTree should parse string and file in teh same way

2007-12-30 Thread Peter Pei
One bad design about elementtree is that it has different ways parsing a 
string and a file, even worse they return different objects:
1) When you parse a file, you can simply call parse, which returns a 
elementtree, on which you can then apply xpath;
2) To parse a string (xml section), you can call XML or fromstring, but both 
return element instead of elementtree. This alone is bad. To make it worse, 
you have to create an elementtree from this element before you can utilize 
xpath.


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


Re: Help please with code to find and move files.

2007-12-30 Thread inFocus
On Sun, 30 Dec 2007 19:29:38 -0800 (PST), John Machin
<[EMAIL PROTECTED]> wrote:

>On Dec 31, 1:04 pm, [EMAIL PROTECTED] wrote:
>> Hello,
>>
>> I am new to python and wanted to write something for myself where
>> after inputing two words it would search entire drive and when finding
>> both names in files name would either copy or move thoe files to a
>> specified directory.
>>
>> But couple of attempts did not work as desired this is one of them.
>
>Care to provide some more details than "did not work as desired"? Do
>you think the problem is in the finding or in the copying? I've given
>some comments below, but you really need to think through what "as
>desired" means ...
>
>Suppose your search words are "foo" and "bar", that C:\files is an
>empty folder, and the following 3 files exist:
>C:\a\foobar.txt
>C:\b\foobar.txt
>C:\b\barfoo.txt
>
>What do you want to happen the first time you run the script? ... if
>you run it a second time? If it's your intention not to make a copy of
>C:\b\foobar.txt (because its "basename" is the same as that of C:\a
>\foobar.txt), consider the desirability of warning yourself when this
>situation happens.
>
>> Could someone help fix it or maybe give a better example.
>>
>>  Thank you very much.
>>
>> import os, os.path, shutil
>>
>> path = r"c:\\"
>
>Leave out the "r"; you are getting TWO backslashes:
>
 path = r"c:\\"
 len(path)
>4
>>> import os
 wkr = os.walk('rd:\\')
 wkr.next()
>Traceback (most recent call last):
>  File "", line 1, in 
>StopIteration
># Nothing inside your for statement would be executed
 wkr = os.walk('d:\\')
 wkr.next()
>('d:\\', a list of folders, a list of files)
>
>
>> dest_file = 'C:\\files'
>
>Presumably that would be better named dest_dir ...
>
>> name_search = raw_input('Please enter name searchs : ').split()
>> dup = []
>
>In the (unlikely) event that an in-memory structure with no knowledge
>of what happened on previous runs will do what you really want to do,
>then consider a set instead of a list.
>
>>
>> for root, dirs, files in os.walk(path):
>>     for name in files:
>>                 file_name = os.path.join(root, name)
>>                 if (name_search[0] in file_name) and (name_search[1]
>> in file_name):
>>                         #if os.path.join(root, name) in dest_file:
>>                         if file_name in dup:
>
>What do you really intend to do here? dup contains the FULL PATH of
>each file that you have found; if you come across another instance of
>one of those, either os.walk is horribly broken or your filesystem has
>a loop in its directory structure.
>
>If you really mean "am I about to try to copy over the top of an
>existing file", attack the problem head-on: make the full path of the
>file you are about to try to create, and use os.path.exists on it.
>
>>                                 break
>
>Why break?
>
>You also want to avoid trying to copy files in the backup
>("dest_file") directory, perhaps including ones that you have just
>copied there. Try a simple test
>if root == dest_file:
>continue
>very early in your outer loop. It's probably a good idea to wrap
>os.path.abspath() around root and destfile.
>
>>                         else:
>>                                 print "copied %s to %s" % (name,
>> dest_file)
>>                                 shutil.copy(os.path.join(root, name),
>> dest_file)
>
>You may prefer the results of copy2 to those of copy.
>
>>                                 dup.append(file_name)
>
>HTH,
>John

John,

What I was trying to do is find files that are scattered all over my
hard drive that contain similar two words in them like bar and foo 
and move them to one desired location removing from where they were
originally.  The did not work as desired were attempts when it would
attempt to read and write to the same location.so i would get an error
saying that source and destination were  the same.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread bukzor
On Dec 30, 3:34 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 30 Dec 2007 12:41:57 -0800, bukzor wrote:
> > BTW, it's silly not to 'allow' globals when they're called for,
> > otherwise we wouldn't need the 'global' keyword.
>
> Nobody argues against allowing globals variables *when they're called
> for*, just pointing out that ninety-nine times out of a hundred, people
> use them when they're not called for and are positively harmful.
>
> And according to functional programmers, they're NEVER called for.
>
> --
> Steven.


I think you struck at the heart of the matter earlier when you noted
that this is the simplest way to declare a static variable in python.
Using the 'global' keyword is the other way, and is much more
explicit, and much more widely used. I also see this as the main use
of the 'notlocal' keyword to be introduced in py3k (it also fixes the
example given by Istvan above).

If the main value of this behavior is to declare a static variable, it
seems like an argument to create a more explicit syntax for static
variables. In the example above, the function only needed a static
integer, but created a one-length list instead because this quirk
doesn't work for immutable values.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Choosing a new language

2007-12-30 Thread George Neuner
On Fri, 28 Dec 2007 22:07:12 -0800 (PST), [EMAIL PROTECTED] wrote:

>Ada is airline/dod blessed.

Airline blessed maybe.  The DOD revoked its Ada only edict because
they couldn't find enough Ada programmers.  AFAIK, Ada is still the
preferred language, but it is not required.

George
--
for email reply remove "/" from address
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help please with code to find and move files.

2007-12-30 Thread John Machin
On Dec 31, 2:44 pm, [EMAIL PROTECTED] wrote:
> On Sun, 30 Dec 2007 19:29:38 -0800 (PST), John Machin
>
>
>
>
>
> <[EMAIL PROTECTED]> wrote:
> >On Dec 31, 1:04 pm, [EMAIL PROTECTED] wrote:
> >> Hello,
>
> >> I am new to python and wanted to write something for myself where
> >> after inputing two words it would search entire drive and when finding
> >> both names in files name would either copy or move thoe files to a
> >> specified directory.
>
> >> But couple of attempts did not work as desired this is one of them.
>
> >Care to provide some more details than "did not work as desired"? Do
> >you think the problem is in the finding or in the copying? I've given
> >some comments below, but you really need to think through what "as
> >desired" means ...
>
> >Suppose your search words are "foo" and "bar", that C:\files is an
> >empty folder, and the following 3 files exist:
> >C:\a\foobar.txt
> >C:\b\foobar.txt
> >C:\b\barfoo.txt
>
> >What do you want to happen the first time you run the script? ... if
> >you run it a second time? If it's your intention not to make a copy of
> >C:\b\foobar.txt (because its "basename" is the same as that of C:\a
> >\foobar.txt), consider the desirability of warning yourself when this
> >situation happens.
>
> >> Could someone help fix it or maybe give a better example.
>
> >>  Thank you very much.
>
> >> import os, os.path, shutil
>
> >> path = r"c:\\"
>
> >Leave out the "r"; you are getting TWO backslashes:
>
>  path = r"c:\\"
>  len(path)
> >4
> >>> import os
>  wkr = os.walk('rd:\\')
>  wkr.next()
> >Traceback (most recent call last):
> >  File "", line 1, in 
> >StopIteration
> ># Nothing inside your for statement would be executed
>  wkr = os.walk('d:\\')
>  wkr.next()
> >('d:\\', a list of folders, a list of files)
>
> >> dest_file = 'C:\\files'
>
> >Presumably that would be better named dest_dir ...
>
> >> name_search = raw_input('Please enter name searchs : ').split()
> >> dup = []
>
> >In the (unlikely) event that an in-memory structure with no knowledge
> >of what happened on previous runs will do what you really want to do,
> >then consider a set instead of a list.
>
> >> for root, dirs, files in os.walk(path):
> >>     for name in files:
> >>                 file_name = os.path.join(root, name)
> >>                 if (name_search[0] in file_name) and (name_search[1]
> >> in file_name):
> >>                         #if os.path.join(root, name) in dest_file:
> >>                         if file_name in dup:
>
> >What do you really intend to do here? dup contains the FULL PATH of
> >each file that you have found; if you come across another instance of
> >one of those, either os.walk is horribly broken or your filesystem has
> >a loop in its directory structure.
>
> >If you really mean "am I about to try to copy over the top of an
> >existing file", attack the problem head-on: make the full path of the
> >file you are about to try to create, and use os.path.exists on it.
>
> >>                                 break
>
> >Why break?
>
> >You also want to avoid trying to copy files in the backup
> >("dest_file") directory, perhaps including ones that you have just
> >copied there. Try a simple test
> >    if root == dest_file:
> >        continue
> >very early in your outer loop. It's probably a good idea to wrap
> >os.path.abspath() around root and destfile.
>
> >>                         else:
> >>                                 print "copied %s to %s" % (name,
> >> dest_file)
> >>                                 shutil.copy(os.path.join(root, name),
> >> dest_file)
>
> >You may prefer the results of copy2 to those of copy.
>
> >>                                 dup.append(file_name)
>
> >HTH,
> >John
>
> John,
>
> What I was trying to do is find files that are scattered all over my
> hard drive that contain similar two words in them like bar and foo
> and move them to one desired location removing from where they were
> originally.  The did not work as desired were attempts when it would
> attempt to read and write to the same location.so i would get an error
> saying that source and destination were  the same.- Hide quoted text -
>
> - Show quoted text -

The script that you showed would not have found any files to move/
copy, as "infixum" and I have pointed out.

Imagine that you were trying to help someone with a Python problem ...
would you not like them to tell you (with some precision) what they
were trying to do, what was the script that they actually ran, what
the precise result (including stack trace and error message if any)
was? Or do you like playing guessing games?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help please with code to find and move files.

2007-12-30 Thread inFocus
On Sun, 30 Dec 2007 20:49:29 -0800 (PST), John Machin
<[EMAIL PROTECTED]> wrote:

>On Dec 31, 2:44 pm, [EMAIL PROTECTED] wrote:
>> On Sun, 30 Dec 2007 19:29:38 -0800 (PST), John Machin
>>
>>
>>
>>
>>
>> <[EMAIL PROTECTED]> wrote:
>> >On Dec 31, 1:04 pm, [EMAIL PROTECTED] wrote:
>> >> Hello,
>>
>> >> I am new to python and wanted to write something for myself where
>> >> after inputing two words it would search entire drive and when finding
>> >> both names in files name would either copy or move thoe files to a
>> >> specified directory.
>>
>> >> But couple of attempts did not work as desired this is one of them.
>>
>> >Care to provide some more details than "did not work as desired"? Do
>> >you think the problem is in the finding or in the copying? I've given
>> >some comments below, but you really need to think through what "as
>> >desired" means ...
>>
>> >Suppose your search words are "foo" and "bar", that C:\files is an
>> >empty folder, and the following 3 files exist:
>> >C:\a\foobar.txt
>> >C:\b\foobar.txt
>> >C:\b\barfoo.txt
>>
>> >What do you want to happen the first time you run the script? ... if
>> >you run it a second time? If it's your intention not to make a copy of
>> >C:\b\foobar.txt (because its "basename" is the same as that of C:\a
>> >\foobar.txt), consider the desirability of warning yourself when this
>> >situation happens.
>>
>> >> Could someone help fix it or maybe give a better example.
>>
>> >>  Thank you very much.
>>
>> >> import os, os.path, shutil
>>
>> >> path = r"c:\\"
>>
>> >Leave out the "r"; you are getting TWO backslashes:
>>
>>  path = r"c:\\"
>>  len(path)
>> >4
>> >>> import os
>>  wkr = os.walk('rd:\\')
>>  wkr.next()
>> >Traceback (most recent call last):
>> >  File "", line 1, in 
>> >StopIteration
>> ># Nothing inside your for statement would be executed
>>  wkr = os.walk('d:\\')
>>  wkr.next()
>> >('d:\\', a list of folders, a list of files)
>>
>> >> dest_file = 'C:\\files'
>>
>> >Presumably that would be better named dest_dir ...
>>
>> >> name_search = raw_input('Please enter name searchs : ').split()
>> >> dup = []
>>
>> >In the (unlikely) event that an in-memory structure with no knowledge
>> >of what happened on previous runs will do what you really want to do,
>> >then consider a set instead of a list.
>>
>> >> for root, dirs, files in os.walk(path):
>> >>     for name in files:
>> >>                 file_name = os.path.join(root, name)
>> >>                 if (name_search[0] in file_name) and (name_search[1]
>> >> in file_name):
>> >>                         #if os.path.join(root, name) in dest_file:
>> >>                         if file_name in dup:
>>
>> >What do you really intend to do here? dup contains the FULL PATH of
>> >each file that you have found; if you come across another instance of
>> >one of those, either os.walk is horribly broken or your filesystem has
>> >a loop in its directory structure.
>>
>> >If you really mean "am I about to try to copy over the top of an
>> >existing file", attack the problem head-on: make the full path of the
>> >file you are about to try to create, and use os.path.exists on it.
>>
>> >>                                 break
>>
>> >Why break?
>>
>> >You also want to avoid trying to copy files in the backup
>> >("dest_file") directory, perhaps including ones that you have just
>> >copied there. Try a simple test
>> >    if root == dest_file:
>> >        continue
>> >very early in your outer loop. It's probably a good idea to wrap
>> >os.path.abspath() around root and destfile.
>>
>> >>                         else:
>> >>                                 print "copied %s to %s" % (name,
>> >> dest_file)
>> >>                                 shutil.copy(os.path.join(root, name),
>> >> dest_file)
>>
>> >You may prefer the results of copy2 to those of copy.
>>
>> >>                                 dup.append(file_name)
>>
>> >HTH,
>> >John
>>
>> John,
>>
>> What I was trying to do is find files that are scattered all over my
>> hard drive that contain similar two words in them like bar and foo
>> and move them to one desired location removing from where they were
>> originally.  The did not work as desired were attempts when it would
>> attempt to read and write to the same location.so i would get an error
>> saying that source and destination were  the same.- Hide quoted text -
>>
>> - Show quoted text -
>
>The script that you showed would not have found any files to move/
>copy, as "infixum" and I have pointed out.
>
>Imagine that you were trying to help someone with a Python problem ...
>would you not like them to tell you (with some precision) what they
>were trying to do, what was the script that they actually ran, what
>the precise result (including stack trace and error message if any)
>was? Or do you like playing guessing games?


I am sorry i thought I did say what I was tryng to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


how to connect to a remote machine using python........

2007-12-30 Thread vinoj davis
hi all,  i am new to python, can anyone tell me how can i connect to a remote machine using python and execute commands.Thanking you..Regards,     ---ViNOJ DAViS---


   Chat on a cool, new interface. No download required. Click here.

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

Re: how to connect to a remote machine using python........

2007-12-30 Thread Shane Geiger
Some python ssh packages are available if you are wanting to execute
commands on a machine that has ssh.  ssh servers are available for
windows, but they aren't necessarily so well supported.

Here's a simple approach that works on ssh servers:

import commands
hostname = commands.getoutput('ssh [EMAIL PROTECTED]  hostname')
print hostname

Alternatively, you could run a Python-based web server from a simple
script like the one below, allowing you to execute a few commands
anonymously.  This is the sort of thing you might and to do on LANs for
a windows computer you don't want to run SSH on. 



"""
This is a small Web server that will allow remote clients to run
commands on this server and get the output.

Usage:  python 

Client Usage:
lynx http://localhost:8000/hostname

On Windows this can be installed as a service with WinServ:  winserv
install py_http_serv C:\Python23\python.exe C:\_admin\httpd_monitor.py
 - make sure that this service is set to restart the process if it fails


Things I could improve:  I could have it download a new dict of commands
which would have to be GPG signed.
  - I could add a feature that would allow it to give me it's public gpg
key...and I could encrypt messages for it.

Perhaps I could even have it push out a shell of some sort.

"""

import BaseHTTPServer, shutil, os
from cStringIO import StringIO
import os

class MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
# HTTP paths we serve, and what commandline-commands we serve them with

# Note: I could run smtp commands...and pop commands to verify that
the mail server is still working

import os
if os.name == 'nt':
cmds = {
'/ping': 'ping www.google.com',
'/netstat' : 'netstat -a',
'/tracert' : 'tracert www.thinkware.se',
'/srvstats' : 'net statistics server',
'/wsstats' : 'net statistics workstation',
'/route' : 'route print',
'/unlock_sgeiger' : 'net user sgeiger /active:yes',  # maybe I
should make that more cryptic
'/lssvc' : 'lssvc.exe',  # list processes
'/sclist' : 'sclist',# list processes (resource kit)
'/exchange_status' : 'lssvc | grep MSExch',
'/diruse' : 'diruse',
'/now' : 'now',
'/uptime' : 'uptime',
}
elif os.name == 'posix': # includes Mac, Linux
cmds = {
'/hostname' : 'hostname',
'/ping': 'ping -c 3 www.google.com',
'/netstat' : 'netstat -rn',
'/tracert' : 'traceroute www.google.com',
#'/srvstats' : 'net statistics server',
#'/wsstats' : 'net statistics workstation',
'/route' : 'route -rn',   # this might be different on the
mac...
}


def do_GET(self):
""" Serve a GET request. """
f = self.send_head()
if f:
f = StringIO()
machine = os.popen('hostname').readlines()[0]
if self.path == '/':
heading = "Select a command to run on %s" % (machine)
body = (self.getMenu() +
"The screen won't update until the select "
"command has finished.  Please be patient.")
else:
heading = "Execution of ''%s'' on %s" %
(self.cmds[self.path], machine)
cmd = self.cmds[self.path]
body = 'Main Menu%s\n' %
os.popen(cmd).read()
# Translation CP437 -> Latin 1 needed for Swedish Windows.
#body = body.decode('cp437').encode('latin1')
f.write("%s\n" % heading)
f.write("%s\n" % (heading))
f.write(body)
f.write("\n")
f.seek(0)
self.copyfile(f, self.wfile)
f.close()
return f

def do_HEAD(self):
""" Serve a HEAD request. """
f = self.send_head()
if f:
f.close()

def send_head(self):
path = self.path
if not path in ['/'] + self.cmds.keys():
head = 'Command "%s" not found.  Try one of these:' %path
msg = head + self.getMenu()
self.send_error(404, msg)
return None
self.send_response(200)
self.send_header("Content-type", 'text/html')
self.end_headers()
f = StringIO()
f.write("A test %s\n" % self.path)
f.seek(0)
return f

def getMenu(self):
keys = self.cmds.keys()
keys.sort()
msg = []
for k in keys:
msg.append('%s => %s' %(k, k,
self.cmds[k]))
msg.append('')
return "\n".join(msg)

def copyfile(self, source, outputfile):
shutil.copyfileobj(source, outputfile)

def main(HandlerClass = MyHTTPRequestHandler,
 ServerClass = BaseHTTPServer.HTTPServer):
BaseHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
main()



vinoj davis wrote:
> hi all,
>   i am new to python, can

Re: Brussels Python Interest/Users Group

2007-12-30 Thread David Van Mosselbeen
on Sat, 29 Dec 2007 04:51:12 -0800 (PST), seb <[EMAIL PROTECTED]> wrote:
> Hi Pythonistas,
>
> Is anyone interested in forming a Brussels(Belgium) area Python User
> Group ? I am not aware of any python focused group in this area.
>
> Language could be whatever fits the bill (English/French/Dutch/...)
> Focus would be python, ironpython/silverlight, scipy, ORMs, web
> frameworks, and whatever is of interest to us.
>
> Interested ? Please post on this thread.
>
> Seb

I'm interested to get some advises at some python user group. English,
Dutch and French is not a problem for me.

-- 
David Van Mosselbeen
http://dvm.zapto.org:8080/
-- 
http://mail.python.org/mailman/listinfo/python-list


help building python installer

2007-12-30 Thread abhishek
Hello group,

I have been able to successfully compile python 2.5.1 using MSVC 8
compiler .
Now i want to build an msi installer out of this. What's procedure
that I should follow for this ??


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


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Matt Nordhoff
Raymond Hettinger wrote:
> I'm considering deprecating these two functions and would like some
> feedback from the community or from people who have a background in
> functional programming.
> 
> * I'm concerned that use cases for the two functions are uncommon and
> can obscure code rather than clarify it.
> 
> * I originally added them to itertools because they were found in
> other functional languages and because it seemed like they would serve
> basic building blocks in combination with other itertools allow
> construction of a variety of powerful, high-speed iterators.  The
> latter may have been a false hope -- to date, I've not seen good
> recipes that depend on either function.
> 
> * If an always true or always false predicate is given, it can be hard
> to break-out of the function once it is running.
> 
> * Both functions seem simple and basic until you try to explain them
> to someone else.  Likewise, when reading code containing dropwhile(),
> I don't think it is self-evident that dropwhile() may have a lengthy
> start-up time.
> 
> * Since itertools are meant to be combined together, the whole module
> becomes easier to use if there are fewer tools to choose from.
> 
> These thoughts reflect my own experience with the itertools module.
> It may be that your experience with them has been different.  Please
> let me know what you think.
> 
> Raymond

FWIW, Google Code Search shows a few users:



Do any of them make good use of them?
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for web...

2007-12-30 Thread David Van Mosselbeen
on Tue, 25 Dec 2007 20:42:03 -0800 (PST), [EMAIL PROTECTED] <[EMAIL PROTECTED]> 
wrote:
>
> Hi everyone,
>
> I have to develop a web based enterprise application for my final year
> project. Since i am interested in open source, i searched the net.
> Almost 90% of them were PHP and MySQL. Cant we use python for that ? I
> tried several sites, but there is not enough tutorial for beginners
> [mod_python, PSP etc]. I couldnt find any detailed book, not even a
> single book :( All the python books are covering only CGI part)
>
> Any suggestions? Any recommended book?
>
> Execuse my English.
>
> Thushanthan.

You can also take a look to `webpy` and `cherrypy`. These where not yet
mentioned.

-- 
David Van Mosselbeen
http://dvm.zapto.org:8080/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread Steven D'Aprano
On Sun, 30 Dec 2007 20:00:14 -0800, bukzor wrote:

> I think you struck at the heart of the matter earlier when you noted
> that this is the simplest way to declare a static variable in python.
> Using the 'global' keyword is the other way, and is much more explicit, 
> and much more widely used. I also see this as the main use of the
> 'notlocal' keyword to be introduced in py3k (it also fixes the example
> given by Istvan above).

There doesn't appear to be any reference to a "notlocal" keyword in 
Python 3 that I can find. Have I missed something? It sounds like an 
April Fool's gag to me. Do you have a reference to a PEP or other 
official announcement?



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


Re: Help please with code to find and move files.

2007-12-30 Thread inFocus
On Sun, 30 Dec 2007 22:52:32 -0800, Dennis Lee Bieber
<[EMAIL PROTECTED]> wrote:

>On Sun, 30 Dec 2007 23:58:17 -0500, [EMAIL PROTECTED] declaimed the
>following in comp.lang.python:
>
>
>> I am sorry i thought I did say what I was tryng to do.
>
>   The only thing I picked up from the thread is that you attempted to
>move any file, whose name contained -- in any order/position -- two
>specific substrings, from some specified source directory tree to a
>single specified directory.
>
>   Among the unknowns: what happens if two source directories have
>files with identical names! Does the second overwrite the first? Does
>the second NOT get moved? Should the second have the name modified with
>a suffix count?
>
>   a/something.wht ->  dest/something.wht
>   b/something.wht ->  ?
>   1) 
> replace the first something.wht
>   
> (thereby losing a/something.wht)
>   2) 
> don't move -- leaving 
>   
> b/something.wht unmoved
>   3) 
> rename as
>   
> dest/something1.wht
>
>   Neither do I have any idea of what type of problem you really
>encountered (you'll have to forgive me, but I do not intend to try
>running your script, on my system, given that I do not know what the
>effects, in the end, are to be).
>
>   The closest to what you seem to ask, that I've created in the past,
>is a task to identify potential duplicate files (I have a large number
>of downloaded images). Note the date -- I think it predated os.walk()
>
>-=-=-=-=-=-=-
>#
>#  DupCheck.py --  Scans a directory and all subdirectories
>#  for duplicate file names, reporting conflicts
>#  March 22 1998   dl bieber <[EMAIL PROTECTED]>
>#
>
>import os
>import sys
>import string
>from stat import *
>
>Files = {}
>
>def Scan_Dir(cd):
>   global Files, logfile
>
>   cur_files = os.listdir(cd)
>   cur_files.sort()
>   for f in cur_files:
>   fib = os.stat("%s\\%s" % (cd, f))
>   if S_ISDIR(fib[ST_MODE]):
>   Scan_Dir("%s\\%s" % (cd, f))
>   elif S_ISREG(fib[ST_MODE]):
>   if Files.has_key(string.lower(f)):
>   (aSize, aDir) = Files[string.lower(f)]
>   if fib[ST_SIZE] == aSize:
>   logfile.write(
>   "*  Possible Duplicate 
> File: %s\n" % (f))
>   logfile.write(
>   "   %s\t%s\n" % 
> (fib[ST_SIZE], cd))
>   logfile.write(
>   "   %s\t%s\n\n" % 
> (Files[string.lower(f)]))
>   else:
>   Files[string.lower(f)] = (fib[ST_SIZE], cd)
>   else:
>   logfile.write(
>   "*  SKIPPED  Not File or Dir: %s\n\n" % (f))
>
>
>if __name__ == "__main__":
>   Cur_Dir = raw_input("Root Directory -> ")
>   Log_To = raw_input("Log File -> ")
>
>   if Log_To:
>   logfile = open(Log_To, "w")
>   else:
>   logfile = sys.stdout
>
>   Scan_Dir(Cur_Dir)
>
>   if Log_To:
>   logfile.close()
>-=-=-=-=-=-

I am sorry if I was not clear in what I was trying to achieve. All I
wanted was simple way to achieve what windows does when you use search
for Files or Folders,  and all the files that mach two words like foo
and bar in the file name to be moved or copied to a specified folder,
duplicates should not be copied just skipped.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree should parse string and file in teh same way

2007-12-30 Thread Paddy
On Dec 31, 3:42 am, "Peter Pei" <[EMAIL PROTECTED]> wrote:
> One bad design about elementtree is that it has different ways parsing a
> string and a file, even worse they return different objects:
> 1) When you parse a file, you can simply call parse, which returns a
> elementtree, on which you can then apply xpath;
> 2) To parse a string (xml section), you can call XML or fromstring, but both
> return element instead of elementtree. This alone is bad. To make it worse,
> you have to create an elementtree from this element before you can utilize
> xpath.

I haven't tried this, but you should be able to wrap your text string
so that it looks like a file using the stringio module and pass that
to elementtree:

http://blog.doughellmann.com/2007/04/pymotw-stringio-and-cstringio.html

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


Re: Bizarre behavior with mutable default arguments

2007-12-30 Thread Gabriel Genellina
En Mon, 31 Dec 2007 05:01:51 -0200, Steven D'Aprano  
<[EMAIL PROTECTED]> escribió:
> On Sun, 30 Dec 2007 20:00:14 -0800, bukzor wrote:
>
>> I also see this as the main use of the
>> 'notlocal' keyword to be introduced in py3k (it also fixes the example
>> given by Istvan above).
>
> There doesn't appear to be any reference to a "notlocal" keyword in
> Python 3 that I can find. Have I missed something? It sounds like an
> April Fool's gag to me. Do you have a reference to a PEP or other
> official announcement?

No, it's a real keyword in python 3, but it's spelled "nonlocal".
See http://www.python.org/dev/peps/pep-3104/

-- 
Gabriel Genellina

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


Re: Push to Make (Single Pole) Button running a loop

2007-12-30 Thread Hendrik van Rooyen
 "Jon Todd"  wrote:

>I'd like to have a button that when pressed executes a loop (this could be a
>thread) and then stops execution when it's released (Push to Make - Single
>Pole in electronics terms).
>
>I've tried the regular way of associating the procedure with a callback and
>tried using  and  bindings but am getting nowhere
>fast (in the latter case the button release event seems to occur anyhows).
>

You are a bit stymied :

Afaik, Button needs the click on the button, leaving it depressed,
while ButtonRelease needs a click on the button, and the release can be anywhere
for drag and drop implementation.  So it is possible to call two routines with
one
click and release.

But there is another hassle - you would have to code the loop as a separate
thread,
started by the first, while the second routine sets some variable that is
checked by
the loop to kill itself, as the GUI will not be responsive until the first
command
returns, because the command "captures" the main loop...

HTH - Hendrik


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