Re: How can I obtain the exception object on a generlized except statement?

2007-06-11 Thread Duncan Booth
Chris Allen <[EMAIL PROTECTED]> wrote:

> I am confused on one aspect of exception handling.  If you specify the
> exception object type to match in an except statement it is possible
> to also obtain the exception object itself, but I can't figure out how
> to get the exception object when I don't specify a match.

In most cases you can just catch Exception. If you want to be sure to 
catch deprecated string exceptions also then use sys.exc_info().

try:
 ... something ...
except Exception, e:
   print e

Also what you want to do with it when you've caught it makes a 
difference:

If you are planning on logging a stack backtrace then you'll want the 
traceback as well as the exception, so sys.exc_info() might be indicated 
except that in that case you'll be better off using logging.exception() 
instead.

try:
 ... something ...
except:
   logging.exception("Unexpected error")

If you are just planning on swallowing the exception then you don't want 
any of these: you want to catch the specific exceptions that you expect 
to be raised.

> >>> except (),msg:

Using an empty tuple for the exception specification won't catch any 
exceptions. Not very useful if the tuple is a literal, but it could be 
useful in some obscure situations (e.g. an except clause to handle 
exceptions declared in a specific DLL which might not always be 
present).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations

2007-06-11 Thread Twisted
On Jun 11, 2:42 am, Joachim Durchholz <[EMAIL PROTECTED]> wrote:
> It is possible to write maintainable Perl.

Interesting (spoken in the tone of someone hearing about a purported
sighting of Bigfoot, or maybe a UFO).

Still, extraordinary claims require extraordinary evidence. (And no, a
fuzzy picture of something that might be a giant serpent-like thing in
the loch, or equivalent, does not constitute "extraordinary
evidence".)

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


Re: Why does one regex routine work and not the other one?

2007-06-11 Thread Peter Otten
TtfnJohn wrote:

> I have two small scripts that while on the surface should both work
> the problem is they don't.
> 
> Here's the first one:
> import re
> 
> testString = 'Thap,fpvi,[EMAIL PROTECTED]:[EMAIL PROTECTED]
> dialin.net:[EMAIL PROTECTED]::'
> 
> reobj = re.compile(r"(.*),(.*),(.*):::(.*):::(.*)")
> 
> testString1 = reobj.search(testString)
> 
> if testString1:
>match0 = testString1.group(0)
>match1 = testString1.group(1)
> 
> This works as expected with any number of seed strings.
> 
> Now then:
> 
> This one consistently fails even though it should work, as near as I
> can tell.
> import os
> import re
> import readline
> from buzhug import Base
> 
> # initialize a few things
> voiceuser = Base('voiceuser')
> # now  to create & open the database. If the database already exists
> this will
> # simply open it
> voiceuser.create(('name',str),('ircname',str),('first',str),
> ('second',str),('third',str),('fourth',str),('fifth',str),
> ('sixth',str),('seventh',str),mode="open")
> 
> #next is to open the file we'll read from and then process it and add
> the names
> # to the database
> # the first step is to compile the regular expression
> testString = re.compile(r"(.*),(.*),(.*):::(.*):::(.*)")
> voiceList = open('friendslist','r')
> 
> while 1:
> line = voiceList.readline()
> if not line:
> break

The above is spelt
  for line in voiceList:

> print len(line)
> line = line[:-2]

Change that to 

line = line[:-1] 

or, more robust,

line = line.rstrip() 

Otherwise you might be clipping the last ":".

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


Re: Python optimization (was Python's "only one way to do it" philosophy isn't good?)

2007-06-11 Thread Diez B. Roggisch
>It's hard to optimize Python code well without global analysis.
> The problem is that you have to make sure that a long list of "wierd
> things", like modifying code or variables via getattr/setattr, aren't
> happening before doing significant optimizations.  Without that,
> you're doomed to a slow implementation like CPython.
> 
>ShedSkin, which imposes some restrictions, is on the right track here.
> The __slots__ feature is useful but doesn't go far enough.
> 
>I'd suggest defining "simpleobject" as the base class, instead of 
> "object",
> which would become a derived class of "simpleobject".   Objects descended
> directly from "simpleobject" would have the following restrictions:
> 
> - "getattr" and "setattr" are not available (as with __slots__)
> - All class member variables must be initialized in __init__, or
>   in functions called by __init__.  The effect is like __slots__,
>   but you don't have to explictly write declarations.
> - Class members are implicitly typed with the type of the first
>   thing assigned to them.  This is the ShedSkin rule.  It might
>   be useful to allow assignments like
> 
> self.str = None(string)
> 
>   to indicate that a slot holds strings, but currently has the null
>   string.
> - Function members cannot be modified after declaration.  Subclassing
>   is fine, but replacing a function member via assignment is not.
>   This allows inlining of function calls to small functions, which
>   is a big win.
> - Private function members (self._foo and self.__foo) really are
>   private and are not callable outside the class definition.
> 
> You get the idea.  This basically means that "simpleobject" objects have
> roughly the same restrictions as C++ objects, for which heavy compile time
> optimization is possible.  Most Python classes already qualify for
> "simpleobject".  And this approach doesn't require un-Pythonic stuff like
> declarations or extra "decorators".
> 
> With this, the heavy optimizations are possible.  Strength reduction.  
> Hoisting
> common subexpressious out of loops.  Hoisting reference count updates 
> out of
> loops.  Keeping frequently used variables in registers.  And elimination of
> many unnecessary dictionary lookups.


I won't give you the "prove it by doing it"-talk. It's to cheap.

Instead I'd like to say why I don't think that this will buy you much 
performance-wise: it's a local optimization only. All it can and will do 
is to optimize lookups and storage of attributes - either functions or 
values - and calls to methods from within one specialobject. As long as 
expressions stay in their own "soup", things might be ok.

The very moment you mix this with "regular", no-strings-attached python 
code, you have to have the full dynamic machinery in place + you need 
tons of guarding statements in the optimized code to prevent access 
violations.

So in the end, I seriously doubt the performance gains are noticable. 
Instead I'd rather take the pyrex-road, which can go even further 
optimizing with some more declarations. But then I at least know exactly 
where the boundaries are. As does the compiler.

> Python could get much, much faster.  Right now CPython is said to be 60X 
> slower
> than C.  It should be possible to get at least an order of magnitude over
> CPython.


Regardless of the possibility of speeding it up - why should one want 
this? Coding speed is more important than speed of coding in 90%+ of all 
cases. The other ones - well, if you _really_ want speed, assembler is 
the way to go. I'm serious about that. There is one famous mathematical 
library author that does code in assembler - because in the end, it's 
all about processor architecture and careful optimization for that. [1]

The same is true for e.g. the new Cell architecture, or the 
altivec-optimized code in photoshop that still beats the crap out of 
Intel processors on PPC-machines.

I'm all for making python faster if it doesn't suffer 
functionality-wise. But until there is a proof that something really 
speeds up python w/o crippling it, I'm more than skeptical.

Diez

[1] http://math-atlas.sourceforge.net/faq.html#auth

"""
  Kazushige Goto
 His ev5/ev6 GEMM is used directly by ATLAS if the user answers 
"yes" to its use during the configuration procedure on an alpha 
processor. This results in a significant speedup over ATLAS's own GEMM 
codes, and is the fastest ev5/ev6 implementation we are aware of.
"""
-- 
http://mail.python.org/mailman/listinfo/python-list


Working with dictionary like strings

2007-06-11 Thread Mr SZ
hello all,
I'm using the urllib module to fetch pages from the web.The returned response 
is in the structure of a dictionary .For eg:

{"":"","label": [
]
,"torrents": [

["F0666BDCCBFD01A52535759C044485E2E1CCE3C3",136,"AAA",1250164864,651,646185088,606208,0,0,0,-1,"",0,0,0,0,33564,7,342884352],
["46683EA1C950CB020DD6DD3007120EAB9966FA79",201,"tpg",4153995264,305,841170944,758087680,901,0,0,103109046,"",4,23,0,0,64080,2,2887053312]]
,"torrentc": "2001899868"}

This response as we can see is not just like a dictionary but it's values are 
in the  form of lists.Now,is there a way I can deal with this string as a 
dictionary .I'm only interested in the value field of torrents key which again 
is a list of lists.




" life isn't heavy enough,it flies away and floats far above action"
  
-
How would you spend $50,000 to create a more sustainable environment in 
Australia?  Go to Yahoo!7 Answers and share your idea.-- 
http://mail.python.org/mailman/listinfo/python-list

RE: Are there any python jobs worked at home from the internet?

2007-06-11 Thread Doug Phillips
> I know of http://www.rentacoder.com/ but I've never actually used it.

http://www.guru.com and http://www.getafreelancer.com are also good
sites (in fact I got my current employment starting off as a contractor
on guru.com)

There are others, but these are the three I've worked with and felt
comfortable working with.

Hope this helps.

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


Re: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations

2007-06-11 Thread Joachim Durchholz
Twisted schrieb:
> On Jun 11, 2:42 am, Joachim Durchholz <[EMAIL PROTECTED]> wrote:
>> It is possible to write maintainable Perl.
> 
> Interesting (spoken in the tone of someone hearing about a purported
> sighting of Bigfoot, or maybe a UFO).
> 
> Still, extraordinary claims require extraordinary evidence. (And no, a
> fuzzy picture of something that might be a giant serpent-like thing in
> the loch, or equivalent, does not constitute "extraordinary
> evidence".)

There's enough Perl code around. Including some that's been reported as 
maintainable and well-maintained.
I haven't looked too deeply into it, but what I have seen from e.g. 
Webmin looked quite clear and straightforward to me. (Real Programmers 
can write Fortran code in any language - and they can write Pascal code 
in any language...)

Perl code *can* resemble line noise. I don't like the language. I think 
Larry and the Perl community have been getting some priorities very 
wrong over time (and other things very right as well: take a look at the 
regex redesign for Perl 6, for example - it's all shades of grey, not 
black-and-white).

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


Re: Are there any python jobs worked at home from the internet?

2007-06-11 Thread kaens
On 6/9/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Sat, 09 Jun 2007 22:53:08 -0300, boyeestudio <[EMAIL PROTECTED]>
> escribió:
>
> > Are there any python jobs worked at home from the internet?
> > I want to find a part time job.
> > Please give a clue to this for me.
>
> I know of http://www.rentacoder.com/ but I've never actually used it.
>
> --
> Gabriel Genellina
>
> --

I'm on RAC, and I'm doing python work right now, but python stuff is
more or less few and far between on RAC.

If you know a few different languages, or can pick them up quickly,
there is a good amount of employment opportunity on RAC. Most of the
"bids" right now seem to be for PHP work or more general web +
random.choice(['design', 'app']) stuff.

But yeah, python works pops up here and there, and when it does it
tends to be pretty interesting stuff.


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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-11 Thread Bruno Desthuilliers
Terry Reedy a écrit :
> <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> | > Terry Reedy wrote:
> | > > In Python, you have a choice of recursion (normal or tail)
> 
> [snip Stroud questions]
> 
> | I'm afraid Terry is wrong here, at least if he meant that CPython had
> | tail recursion *optimization*.
> 
> NO!!!
> I did not mean that or imply that in any way.

I understand you didn't mean it, but since the whole point of 
tail-recursion is allowing optimisation (else tail-recursion is nothing 
else than a subset of recursion), you somehow implied it, even while 
that was not your intention.

> |  (and just for those who don't know yet, it's not a shortcoming, it's a
> | design choice.)
> 
> And I already noted in a followup that I am working on a Python Papers 
> paper explaining that choice, including Guido's claim that 'for statements 
> are better'.
> 
> So frankly I am a little annoyed that you dragged my name into your answer 
> to Stroud when you should have succintly said 'No, Never', or better, 
> nothing at all, as someone else already did say that.  Read more of the 
> tread before jumping in and acribing ignorance to people.
> 

You're right on the fact that I should have read more of the thread 
before posting this (which I usually do), and I do apologize for this. 
But please note the second half of the sentence - which puts a strong 
precondition on the validity of the first part.


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


Re: updating db with csv

2007-06-11 Thread Captain Paralytic
On 11 Jun, 07:37, Tim Roberts <[EMAIL PROTECTED]> wrote:
| Not in standard SQL.  MySQL supports a REPLACE extension that does
an
| UPDATE if the key already exists, and an INSERT if it does not.
 There is
| also an extension clause to the INSERT statement called "ON
DUPLICATE KEY
| UPDATE xxx" that might do what you want.
| --
| Tim Roberts, [EMAIL PROTECTED]
| Providenza & Boekelheide, Inc.

No Tim, that is not correct. the REPLACE extension does not do an
update, it does a replace. It delets the old record and inserts a new
one. The INSERT...ON DUPLICATE KEY UPDATE... does an update. So a
REPLACE will remove all existing field values not referenced in the
statement, whilst an INSERT...ON DUPLICATE KEY UPDATE... will preserve
them. Also REPLACE will make a TIMESTAMP column which has a DEFAULT
CURRENT_TIMESTAMP setting work like one which has ON UPDATE
CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP setting.

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


Python Help!!!

2007-06-11 Thread Elfine Peterson Tjio
I'm trying to make a program that reads Fasta file and print it out. I used the 
SeqIO module and the results is:

'ATGGTCATSingleAlphabet()'

For this purpose, should I use SeqIO or Fasta?

for example:

from Bio import SeqIO

or

from Bio import Fasta

I want it to print every letter. Can anyone point me to the right direction. 
The newest biopython tutorial or book recommendation will be appreciated, too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Regular Text

2007-06-11 Thread jaeltong
Hallo,
I am new to python.
I wrote a program to retrieve the filepath. eg. C:\Programs\Python\
and write it in a text file
It works fine until the path contains \t or \n. eg. C:\Programs\Python
\new\.
Because of the regular text format, I didn't get what I want in the
text file.

I tried to change the separator from \ to / but python only gives C:/
Programs/Python\new/.

How should I do to make sure that the program writes the correct path
in the text file?

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


Re: Regular Text

2007-06-11 Thread Gabriel Genellina
En Mon, 11 Jun 2007 05:53:55 -0300, <[EMAIL PROTECTED]> escribió:

> Hallo,
> I am new to python.
> I wrote a program to retrieve the filepath. eg. C:\Programs\Python\
> and write it in a text file
> It works fine until the path contains \t or \n. eg. C:\Programs\Python
> \new\.
> Because of the regular text format, I didn't get what I want in the
> text file.
>
> I tried to change the separator from \ to / but python only gives C:/
> Programs/Python\new/.
>
> How should I do to make sure that the program writes the correct path
> in the text file?

In your code, you should use string literals like

my_path = r"C:\Programs\Python\new"
my_path = "C:\\Programs\\Python\\new"

But you said "a program to retrieve the filepath" - and I understand that  
you dont have a string literal, and you compute it somehow. Escape  
characters should not be a problem then. Have you verified the contents of  
the text file? With notepad?

-- 
Gabriel Genellina

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


Re: python-ldap for Python 2.5 on Windows?

2007-06-11 Thread Benedict Verheyen
Waldemar Osuch schreef:

> 
> I have managed to build it for myself using MinGW:
> http://www.osuch.org-a.googlepages.com/python-ldap-2.3.win32-py2.5.exe
> 
> See if it will work for you
> 
> Waldemar

Hi Waldemar,

thanks for the installation file.
When i installed it, i got an error stating "The setup files are corrupt".
Anyway, i would be interested in knowing how to build the setup.
The only experience i have so far with building stuff via MinGW was with 
a Qemu build.

Regards,
Benedict

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


Postpone creation of attributes until needed

2007-06-11 Thread Frank Millman
Hi all

I have a small problem. I have come up with a solution, but I don't
know if it is a) safe, and b) optimal.

I have a class with a number of attributes, but for various reasons I
cannot assign values to all the attributes at __init__ time, as the
values depend on attributes of other linked classes which may not have
been created yet. I can be sure that by the time any values are
requested, all the other classes have been created, so it is then
possible to compute the missing values.

At first I initialised the values to None, and then when I needed a
value I would check if it was None, and if so, call a method which
would compute all the missing values. However, there are a number of
attributes, so it got tedious. I was looking for one trigger point
that would work in any situation. This is what I came up with.

>>> class A(object):
...__slots__ = ('x','y','z')
...def __init__(self,x,y):
...self.x = x
...self.y = y
...def __getattr__(self,name):
...print 'getattr',name
...if name not in self.__class__.__slots__:
...raise AttributeError,name
...self.z = self.x * self.y
...return getattr(self,name)

>>> a = A(3,4)
>>> a.x
3
>>> a.y
4
>>> a.z
getattr z
12
>>> a.z
12
>>> a.q
getattr q
Attribute Error: q

In other words, I do not declare the unknown attributes at all. This
causes __getattr__ to be called when any of their values are
requested, and __getattr__ calls the method that sets up the
attributes and computes the values.

I use __slots__ to catch any invalid attributes, otherwise I would get
a 'maximum recursion depth exceeded' error.

Is this ok, or is there a better way?

Thanks

Frank Millman

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


Re: python-ldap for Python 2.5 on Windows?

2007-06-11 Thread Thorsten Kampe
* Benedict Verheyen (Mon, 11 Jun 2007 11:23:59 +0200)
> Waldemar Osuch schreef:
> > I have managed to build it for myself using MinGW:
> > http://www.osuch.org-a.googlepages.com/python-ldap-2.3.win32-py2.5.exe
> > 
> > See if it will work for you
> > 
> thanks for the installation file.
> When i installed it, i got an error stating "The setup files are corrupt".

I downloaded and installed them. They work fine...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python-ldap for Python 2.5 on Windows?

2007-06-11 Thread Benedict Verheyen
Thorsten Kampe schreef:
> * Benedict Verheyen (Mon, 11 Jun 2007 11:23:59 +0200)
>> Waldemar Osuch schreef:
>>> I have managed to build it for myself using MinGW:
>>> http://www.osuch.org-a.googlepages.com/python-ldap-2.3.win32-py2.5.exe
>>>
>>> See if it will work for you
>>>
>> thanks for the installation file.
>> When i installed it, i got an error stating "The setup files are corrupt".
> 
> I downloaded and installed them. They work fine...

I'm on Vista (boohoo :(), what's your platform?

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


Re: Regular Text

2007-06-11 Thread jaeltong
Wow, that is fast. Thanks.

> In your code, you should use string literals like
>
> my_path = r"C:\Programs\Python\new"
> my_path = "C:\\Programs\\Python\\new"
>
> But you said "a program to retrieve the filepath" - and I understand that
> you dont have a string literal, and you compute it somehow. Escape
> characters should not be a problem then. Have you verified the contents of
> the text file? With notepad?

I meant, I used a GUI-Tkinter Script to retrieve the input(the
directory). my program is supposed to
1. get the directory from the GUI Script,
 with my_path= FieldValue.insert(n, variable.get())
2. open a text file
3. and edit a filepath in the file,
4 then saving as another new file...

if that is the case, how should I do, in order to get the input in the
correct format??



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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Phil Thompson
On Monday 11 June 2007 10:24 am, Frank Millman wrote:
> Hi all
>
> I have a small problem. I have come up with a solution, but I don't
> know if it is a) safe, and b) optimal.
>
> I have a class with a number of attributes, but for various reasons I
> cannot assign values to all the attributes at __init__ time, as the
> values depend on attributes of other linked classes which may not have
> been created yet. I can be sure that by the time any values are
> requested, all the other classes have been created, so it is then
> possible to compute the missing values.
>
> At first I initialised the values to None, and then when I needed a
> value I would check if it was None, and if so, call a method which
> would compute all the missing values. However, there are a number of
> attributes, so it got tedious. I was looking for one trigger point
> that would work in any situation. This is what I came up with.
>
> >>> class A(object):
>
> ...__slots__ = ('x','y','z')
> ...def __init__(self,x,y):
> ...self.x = x
> ...self.y = y
> ...def __getattr__(self,name):
> ...print 'getattr',name
> ...if name not in self.__class__.__slots__:
> ...raise AttributeError,name
> ...self.z = self.x * self.y
> ...return getattr(self,name)
>
> >>> a = A(3,4)
> >>> a.x
>
> 3
>
> >>> a.y
>
> 4
>
> >>> a.z
>
> getattr z
> 12
>
> >>> a.z
>
> 12
>
> >>> a.q
>
> getattr q
> Attribute Error: q
>
> In other words, I do not declare the unknown attributes at all. This
> causes __getattr__ to be called when any of their values are
> requested, and __getattr__ calls the method that sets up the
> attributes and computes the values.
>
> I use __slots__ to catch any invalid attributes, otherwise I would get
> a 'maximum recursion depth exceeded' error.
>
> Is this ok, or is there a better way?

Properties...

@property
def z(self):
return self.x * self.y

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


Re: Regular Text

2007-06-11 Thread Peter Otten
 [EMAIL PROTECTED] wrote:

> Wow, that is fast. Thanks.
> 
>> In your code, you should use string literals like
>>
>> my_path = r"C:\Programs\Python\new"
>> my_path = "C:\\Programs\\Python\\new"
>>
>> But you said "a program to retrieve the filepath" - and I understand that
>> you dont have a string literal, and you compute it somehow. Escape
>> characters should not be a problem then. Have you verified the contents
>> of the text file? With notepad?
> 
> I meant, I used a GUI-Tkinter Script to retrieve the input(the
> directory). my program is supposed to
> 1. get the directory from the GUI Script,
>  with my_path= FieldValue.insert(n, variable.get())
> 2. open a text file
> 3. and edit a filepath in the file,
> 4 then saving as another new file...
> 
> if that is the case, how should I do, in order to get the input in the
> correct format??

The user can input literals like "...\t..." via the GUI, and Python will
interpret the sequence "\t" as a backslash followed by the letter t. If you
want to allow the user to use forward slashes, too, apply
os.path.normpath():

... os.path.normpath(variable.get()) ...

Peter


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


Re: memory efficient set/dictionary

2007-06-11 Thread koara
> > I would recommend you to use a database since it meets your
> > requirements (off-memory, fast, persistent). The bsdddb module
> > (berkeley db) even gives you a dictionary like interface.
> >http://www.python.org/doc/lib/module-bsddb.html
>
> Standard SQL databases can work for this, but generally your
> recommendation of using bsddb works very well for int -> int mappings.
> In particular, I would suggest using a btree, if only because I have had
> troubles in the past with colliding keys in the bsddb.hash (and recno is
> just a flat file, and will attempt to create a file i*(record size) to
> write to record number i .
>
> As an alternative, there are many search-engine known methods for
> mapping int -> [int, int, ...], which can be implemented as int -> int,
> where the second int is a pointer to an address on disk.  Looking into a
> few of the open source search implementations may be worthwhile.

Thanks guys! I will look into bsddb, hopefully this doesn't keep all
keys in memory, i couldn't find answer to that during my (very brief)
look into the documentation.

And how about the extra memory used for set/dict'ing of integers? Is
there a simple answer?

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Steven D'Aprano
On Mon, 11 Jun 2007 02:24:51 -0700, Frank Millman wrote:

> Hi all
> 
> I have a small problem. I have come up with a solution, but I don't
> know if it is a) safe, and b) optimal.
> 
> I have a class with a number of attributes, but for various reasons I
> cannot assign values to all the attributes at __init__ time, as the
> values depend on attributes of other linked classes which may not have
> been created yet. I can be sure that by the time any values are
> requested, all the other classes have been created, so it is then
> possible to compute the missing values.

Unless you're doing something like creating classes in one thread while
another thread initiates your instance, I don't understand how this is
possible.

Unless... you're doing something like this?


def MyClass(object):
def __init__(self):
self.x = Parrot.plumage   # copy attributes of classes
self.y = Shrubbery.leaves


Maybe you should force the creation of the classes?

def MyClass(object):
def __init__(self):
try:
Parrot
except Some_Error_Or_Other: # NameError?
# do something to create the Parrot class
pass
self.x = Parrot.plumage
# etc.


> At first I initialised the values to None, and then when I needed a
> value I would check if it was None, and if so, call a method which
> would compute all the missing values. However, there are a number of
> attributes, so it got tedious. I was looking for one trigger point
> that would work in any situation. This is what I came up with.
> 
 class A(object):
> ...__slots__ = ('x','y','z')

By using slots, you're telling Python not to reserve space for a __dict__,
which means that your class cannot create attributes on the fly.



> ...def __init__(self,x,y):
> ...self.x = x
> ...self.y = y
> ...def __getattr__(self,name):
> ...print 'getattr',name
> ...if name not in self.__class__.__slots__:
> ...raise AttributeError,name
> ...self.z = self.x * self.y
> ...return getattr(self,name)

[snip]

> In other words, I do not declare the unknown attributes at all. This
> causes __getattr__ to be called when any of their values are
> requested, and __getattr__ calls the method that sets up the
> attributes and computes the values.
> 
> I use __slots__ to catch any invalid attributes, otherwise I would get
> a 'maximum recursion depth exceeded' error.

That's the wrong solution to that problem. To avoid that problem,
__getattr__ should write directly to self.__dict__.


> Is this ok, or is there a better way?

At the interactive Python prompt: 

help(property)



-- 
Steven

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Frank Millman
On Jun 11, 11:47 am, Phil Thompson <[EMAIL PROTECTED]>
wrote:
> On Monday 11 June 2007 10:24 am, Frank Millman wrote:
>
> > Hi all
>
> > I have a small problem. I have come up with a solution, but I don't
> > know if it is a) safe, and b) optimal.
>
> > I have a class with a number of attributes, but for various reasons I
> > cannot assign values to all the attributes at __init__ time, as the
> > values depend on attributes of other linked classes which may not have
> > been created yet. I can be sure that by the time any values are
> > requested, all the other classes have been created, so it is then
> > possible to compute the missing values.
>
>
> Properties...
>
> @property
> def z(self):
> return self.x * self.y
>

In my simple example I showed only one missing attribute - 'z'. In
real life I have a number of them, so I would have to set up a
separate property definition for each of them.

With my approach, __getattr__ is called if *any* of the missing
attributes are referenced, which seems easier and requires less
maintenance if I add additional attributes.

Another point - the property definition is called every time the
attribute is referenced, whereas __getattr__ is only called if the
attribute does not exist in the class __dict__, and this only happens
once. Therefore I think my approach should be slightly quicker.

Frank

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


Threads, signals and sockets (on UNIX)

2007-06-11 Thread geoffbache
Hi all,

I have a Python program (on UNIX) whose main job is to listen on a
socket, for which I use the SocketServer module. However, I would also
like it to be sensitive to signals received, which it isn't if it's
listening on the socket. ("signals can only be received between atomic
actions of the python interpreter", presumably - and control will not
return to Python unless something appears on the socket). Does anyone
have a tip of a good way to do this?

I can of course put the SocketServer in a thread and call
signal.pause() in the main thread, but this falls down when the
SocketServer terminates normally, as the signal.pause() cannot be
interrupted except via signals. So I tried sending a "dummy" signal
(SIGCHLD) from the thread when the SocketServer terminates, which
seems to work on Linux but not Solaris. And which in any case feels a
bit hackish - surely there has to be a better way?

Regards,
Geoff Bache

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-11 Thread Antoon Pardon
On 2007-06-09, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
> "WaterWalk" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>| I've just read an article "Building Robust System" by Gerald Jay
>| Sussman. The article is here:
>| 
> http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf
>|
>| In it there is a footprint which says:
>| "Indeed, one often hears arguments against building exibility into an
>| engineered sys-
>| tem. For example, in the philosophy of the computer language Python it
>| is claimed:
>
> For him to imply that Python is anti-flexibility is wrong.  Very wrong.. 
> He should look in a mirror.  See below.

My impression is that python supporters often enough show
some anti-flexibility attitude.

>| \There should be one|and preferably only one|obvious way to do
>| it."[25] Science does
>| not usually proceed this way: In classical mechanics, for example, one
>| can construct equa-
>| tions of motion using Newtonian vectoral mechanics, or using a
>| Lagrangian or Hamiltonian
>| variational formulation.[30] In the cases where all three approaches
>| are applicable they are
>| equivalent, but each has its advantages in particular contexts."
>
> And in those contexts, one would hope that the method with advantages is 
> somehow the obvious way to do it.  Otherwise beginners might become like 
> Buriden's ass.
>
> So I dispute that science is as different as he claims.  And I do not see 
> any real value in the statement in that I do not see it saying anything 
> useful to the reader, at least not in this snippet.

Yes science is different. The difference is the following. Should
science only know the Newtonian vectoral mechanics and someone
would come up with the Lagrangian approach, nobody would protest
against this new approach by remarking that there should only be
one obvious approach, implying that by introducing the second approach
you give the people a choice, which they will have to think about
so their decision what to use is no longer obvious, which it is
if there is only one option.

Yet these kind of remarks are made often enough when someone suggest a
change to python.

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


How to get inputs for a python program that run from another python program

2007-06-11 Thread pradeep nair
I would like to know how to pass keyboard input for a python script
which is ran by another script.

for eg:

hello1.py:

import os

if __name__=='__main__':

 print "I will call this other program called hello.py"
 os.system("python hello.py")
 print "hello1.py"


hello.py:

import os

if __name__=='__main__':

 print "press ENTER to display"
 #code wer if the user hits enter
 print "hello"
 #else the user hits any other keyboard button:
 sys.exit()


now wen i run hello1.py,i want the  some function or utility in
hello1.py that can pass the keyboard i/p  to hello.py .

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


Type error when using SQLAlchemy and Python

2007-06-11 Thread Nathan Harmston
HI,

I posted this to sqlalchemy but didnt get a response, so I was
wondering if anyone on python-list could help me.

I m currently trying to build an api for a database and I really like
the way that Djangos manager ( Class_name.objects ) is set up. This
seems very intuitive for me. After reading through the some of the
django source and getting slightly confused I ve implemented a basic
version for one of my tables. The problem is I get an exception, when
I m not expecting one.

registry.py --> contains table definitions etc.

Manager.py

from Registry import *

class Manager(object):
def __init__(self, model, table=None):
self.model = model
self.table = table
def get(self, slice):
pass
def all(self):
print "1"
mapper(self.model, interpro_table)
print "2"
session = create_session()
print "3"
query = session.query(self.model)
print "4"
return query.select()

Models.py

from Manager import *

class ModelBase(type):
def __new__(cls, name, bases, dict):
print cls
setattr(cls, 'objects', Manager(cls))
return type.__new__(cls, name, bases, dict)

class Model(object):
__metaclass__=ModelBase

class InterPro(Model):
_tableName = interpro_table
def __init__(self, interpro_ac):
self.interpro_ac = interpro_ac
def __str__(self):
return "InterPro: %s" %(self.interpro_ac)
def __repr__(self):
return "InterPro: %s" %(self.interpro_ac)

if __name__=='__main__':
a = Manager(InterPro)
print a
print a.all() --> this prints out all of the objects in the database
i = InterPro('IPR014697')
print InterPro.objects
print InterPro.objects.all()
 --> this fails and produces the exception.

Traceback (most recent call last):
  File "Model.py ", line 28, in ?
print InterPro.objects.all()
  File "/home/skeg/workspace/test/src/Manager.py", line 17, in all
return query.select()
  File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py",
line 247, in select
return self.select_whereclause(whereclause=arg, **kwargs)
  File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py",
line 252, in select_whereclause
return self._select_statement(statement, params=params)
  File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py",
line 378, in _select_statement
return self.execute(statement, params=params, **kwargs)
  File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py",
line 310, in execute
return self.instances(result, **kwargs)
  File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py",
line 329, in instances
self.mapper._instance(context, row, result)
  File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/mapper.py",
line 1213, in _instance
instance = self._create_instance(context.session)
  File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/mapper.py",
line 1234, in _create_instance
obj = self.class_.__new__(self.class_)
TypeError: __new__() takes exactly 4 arguments (1 given)

Does anyone know what the problem is? Is it the way I ve programmed
this using metaclasses or is it sqlalchemy and the way in instantiates
objects or even both?

Many Thanks in advance,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Postpone creation of attributes until needed

2007-06-11 Thread Frank Millman
On Jun 11, 12:21 pm, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Mon, 11 Jun 2007 02:24:51 -0700, Frank Millman wrote:
> > Hi all
>
> > I have a small problem. I have come up with a solution, but I don't
> > know if it is a) safe, and b) optimal.
>
> > I have a class with a number of attributes, but for various reasons I
> > cannot assign values to all the attributes at __init__ time, as the
> > values depend on attributes of other linked classes which may not have
> > been created yet. I can be sure that by the time any values are
> > requested, all the other classes have been created, so it is then
> > possible to compute the missing values.
>
> Unless you're doing something like creating classes in one thread while
> another thread initiates your instance, I don't understand how this is
> possible.
>

I was hoping not to have to explain this, as it gets a bit complicated
(yes, I have read The Zen of Python ;-), but I will try.

I have a class that represents a database table, and another class
that represents a database column. When the application 'opens' a
table, I create an instance for the table and separate instances for
each column.

If there are foreign keys, I used to automatically open the foreign
table with its columns, and build cross-references between the foreign
key column on the first table and the primary key column on the second
table.

I found that as the database grew, I was building an increasing number
of links, most of which would never be used during that run of the
program, so I stopped doing it that way. Now I only open the foreign
table if the application requests it, but then I have to find the
original table and update it with attributes representing the link to
the new table.

It gets more complicated than that, but that is the gist of it.

>  class A(object):
> > ...__slots__ = ('x','y','z')
>
> By using slots, you're telling Python not to reserve space for a __dict__,
> which means that your class cannot create attributes on the fly.
>

I understand that. In fact I was already using slots, as I was
concerned about the number of 'column' instances that could be created
in any one program, and wanted to minimise the footprint. I have since
read some of caveats regarding slots, but I am not doing anything out
of the ordinary so I feel comfortable with them so far.

> > I use __slots__ to catch any invalid attributes, otherwise I would get
> > a 'maximum recursion depth exceeded' error.
>
> That's the wrong solution to that problem. To avoid that problem,
> __getattr__ should write directly to self.__dict__.
>

Are you saying that instead of

self.z = self.x * self.y
return getattr(self.name)

I should have

self.__dict__['z'] = self.x * self.y
return self.__dict__[name]

I tried that, but I get AttributeError: 'A' object has no attribute
'__dict__'.

Aslo, how does this solve the problem that 'name' may not be one of
the attributes that my 'compute' method sets up. Or are you saying
that, if I fixed the previous problem, it would just raise
AttributeError anyway, which is what I would want to happen.

> > Is this ok, or is there a better way?
>
> At the interactive Python prompt:
>
> help(property)
>

See my reply to Phil - I would use property if there was only one
attribute, but there are several.

Thanks

Frank

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


netlink messages

2007-06-11 Thread martin f krafft
Dear list,

I am writing a daemon in Python that listens on AF_NETLINK and
processes RTM_NETLINK messages. FWIW, code is below since there is
hardly any reference on the net yet.

As you can see from the code, the NETLINK message is all binary/hex.
Before I go about wrapping it in a Python class, I was wondering
whether such a class already existed or if someone is already
working on this.

Please let me know if you are or have any hints, and please keep me
on CC.

Thanks,
m


Python 2.5.1 (r251:54863, Apr 25 2007, 22:53:30) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from socket import *
>>> from select import *
>>> s = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)
>>> from os import getpid
>>> RTMGRP_LINK = 1
>>> s.bind((getpid(), RTMGRP_LINK))
>>> p = select((s,), (), (), 0)
>>> p
([], [], [])
>>> # connect device
... 
>>> p = select((s,), (), (), 0)
>>> p
([], [], [])
>>> s2 = p[0][0]
>>> d = s2.recv(4096)
>>> d
'\xf8\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x0c\x00\x00\x00\x02\x10\x00\x00\xff\xff\xff\xff\t\x00\x03\x00eth0\x00\x00\x00\x00\x08\x00\r\x00\xe8\x03\x00\x00\x08\x00\x0f\x00\x00\x00\x00\x00\x05\x00\x10\x00\x02\x00\x00\x00\x05\x00\x11\x00\x00\x00\x00\x00\x08\x00\x04\x00\xdc\x05\x00\x00\t\x00\x06\x00noop\x00\x00\x00\x00\x00\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n\x00\x01\x00N\x80\xba~4\x14\x00\x00\n\x00\x02\x00\xff\xff\xff\xff\xff\xff\x00\x00`\x00\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'


-- 
martin;  (greetings from the heart of the sun.)
  \ echo mailto: !#^."<*>"|tr "<*> mailto:"; [EMAIL PROTECTED]
 
spamtraps: [EMAIL PROTECTED]
 
"men always want to be a woman's first love.
 women have a more subtle instinct:
 what they like is to be a man's last romance."
-- oscar wilde


signature.asc
Description: Digital signature (GPG/PGP)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread Stefan Behnel
geoffbache wrote:
> I have a Python program (on UNIX) whose main job is to listen on a
> socket, for which I use the SocketServer module. However, I would also
> like it to be sensitive to signals received, which it isn't if it's
> listening on the socket. ("signals can only be received between atomic
> actions of the python interpreter", presumably - and control will not
> return to Python unless something appears on the socket). Does anyone
> have a tip of a good way to do this?

Twisted *should* be able to do this, as it uses non-blocking IO.

http://twistedmatrix.com/trac/

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Frank Millman
wrote:

> On Jun 11, 12:21 pm, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
>> > I use __slots__ to catch any invalid attributes, otherwise I would get
>> > a 'maximum recursion depth exceeded' error.
>>
>> That's the wrong solution to that problem. To avoid that problem,
>> __getattr__ should write directly to self.__dict__.
>>
> 
> Are you saying that instead of
> 
> self.z = self.x * self.y
> return getattr(self.name)
> 
> I should have
> 
> self.__dict__['z'] = self.x * self.y
> return self.__dict__[name]
> 
> I tried that, but I get AttributeError: 'A' object has no attribute
> '__dict__'.

That's because you used `__slots__`.  One of the drawbacks of `__slots__`.

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Steven D'Aprano
On Mon, 11 Jun 2007 03:58:16 -0700, Frank Millman wrote:

>> By using slots, you're telling Python not to reserve space for a __dict__,
>> which means that your class cannot create attributes on the fly.
>>
> 
> I understand that. In fact I was already using slots, as I was
> concerned about the number of 'column' instances that could be created
> in any one program, and wanted to minimise the footprint. 

Unless you have thousands and thousands of instances, __slots__ is almost
certainly not the answer. __slots__ is an optimization to minimize the
size of each instance. The fact that it prevents the creation of new
attributes is a side-effect.


> I have since
> read some of caveats regarding slots, but I am not doing anything out
> of the ordinary so I feel comfortable with them so far.
> 
>> > I use __slots__ to catch any invalid attributes, otherwise I would get
>> > a 'maximum recursion depth exceeded' error.
>>
>> That's the wrong solution to that problem. To avoid that problem,
>> __getattr__ should write directly to self.__dict__.
>>
> 
> Are you saying that instead of
> 
> self.z = self.x * self.y
> return getattr(self.name)
> 
> I should have
> 
> self.__dict__['z'] = self.x * self.y
> return self.__dict__[name]
> 
> I tried that, but I get AttributeError: 'A' object has no attribute
> '__dict__'.

Of course you do, because you are using __slots__ and so there is no
__dict__ attribute.

I really think you need to lose the __slots__. I don't see that it really
gives you any advantage.



> Aslo, how does this solve the problem that 'name' may not be one of
> the attributes that my 'compute' method sets up. Or are you saying
> that, if I fixed the previous problem, it would just raise
> AttributeError anyway, which is what I would want to happen.

You haven't told us what the 'compute' method is.

Or if you have, I missed it.


>> > Is this ok, or is there a better way?
>>
>> At the interactive Python prompt:
>>
>> help(property)
>>
> 
> See my reply to Phil - I would use property if there was only one
> attribute, but there are several.

Writing "several" properties isn't that big a chore, especially if they
have any common code that can be factored out.

Another approach might be to create a factory-function that creates the
properties for you, so you just need to call it like this:

class MyClass(object):
x = property_maker(database1, tableX, 'x', other_args)
y = property_maker(database2, tableY, 'y', other_args)
# blah blah blah

def property_maker(database, table, name, args):
def getx(self):
return getattr(database[table], name)  # or whatever...
def setx(self, value):
setattr(database[table], name, value)
return property(getx, setx, None, "Some doc string")



-- 
Steven.

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Peter Otten
Frank Millman wrote:

> I tried that, but I get AttributeError: 'A' object has no attribute
> '__dict__'.

That's what you get for (ab)using __slots__ without understanding the
implications ;)

You can instead invoke the __getattr__() method of the superclass:

super(A, self).__getattr__(name)

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Giles Brown
On 11 Jun, 11:10, Frank Millman <[EMAIL PROTECTED]> wrote:
> On Jun 11, 11:47 am, Phil Thompson <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > On Monday 11 June 2007 10:24 am, Frank Millman wrote:
>
> > > Hi all
>
> > > I have a small problem. I have come up with a solution, but I don't
> > > know if it is a) safe, and b) optimal.
>
> > > I have a class with a number of attributes, but for various reasons I
> > > cannot assign values to all the attributes at __init__ time, as the
> > > values depend on attributes of other linked classes which may not have
> > > been created yet. I can be sure that by the time any values are
> > > requested, all the other classes have been created, so it is then
> > > possible to compute the missing values.
>
> > Properties...
>
> > @property
> > def z(self):
> > return self.x * self.y
>
> In my simple example I showed only one missing attribute - 'z'. In
> real life I have a number of them, so I would have to set up a
> separate property definition for each of them.
>
> With my approach, __getattr__ is called if *any* of the missing
> attributes are referenced, which seems easier and requires less
> maintenance if I add additional attributes.
>
> Another point - the property definition is called every time the
> attribute is referenced, whereas __getattr__ is only called if the
> attribute does not exist in the class __dict__, and this only happens
> once. Therefore I think my approach should be slightly quicker.
>
> Frank

You could treat the property access like a __getattr__ and use it
to trigger the assignment of instance variables.  This would mean that
all future access would pick up the instance variables.  Following a
kind
"class variable access causes instance variable creation" pattern
(anyone
know a better name for that?).

You may want to construct a little mechanism that sets up these
properties
(a loop, a list of attribute names, and a setattr on the class?).

If you've got to allow access from multiple threads and aren't happy
that
the calculations being idempotent is going to be sufficient (e.g. if
the calculations are really expensive) then you need some kind of
threading
lock in your (one and only?) lazy loading function.

Ok.  Enough lunchtime diversion (I should get some fresh air).

Giles

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


Re: python-ldap for Python 2.5 on Windows?

2007-06-11 Thread Thorsten Kampe
* Benedict Verheyen (Mon, 11 Jun 2007 11:32:26 +0200)
> Thorsten Kampe schreef:
> > * Benedict Verheyen (Mon, 11 Jun 2007 11:23:59 +0200)
> >> Waldemar Osuch schreef:
> >>> I have managed to build it for myself using MinGW:
> >>> http://www.osuch.org-a.googlepages.com/python-ldap-2.3.win32-py2.5.exe
> >>>
> >>> See if it will work for you
> >>>
> >> thanks for the installation file.
> >> When i installed it, i got an error stating "The setup files are corrupt".
> > 
> > I downloaded and installed them. They work fine...
> 
> I'm on Vista (boohoo :(), what's your platform?

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


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread geoffbache

> Twisted *should* be able to do this, as it uses non-blocking IO.
>
> http://twistedmatrix.com/trac/

Thanks for the tip. I'll take a look if nobody has any better
suggestions.

It still seems to me that what I'm trying to do is essentially quite
simple, and shouldn't require
as large a tool as Twisted to fix it. Isn't Twisted basically for web
applications?

Geoff

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


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread Jean-Paul Calderone
On Mon, 11 Jun 2007 04:56:43 -0700, geoffbache <[EMAIL PROTECTED]> wrote:
>
>> Twisted *should* be able to do this, as it uses non-blocking IO.
>>
>> http://twistedmatrix.com/trac/
>
>Thanks for the tip. I'll take a look if nobody has any better
>suggestions.

Twisted is a pretty good suggestion in general. ;)

>
>It still seems to me that what I'm trying to do is essentially quite
>simple, and shouldn't require
>as large a tool as Twisted to fix it. Isn't Twisted basically for web
>applications?

Twisted supports HTTP, but it does plenty of other things too.  Generally
speaking, it's useful for any network application, plus some other stuff.

You're half right about this being simple though, and not needing Twisted
to solve the problem.  The only thing you need to do to solve the problem
is avoid using either signals or threads.  Interaction between the two is
very complicated and, as you've noticed, varies across platforms.  Twisted
is solving the problem for you here by letting you do I/O without using
threads, making signals *almost* simple.

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


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread Chaz Ginger
geoffbache wrote:
>> Twisted *should* be able to do this, as it uses non-blocking IO.
>>
>> http://twistedmatrix.com/trac/
> 
> Thanks for the tip. I'll take a look if nobody has any better
> suggestions.
> 
> It still seems to me that what I'm trying to do is essentially quite
> simple, and shouldn't require
> as large a tool as Twisted to fix it. Isn't Twisted basically for web
> applications?
> 
> Geoff
> 
You could probably use the Asyncore stuff to do it as well (with a lot
less stuff).

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


Pasting an image from clipboard in Tkinter?

2007-06-11 Thread exhuma.twn
As many might know, windows allows to copy an image into the clipboard
by pressing the "Print Screen" button on the keyboard. Is it possible
to paste such an image from the clipboard into a "Text" widget in
Tkinter? Here is my first attempt with just trying to print out the
image data:

-
def pasteImg(tgt):
   global clipboardEnabled
   if not clipboardEnabled: return

   win32clipboard.OpenClipboard(0)
   print win32clipboard.GetClipboardData()
   win32clipboard.CloseClipboard()
-

This works fine with selecting text, but comes up with the following
error when trying to paste an image:

-
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
  File "X:\development\testing\tkwiki\tkwiki.py", line 52, in 
Button( root, command=lambda: pasteImg(txt) ).pack()
  File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg
print win32clipboard.GetClipboardData()
TypeError: Specified clipboard format is not available
-

Obviously the clipboard does not know about that format. Does that
mean I have to wait until it's implemented or are there other ways to
access the image data?

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


Re: Adding tuples to a dictionary

2007-06-11 Thread Maciej Blizi ski
Thank you for all the answers! My problem is solved even better than I
expected!

@Peter: Yes, the garbage collector was causing the slowdown. Switching
it off sped the program up; each iteration was taking the same amount
of time. I ran collection manually every 10 iterations to control
memory usage.

@Bosko: Right, this example code had a bug, appending to the
dictionary was meant to be one nesting level up.

@Nick: Using a tuple cache is a great advice! My real program's tuples
are even better to cache, as there are roughly about 10 different
tuples that are used as values. Using a tuple cache reduced the memory
consumption by about 3-4 times (I'm telling that by looking at the
gkrellm display).

Thanks!
Maciej

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Frank Millman
On Jun 11, 1:56 pm, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
>
> Unless you have thousands and thousands of instances, __slots__ is almost
> certainly not the answer. __slots__ is an optimization to minimize the
> size of each instance. The fact that it prevents the creation of new
> attributes is a side-effect.
>

Understood - I am getting there slowly.

I now have the following -

>>> class A(object):
...def __init__(self,x,y):
...self.x = x
...self.y = y
...def __getattr__(self,name):
...print 'getattr',name
...self.compute()
...return self.__dict__[name]
...def compute(self):  # compute all missing attributes
...self.__dict__['z'] = self.x * self.y
   [there could be many of these]

>>> a = A(3,4)
>>> a.x
3
>>> a.y
4
>>> a.z
getattr z
12
>>> a.z
12
>>> a.q
KeyError: 'q'

The only problem with this is that it raises KeyError instead of the
expected AttributeError.

>
> You haven't told us what the 'compute' method is.
>
> Or if you have, I missed it.
>

Sorry - I made it more explicit above. It is the method that sets up
all the missing attributes. No matter which attribute is referenced
first, 'compute' sets up all of them, so they are all available for
any future reference.

To be honest, it feels neater than setting up a property for each
attribute.

I would prefer it if there was a way of raising AttributeError instead
of KeyError. I suppose I could do it manually -

try:
return self.__dict__[name]
except KeyError:
raise AttributeError,name

Frank

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


Re: python-ldap for Python 2.5 on Windows?

2007-06-11 Thread Benedict Verheyen
Thorsten Kampe schreef:

>> I'm on Vista (boohoo :(), what's your platform?
> 
> XP SP2

Hmmm it thought so.
So in my case it would be interesting to know how to build it so i can 
make a build that works on Vista too.

Regards,
Benedict

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


Re: Are there any python jobs worked at home from the internet?

2007-06-11 Thread Rob Knapp
boyeestudio wrote:
> Hi,all buddies.
> Are there any python jobs worked at home from the internet?
> I want to find a part time job.
> Please give a clue to this for me.
> Thanks a lot!
This is probably going to sound like I'm telling you something you 
already know, but keep a close eye on the Python Job Page 
(http://python.org/community/jobs/).  By checking it daily, I was able 
to find 2 part-time jobs about 2 years back.  One of which has morphed 
into a full time job recently.

Also Feedster and UKLUG () both allow you to form an RSS feed of a 
custom job search.  I found that quite useful when I was last looking.  
(Although, there are quite a few dupes)

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


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread geoffbache

>
> You could probably use the Asyncore stuff to do it as well (with a lot
> less stuff).

This looked interesting. But it seems the asyncore stuff operates at
the socket level,
whereas I've currently just got a standard synchronous SocketServer
and the socket
operations themselves are kind of hidden beneath this layer. Can you
point me at anything
that might tell me how to combine Asyncore with SocketServer,
preferably without having to
mess with the internals of SocketServer too much :)

Geoff


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


Re: How to get inputs for a python program that run from another python program

2007-06-11 Thread René Fleschenberg
Hi

pradeep nair schrieb:
> now wen i run hello1.py,i want the  some function or utility in
> hello1.py that can pass the keyboard i/p  to hello.py .

Have a look at subprocess.Popen

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

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

Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread geoffbache
On Jun 11, 2:08 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Mon, 11 Jun 2007 04:56:43 -0700, geoffbache <[EMAIL PROTECTED]> wrote:
>
> >> Twisted *should* be able to do this, as it uses non-blocking IO.
>
> >>http://twistedmatrix.com/trac/
>
> >Thanks for the tip. I'll take a look if nobody has any better
> >suggestions.
>
> Twisted is a pretty good suggestion in general. ;)
> >It still seems to me that what I'm trying to do is essentially quite
> >simple, and shouldn't require
> >as large a tool as Twisted to fix it. Isn't Twisted basically for web
> >applications?
>
> Twisted supports HTTP, but it does plenty of other things too.  Generally
> speaking, it's useful for any network application, plus some other stuff.
>

My application is only incidentally a network application. It doesn't
have clients
and servers as such, it just distributes its work via a grid engine
and then lets
these workers communicate back their results via sockets.

> You're half right about this being simple though, and not needing Twisted
> to solve the problem.  The only thing you need to do to solve the problem
> is avoid using either signals or threads.  Interaction between the two is
> very complicated and, as you've noticed, varies across platforms.  Twisted
> is solving the problem for you here by letting you do I/O without using
> threads, making signals *almost* simple.
>

Yes, I would avoid signals or threads if I could, but it's tough. The
program
is supposed to "appear" to just be a batch process, so handling e.g.
ctrl-C is essential.
The standard SocketServer doesn't allow for this, so I need some other
thread of control
that will, or some means of "asynchronising" SocketServer internally.

Or there's always the really hacky low tech solution which has a
certain appeal : have
the main thread check all the others for being alive and sleep in
between...

Geoff

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread George Sakkis
On Jun 11, 8:27 am, Frank Millman <[EMAIL PROTECTED]> wrote:
> On Jun 11, 1:56 pm, Steven D'Aprano
>
> <[EMAIL PROTECTED]> wrote:
>
> > Unless you have thousands and thousands of instances, __slots__ is almost
> > certainly not the answer. __slots__ is an optimization to minimize the
> > size of each instance. The fact that it prevents the creation of new
> > attributes is a side-effect.
>
> Understood - I am getting there slowly.
>
> I now have the following -
>
> >>> class A(object):
>
> ...def __init__(self,x,y):
> ...self.x = x
> ...self.y = y
> ...def __getattr__(self,name):
> ...print 'getattr',name
> ...self.compute()
> ...return self.__dict__[name]
> ...def compute(self):  # compute all missing attributes
> ...self.__dict__['z'] = self.x * self.y
>[there could be many of these]
>
> >>> a = A(3,4)
> >>> a.x
> 3
> >>> a.y
> 4
> >>> a.z
>
> getattr z
> 12>>> a.z
> 12
> >>> a.q
>
> KeyError: 'q'
>
> The only problem with this is that it raises KeyError instead of the
> expected AttributeError.
>
>
>
> > You haven't told us what the 'compute' method is.
>
> > Or if you have, I missed it.
>
> Sorry - I made it more explicit above. It is the method that sets up
> all the missing attributes. No matter which attribute is referenced
> first, 'compute' sets up all of them, so they are all available for
> any future reference.
>
> To be honest, it feels neater than setting up a property for each
> attribute.

I don't see why this all-or-nothing approach is neater; what if you
have a hundred expensive computed attributes but you just need one ?
Unless you know this never happens in your specific situation because
all missing attributes are tightly coupled, properties are a better
way to go. The boilerplate code can be minimal too with an appropriate
decorator, something like:

class A(object):

def __init__(self,x,y):
self.x = x
self.y = y

@cachedproperty
def z(self):
return self.x * self.y


where cachedproperty is

def cachedproperty(func):
name = '__' + func.__name__
def wrapper(self):
try: return getattr(self, name)
except AttributeError: # raised only the first time
value = func(self)
setattr(self, name, value)
return value
return property(wrapper)


HTH,

George

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


Re: Pasting an image from clipboard in Tkinter?

2007-06-11 Thread kyosohma
On Jun 11, 7:23 am, "exhuma.twn" <[EMAIL PROTECTED]> wrote:
> As many might know, windows allows to copy an image into the clipboard
> by pressing the "Print Screen" button on the keyboard. Is it possible
> to paste such an image from the clipboard into a "Text" widget in
> Tkinter? Here is my first attempt with just trying to print out the
> image data:
>
> -
> def pasteImg(tgt):
>global clipboardEnabled
>if not clipboardEnabled: return
>
>win32clipboard.OpenClipboard(0)
>print win32clipboard.GetClipboardData()
>win32clipboard.CloseClipboard()
> -
>
> This works fine with selecting text, but comes up with the following
> error when trying to paste an image:
>
> -
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
> return self.func(*args)
>   File "X:\development\testing\tkwiki\tkwiki.py", line 52, in 
> Button( root, command=lambda: pasteImg(txt) ).pack()
>   File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg
> print win32clipboard.GetClipboardData()
> TypeError: Specified clipboard format is not available
> -
>
> Obviously the clipboard does not know about that format. Does that
> mean I have to wait until it's implemented or are there other ways to
> access the image data?


I don't think you can paste to a text widget, but I could be mistaken.
This link talks about pasting an image into a window, but I don't
think it's really what you want...however, it might give you some
ideas:

http://effbot.org/zone/wck-3.htm  (see the "Drawing Images" section)

This link also talks about some of the same things:
http://www.wadsworth.org/spider_doc/spider/docs/python/spipylib/tkinter.html

If I understand them correctly, it sounds like you could possibly
catch the the paste operation and convert the image to a TkImage and
then paste it. I think that since it is in the clipboard, then it is a
file object and this may work. I just don't know how you intercept a
paste.

Mike

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


Re: Python Help!!!

2007-06-11 Thread kyosohma
On Jun 11, 3:39 am, Elfine Peterson Tjio <[EMAIL PROTECTED]> wrote:
> I'm trying to make a program that reads Fasta file and print it out. I used 
> the SeqIO module and the results is:
>
> 'ATGGTCATSingleAlphabet()'
>
> For this purpose, should I use SeqIO or Fasta?
>
> for example:
>
> from Bio import SeqIO
>
> or
>
> from Bio import Fasta
>
> I want it to print every letter. Can anyone point me to the right direction. 
> The newest biopython tutorial or book recommendation will be appreciated, too.

As I understand it, a "Fasta" file is a text file, correct? If so,
this should be trivial with Python.

I created a file with the following data from 
http://en.wikipedia.org/wiki/Fasta_format:

>gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus]
LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV
EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG
LLILILLALLSPDMLGDPDNHMPADPLNTPLHIKPEWYFLFAYAILRSVPNKLGGVLALFLSIVIL
GLMPFLHTSKHRSMMLRPLSQALFWTLTMDLLTLTWIGSQPVEYPYTIIGQMASILYFSIILAFLPIAGX
IENY

Then I did the following to read it:

>>> fil = open(r'c:\test\fasta.txt')
>>> for f in fil.readlines():
if '>' in f:
print f
else:
for letter in f:
print letter

That seemed to work for me. You probably don't want to print the first
line, but that's easily fixed.

Hope that helps.

Mike

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


wx.grid 2.6.1.0 events

2007-06-11 Thread DarkBlue
Hello

pythoncard
wx 2.6.1
python 2.4.x
kinterbasdb
firebird

I have a wx.grid filled with data from a database
one of the fields is a blob field with text data, which
I want to display in some adjacent text control when I scroll
through the grid.

The question is which wx.EVT_XXX do I need
to use and how to 'connect ' the wx.grid to my TextArea
control ,so that the correct data gets displayed after
any row change?


Thanks for any hints.

Db

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


Re: Pasting an image from clipboard in Tkinter?

2007-06-11 Thread exhuma.twn
On Jun 11, 3:47 pm, [EMAIL PROTECTED] wrote:
> On Jun 11, 7:23 am, "exhuma.twn" <[EMAIL PROTECTED]> wrote:
>
>
>
> > As many might know, windows allows to copy an image into the clipboard
> > by pressing the "Print Screen" button on the keyboard. Is it possible
> > to paste such an image from the clipboard into a "Text" widget in
> > Tkinter? Here is my first attempt with just trying to print out the
> > image data:
>
> > -
> > def pasteImg(tgt):
> >global clipboardEnabled
> >if not clipboardEnabled: return
>
> >win32clipboard.OpenClipboard(0)
> >print win32clipboard.GetClipboardData()
> >win32clipboard.CloseClipboard()
> > -
>
> > This works fine with selecting text, but comes up with the following
> > error when trying to paste an image:
>
> > -
> > Exception in Tkinter callback
> > Traceback (most recent call last):
> >   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
> > return self.func(*args)
> >   File "X:\development\testing\tkwiki\tkwiki.py", line 52, in 
> > Button( root, command=lambda: pasteImg(txt) ).pack()
> >   File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg
> > print win32clipboard.GetClipboardData()
> > TypeError: Specified clipboard format is not available
> > -
>
> > Obviously the clipboard does not know about that format. Does that
> > mean I have to wait until it's implemented or are there other ways to
> > access the image data?
>
> I don't think you can paste to a text widget, but I could be mistaken.
> This link talks about pasting an image into a window, but I don't
> think it's really what you want...however, it might give you some
> ideas:
>
> http://effbot.org/zone/wck-3.htm (see the "Drawing Images" section)
>
> This link also talks about some of the same 
> things:http://www.wadsworth.org/spider_doc/spider/docs/python/spipylib/tkint...
>
> If I understand them correctly, it sounds like you could possibly
> catch the the paste operation and convert the image to a TkImage and
> then paste it. I think that since it is in the clipboard, then it is a
> file object and this may work. I just don't know how you intercept a
> paste.
>
> Mike

Unfortunately, when they talk about "pasting" they talk about a PIL
method called paste, which (if I understood correctly) deals with
blitting one image onto another. Not "pasting" as in copy/paste from
clipboard.

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


Python-URL! - weekly Python news and links (Jun 11)

2007-06-11 Thread Gabriel Genellina
QOTW:  "That's the Martellibot for you.  Never use a word where a paragraph
with explanatory footnotes will do.

Sigh.  I miss him on c.l.py." - Simon Brunning

"Conclusion:  advice to 'try Python for yourself' is apt in a way the
original questioner might not realize." - Cameron Laird


A small survey revealing so many people using Python
for so many different tasks...

http://groups.google.com/group/comp.lang.python/browse_thread/thread/64b947bf0d77a9da/

"Bragging about Python": A call for good examples to
impress non-Pythoneers generates a nice and compact
solution to the 8 Queens problem by Paul McGuire.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/61c10896866425f6/

Naming conventions again: this time, how people construct
meaningful names, and what they consider a "good" name:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/4f1610900da8f4bb/

Several attempts to speed up date conversions - and at the
end, perhaps one doesn't even *need* the conversion at all!
http://mail.python.org/pipermail/python-list/2007-June/444306.html

If you thought that you could not use multiple Python
interpreters inside the same process, you were wrong,
and this is how to do it:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/4ac31cd3a389a4d8/

Did you know that you could skip a value using string
interpolation? Here is the trick:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/79bb6c636f8710bb/



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

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

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

The Python Papers aims to publish "the efforts of Python enthusiats".
http://pythonpapers.org/

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

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

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

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

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pythonware_com_daily.pc

Santa Fe Python Day report

2007-06-11 Thread Facundo Batista
It was very succesful, around +300 people assisted, and there were a lot of 
interesting talks (two introductory talks, Turbogears, PyWeek, Zope 3, 
security, creating 3D games, Plone, automatic security testings, concurrency, 
and programming the OLPC).

I want to thanks the PSF for the received support. Python is developing 
interestingly in Argentina, and this Python Days are both a prove of that, and 
a way to get more Python developers.

Some links:

  Santa Fe Python Day: http://www.python-santafe.com.ar/
  Python Argentina: http://www.python.com.ar/moin

Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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


Re: wx.grid 2.6.1.0 events

2007-06-11 Thread kyosohma
On Jun 11, 9:04 am, DarkBlue <[EMAIL PROTECTED]> wrote:
> Hello
>
> pythoncard
> wx 2.6.1
> python 2.4.x
> kinterbasdb
> firebird
>
> I have a wx.grid filled with data from a database
> one of the fields is a blob field with text data, which
> I want to display in some adjacent text control when I scroll
> through the grid.
>
> The question is which wx.EVT_XXX do I need
> to use and how to 'connect ' the wx.grid to my TextArea
> control ,so that the correct data gets displayed after
> any row change?
>
> Thanks for any hints.
>
> Db

Upon skimming the grid controls event types in the wxPython in Action
book, it looks like you could catch the wx.grid.EVT_GRID_SELECT_CELL
event. Then use the GetCellValue method to grab the selected cell's
contents and then write that to your TextCtrl.

If that doesn't work, please post the issue to the wxPython user's
group here: http://wxpython.org/maillist.php

Mike

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Frank Millman
On Jun 11, 3:38 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Jun 11, 8:27 am, Frank Millman <[EMAIL PROTECTED]> wrote:
>
>
> > Sorry - I made it more explicit above. It is the method that sets up
> > all the missing attributes. No matter which attribute is referenced
> > first, 'compute' sets up all of them, so they are all available for
> > any future reference.
>
> > To be honest, it feels neater than setting up a property for each
> > attribute.
>
> I don't see why this all-or-nothing approach is neater; what if you
> have a hundred expensive computed attributes but you just need one ?
> Unless you know this never happens in your specific situation because
> all missing attributes are tightly coupled, properties are a better
> way to go.

It so happens that this is my specific situation. I can have a foreign
key column in one table with a reference to a primary key column in
another table. I have for some time now had the ability to set up a
pseudo-column in the first table with a reference to an alternate key
column in the second table, and this requires various attributes to be
set up. I have recently extended this concept where the first table
can have a pseudo-column pointing to a column in the second table,
which is in turn a pseudo-column pointing to a column in a third
table. This can chain indefinitely provided that the end of the chain
is a real column in the final table.

My problem is that, when I create the first pseudo-column, the target
column, also pseudo, does not exist yet. I cannot call it recursively
due to various other complications. Therefore my solution was to wait
until I need it. Then the first one makes a reference to the second
one, which in turn realises that in needs a reference to the third
one, and so on. So it is recursive, but at execution-time, not at
instantiation-time.

Hope this makes sense.

>The boilerplate code can be minimal too with an appropriate
> decorator, something like:
>
> class A(object):
>
> def __init__(self,x,y):
> self.x = x
> self.y = y
>
> @cachedproperty
> def z(self):
> return self.x * self.y
>
> where cachedproperty is
>
> def cachedproperty(func):
> name = '__' + func.__name__
> def wrapper(self):
> try: return getattr(self, name)
> except AttributeError: # raised only the first time
> value = func(self)
> setattr(self, name, value)
> return value
> return property(wrapper)
>

This is very neat, George. I will have to read it a few more times
before I understand it properly - I still have not fully grasped
decorators, as I have not yet had a need for them.

Actually I did spend a bit of time trying to understand it before
posting, and I have a question.

It seems that this is now a 'read-only' attribute, whose value is
computed by the function the first time, and after that cannot be
changed. It would probably suffice for my needs, but how easy would it
be to convert it to read/write?

Thanks

Frank

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


Re: Pasting an image from clipboard in Tkinter?

2007-06-11 Thread kyosohma
On Jun 11, 9:07 am, "exhuma.twn" <[EMAIL PROTECTED]> wrote:
> On Jun 11, 3:47 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > On Jun 11, 7:23 am, "exhuma.twn" <[EMAIL PROTECTED]> wrote:
>
> > > As many might know, windows allows to copy an image into the clipboard
> > > by pressing the "Print Screen" button on the keyboard. Is it possible
> > > to paste such an image from the clipboard into a "Text" widget in
> > > Tkinter? Here is my first attempt with just trying to print out the
> > > image data:
>
> > > -
> > > def pasteImg(tgt):
> > >global clipboardEnabled
> > >if not clipboardEnabled: return
>
> > >win32clipboard.OpenClipboard(0)
> > >print win32clipboard.GetClipboardData()
> > >win32clipboard.CloseClipboard()
> > > -
>
> > > This works fine with selecting text, but comes up with the following
> > > error when trying to paste an image:
>
> > > -
> > > Exception in Tkinter callback
> > > Traceback (most recent call last):
> > >   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
> > > return self.func(*args)
> > >   File "X:\development\testing\tkwiki\tkwiki.py", line 52, in 
> > > Button( root, command=lambda: pasteImg(txt) ).pack()
> > >   File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg
> > > print win32clipboard.GetClipboardData()
> > > TypeError: Specified clipboard format is not available
> > > -
>
> > > Obviously the clipboard does not know about that format. Does that
> > > mean I have to wait until it's implemented or are there other ways to
> > > access the image data?
>
> > I don't think you can paste to a text widget, but I could be mistaken.
> > This link talks about pasting an image into a window, but I don't
> > think it's really what you want...however, it might give you some
> > ideas:
>
> >http://effbot.org/zone/wck-3.htm(see the "Drawing Images" section)
>
> > This link also talks about some of the same 
> > things:http://www.wadsworth.org/spider_doc/spider/docs/python/spipylib/tkint...
>
> > If I understand them correctly, it sounds like you could possibly
> > catch the the paste operation and convert the image to a TkImage and
> > then paste it. I think that since it is in the clipboard, then it is a
> > file object and this may work. I just don't know how you intercept a
> > paste.
>
> > Mike
>
> Unfortunately, when they talk about "pasting" they talk about a PIL
> method called paste, which (if I understood correctly) deals with
> blitting one image onto another. Not "pasting" as in copy/paste from
> clipboard.

I don't do much with images as of yet, but from what I've read, it
seems that blitting is a common method. Here's a fairly interesting
article on the process using wxPython (sorry...I wasn't finding
anything under Tkinter):

http://wiki.wxpython.org/index.cgi/WorkingWithImages

It might give some ideas.

Mike

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


skip next item in list

2007-06-11 Thread ahlongxp
list=('a','d','c','d')
for a in list:
if a=='a' :
#skip the letter affer 'a'

what am I supposed to do?

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

Re: skip next item in list

2007-06-11 Thread Andre Engels
2007/6/11, ahlongxp <[EMAIL PROTECTED]>:
> list=('a','d','c','d')
> for a in list:
> if a=='a' :
> #skip the letter affer 'a'
>
> what am I supposed to do?

There might be better ways to do it, but I would do:

flag_last_a = False
for a in list:
   if flag_last_a:
   flag_last_a = False
   continue
   if a=='a':
   flag_last_a = True
   # Whatever is done when you don't skip

-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
-- 
http://mail.python.org/mailman/listinfo/python-list


with as a reserved word

2007-06-11 Thread BBands
I gather that 'with' is on its way to becoming a reserved word. Is
this something that will break?

import Gnuplot
gp = Gnuplot.Gnuplot(debug=1)
data = Gnuplot.Data([1,2,3,4,3,2,3,4,3,2,1], with='linespoints')
gp.plot(data)

>>> :3: Warning: 'with' will become a reserved keyword in Python 2.6

http://www.gnuplot.info/
http://gnuplot-py.sourceforge.net/

This was run by PyScripter 1.8.7.1 with Python 2.5.

 jab

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


Re: with as a reserved word

2007-06-11 Thread kyosohma
On Jun 11, 10:03 am, BBands <[EMAIL PROTECTED]> wrote:
> I gather that 'with' is on its way to becoming a reserved word. Is
> this something that will break?
>
> import Gnuplot
> gp = Gnuplot.Gnuplot(debug=1)
> data = Gnuplot.Data([1,2,3,4,3,2,3,4,3,2,1], with='linespoints')
> gp.plot(data)
>
> >>> :3: Warning: 'with' will become a reserved keyword in Python 2.6
>
> http://www.gnuplot.info/http://gnuplot-py.sourceforge.net/
>
> This was run by PyScripter 1.8.7.1 with Python 2.5.
>
>  jab

Looks that way since you can assign anything to 'for' or 'if' or other
reserved words.

Mike

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


Re: skip next item in list

2007-06-11 Thread Diez B. Roggisch
ahlongxp wrote:

> list=('a','d','c','d')
> for a in list:
> if a=='a' :
> #skip the letter affer 'a'
> 
> what am I supposed to do?

First - don't use list as name, as it is a builtins-name and shadowing is
likely to produce errors at some point.

list_iterator = iter(('a','d','c','d'))

for a in list_iterator:
if a == 'a':
   list_iterator.next()
...

should do the trick.



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


Re: with as a reserved word

2007-06-11 Thread Francesco Guerrieri
Within gnuplot you can shorten "with" to "w", don't know if it can
work inside a call to Gnuplot.Data()

francesco

On 6/11/07, BBands <[EMAIL PROTECTED]> wrote:
> I gather that 'with' is on its way to becoming a reserved word. Is
> this something that will break?
>
> import Gnuplot
> gp = Gnuplot.Gnuplot(debug=1)
> data = Gnuplot.Data([1,2,3,4,3,2,3,4,3,2,1], with='linespoints')
> gp.plot(data)
>
> >>> :3: Warning: 'with' will become a reserved keyword in Python 2.6
>
> http://www.gnuplot.info/
> http://gnuplot-py.sourceforge.net/
>
> This was run by PyScripter 1.8.7.1 with Python 2.5.
>
> jab
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as
both victim and villain by the vicissitudes of fate. This visage, no
mere veneer of vanity, is a vestige of the vox populi, now vacant,
vanished. However, this valorous visitation of a bygone vexation
stands vivified, and has vowed to vanquish these venal and virulent
vermin vanguarding vice and vouchsafing the violently vicious and
voracious violation of volition. The only verdict is vengeance; a
vendetta held as a votive, not in vain, for the value and veracity of
such shall one day vindicate the vigilant and the virtuous. Verily,
this vichyssoise of verbiage veers most verbose vis-à-vis an
introduction, so let me simply add that it's my very good honor to
meet you and you may call me V." -- V's introduction to Evey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Postpone creation of attributes until needed

2007-06-11 Thread George Sakkis
On Jun 11, 10:37 am, Frank Millman <[EMAIL PROTECTED]> wrote:
> On Jun 11, 3:38 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> >The boilerplate code can be minimal too with an appropriate
> > decorator, something like:
>
> > class A(object):
>
> > def __init__(self,x,y):
> > self.x = x
> > self.y = y
>
> > @cachedproperty
> > def z(self):
> > return self.x * self.y
>
> > where cachedproperty is
>
> > def cachedproperty(func):
> > name = '__' + func.__name__
> > def wrapper(self):
> > try: return getattr(self, name)
> > except AttributeError: # raised only the first time
> > value = func(self)
> > setattr(self, name, value)
> > return value
> > return property(wrapper)
>
> This is very neat, George. I will have to read it a few more times
> before I understand it properly - I still have not fully grasped
> decorators, as I have not yet had a need for them.

You never *need* decorators, in the sense it's just syntax sugar for
things you might do without them, but they're handy once you get your
head around them.

> Actually I did spend a bit of time trying to understand it before
> posting, and I have a question.
>
> It seems that this is now a 'read-only' attribute, whose value is
> computed by the function the first time, and after that cannot be
> changed. It would probably suffice for my needs, but how easy would it
> be to convert it to read/write?

It's straightforward, just define a setter wrapper and pass it in the
property along with the getter:

def cachedproperty(func):
name = '__' + func.__name__
def getter(self):
try: return getattr(self, name)
except AttributeError: # raised only the first time
value = func(self)
setattr(self, name, value)
return value
def setter(self, value):
setattr(self, name, value)
return property(getter,setter)


HTH,

George

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


Re: skip next item in list

2007-06-11 Thread [EMAIL PROTECTED]
On Jun 11, 8:49 am, ahlongxp <[EMAIL PROTECTED]> wrote:
> list=('a','d','c','d')
> for a in list:
> if a=='a' :
> #skip the letter affer 'a'
>
> what am I supposed to do?


You could do this with itertools.ifilter and an predicate (pred) for a
more OO solution. I've created 2 lists, the source list (l) and the
expected answer (ans). Make sure this is what you meant in your
problem statement:

import itertools

l = ['a', 'b', 'c', 'a', 'd', 'e', 'f', 'a', 'g', 'h']
ans = ['a', 'c', 'a', 'e', 'f', 'a', 'h']

class pred(object):
def __init__(self):
self.last = None

def __call__(self, arg):
result = None

if self.last == 'a':
result = False
else:
result = True

self.last = arg

return result

i = itertools.ifilter(pred(), l)

result = list(i)

print result
print ans

assert result == ans

print 'done'

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Frank Millman
On Jun 11, 5:22 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Jun 11, 10:37 am, Frank Millman <[EMAIL PROTECTED]> wrote:
>
>
> You never *need* decorators, in the sense it's just syntax sugar for
> things you might do without them, but they're handy once you get your
> head around them.
>
> > Actually I did spend a bit of time trying to understand it before
> > posting, and I have a question.
>
> > It seems that this is now a 'read-only' attribute, whose value is
> > computed by the function the first time, and after that cannot be
> > changed. It would probably suffice for my needs, but how easy would it
> > be to convert it to read/write?
>
> It's straightforward, just define a setter wrapper and pass it in the
> property along with the getter:
>
> def cachedproperty(func):
> name = '__' + func.__name__
> def getter(self):
> try: return getattr(self, name)
> except AttributeError: # raised only the first time
> value = func(self)
> setattr(self, name, value)
> return value
> def setter(self, value):
> setattr(self, name, value)
> return property(getter,setter)
>

Wonderful - this is very educational for me :-)

Thanks very much

Frank

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


Re: skip next item in list

2007-06-11 Thread Rafael Darder Calvo
On 6/11/07, Andre Engels <[EMAIL PROTECTED]> wrote:
> 2007/6/11, ahlongxp <[EMAIL PROTECTED]>:
> > list=('a','d','c','d')
> > for a in list:
> > if a=='a' :
> > #skip the letter affer 'a'
> >
> > what am I supposed to do?
>
> There might be better ways to do it, but I would do:
>
> flag_last_a = False
> for a in list:
>if flag_last_a:
>flag_last_a = False
>continue
>if a=='a':
>flag_last_a = True
># Whatever is done when you don't skip
>
> --
> Andre Engels, [EMAIL PROTECTED]
> ICQ: 6260644  --  Skype: a_engels
> --
> http://mail.python.org/mailman/listinfo/python-list
>
another way:

def skip_after(l):
i = iter(l)
for x in i:
yield x
while x == 'a':
x = i.next()

depending on what to do in case of consecutive 'a's, change the
'while' for an 'if'
list(skip_after('spam aand eggs'))
['s', 'p', 'a', ' ', 'a', 'd', ' ', 'e', 'g', 'g', 's']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: skip next item in list

2007-06-11 Thread Duncan Smith
ahlongxp wrote:
> list=('a','d','c','d')
> for a in list:
> if a=='a' :
> #skip the letter affer 'a'
> 
> what am I supposed to do?
> 

Maybe,

>>> it = iter(['a','d','c','d'])
>>> for item in it:
print item
if item == 'a':
x = it.next()


a
c
d
>>>

The binding of a name to it.next() is unnecessary.  It just prevents 'd'
being printed.

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

Accessing global namespace from module

2007-06-11 Thread reubendb
Hello,
I am new to Python. I have the following question / problem.
I have a visualization software with command-line interface (CLI),
which essentially is a Python (v. 2.5) interpreter with functions
added to the global namespace. I would like to keep my own functions
in a separate module and then import that module to the main script
(that will be executed using the CLI interpreter). The problem is, I
cannot access the functions in the global namespace of the main script
from my module. Is there anyway to do that ?

Here is an example of what I meant. The function AddPlot() and
DrawPlots() are added to the global namespace by the software CLI. If
I do this:

mainscript.py:
---
AddPlot("scatter", "coordinate")
# set other things here
DrawPlots()

it works fine. But I want to be able to do this:

myModule.py:
--
def defaultScatterPlot():
  AddPlot("scatter", "coordinate")
  #do other things
  DrawPlots()

and then in mainscript.py:
---
import myModule
myModule.defaultScatterPlot()

This won't work because myModule.py doesnot have access to AddPlot().
How do I do something like this ?

Thank you in advance for any help.
RDB

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


Re: Tkinter - resize tkMessageBox

2007-06-11 Thread Cameron Laird
In article <[EMAIL PROTECTED]>, I wondered:
>In article <[EMAIL PROTECTED]>,
>Glenn Hutchings  <[EMAIL PROTECTED]> wrote:
>>On 4 Jun, 21:29, [EMAIL PROTECTED] wrote:
>>> Is there a way to resize the width of the "tkMessageBox.askyesno"
>>> dialog box, so that the text does not wrap to the next line.
>>
>>You can use the Tk option database, either explicitly or from a file.
>>For example, to set the wrap length of all dialogs to 10 inches, try
>>this:
>>
>>   root = Tk()
>>   root.option_add("*Dialog.msg.wrapLength", "10i")
>   .
>   .
>   .
>But that does *not* affect the MessageBoxes under MacOS and Windows, right?

I apologize for my coyness.  I'll be explicit:  current MessageBoxes
under MacOS and Windows (but NOT X11-based MessageBoxes, as with Linux)
do NOT respect Dialog options.  Tkinter will presumably build in Tile 
capabilities in the future; then the default appearances may change
again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: memory efficient set/dictionary

2007-06-11 Thread Josiah Carlson
koara wrote:
>>> I would recommend you to use a database since it meets your
>>> requirements (off-memory, fast, persistent). The bsdddb module
>>> (berkeley db) even gives you a dictionary like interface.
>>> http://www.python.org/doc/lib/module-bsddb.html
>> Standard SQL databases can work for this, but generally your
>> recommendation of using bsddb works very well for int -> int mappings.
>> In particular, I would suggest using a btree, if only because I have had
>> troubles in the past with colliding keys in the bsddb.hash (and recno is
>> just a flat file, and will attempt to create a file i*(record size) to
>> write to record number i .
>>
>> As an alternative, there are many search-engine known methods for
>> mapping int -> [int, int, ...], which can be implemented as int -> int,
>> where the second int is a pointer to an address on disk.  Looking into a
>> few of the open source search implementations may be worthwhile.
> 
> Thanks guys! I will look into bsddb, hopefully this doesn't keep all
> keys in memory, i couldn't find answer to that during my (very brief)
> look into the documentation.

No, bsddb does not keep all data in memory.


> And how about the extra memory used for set/dict'ing of integers? Is
> there a simple answer?

A non-long integer for a 32 bit Python uses 12 bytes.  A non-long 
integer for a 64 bit Python uses 24 bytes.

Each entry in a dictionary for a 32 bit Python uses 12 bytes; 4 for the 
hash, 4 for the key pointer, 4 for the value pointer.  Double that to 24 
bytes each in the 64 bit Python (I don't know if the hash actually has 
its range increased, but if one doesn't double the size of the pointers, 
then you have alignment issues that can slow down dictionary access).

Sets only have the hash and key pointers, so only use 8/16 bytes per entry.


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


Re: read 9 bytes

2007-06-11 Thread Grant Edwards
On 2007-06-11, nik <[EMAIL PROTECTED]> wrote:

> I need to read a 9 byte response from a device on the serial
> port. From reading the pySerial documentation it appears that
> I can only read in characters at a time.

bytes are the same thing as characters.

> If I do: serialport.read(4)
> I would get 8 bytes,

No, you'd get 4.  Just try it and see.  That would be way
faster and easier than waiting for answers from Usenet.

> and if I did serialport.read(5) I think the port will block
> until a time out,

It would read 5 bytes if available, otherwise it would block
until a timeout.

> since there
>
> Is there a trick to read 9 bytes off of a serial port?

Please tell us what happened when you tried the obvious:

  serialport.read(9)

-- 
Grant Edwards   grante Yow! Do I have a lifestyle
  at   yet?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *Naming Conventions*

2007-06-11 Thread Marius Gedminas
On Jun 6, 3:18 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> > Since 'i' and 'j' are canonically loop indices, I find it
> > totally confusing to use them to name the iteration variable -
> > which is not an index.
>
> Certainly i and j are just as generic, but they have the
> advantage over 'item' of being more terse.

Python programmers usually prefer readability over terseness. Finding
a variable named 'i' that is not an integer index would be surprising
to me.

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


Re: Repository - file scanner

2007-06-11 Thread HMS Surprise
>
> Why not use grep?

With Windows XP?

jh

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


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread fumanchu
On Jun 11, 3:34 am, geoffbache <[EMAIL PROTECTED]> wrote:
> I have a Python program (on UNIX) whose main job is to listen on a
> socket, for which I use the SocketServer module. However, I would also
> like it to be sensitive to signals received, which it isn't if it's
> listening on the socket. ("signals can only be received between atomic
> actions of the python interpreter", presumably - and control will not
> return to Python unless something appears on the socket). Does anyone
> have a tip of a good way to do this?
>
> I can of course put the SocketServer in a thread and call
> signal.pause() in the main thread, but this falls down when the
> SocketServer terminates normally, as the signal.pause() cannot be
> interrupted except via signals. So I tried sending a "dummy" signal
> (SIGCHLD) from the thread when the SocketServer terminates, which
> seems to work on Linux but not Solaris. And which in any case feels a
> bit hackish - surely there has to be a better way?

Use a timeout on your socket and put socket.accept() in a loop:

mainsocket.settimeout(1)

while True:
try:
childsocket, addr = mainsocket.accept()
handle(childsocket, addr)
except socket.timeout:
pass


Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]

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


Re: Accessing global namespace from module

2007-06-11 Thread kyosohma
On Jun 11, 11:02 am, reubendb <[EMAIL PROTECTED]> wrote:
> Hello,
> I am new to Python. I have the following question / problem.
> I have a visualization software with command-line interface (CLI),
> which essentially is a Python (v. 2.5) interpreter with functions
> added to the global namespace. I would like to keep my own functions
> in a separate module and then import that module to the main script
> (that will be executed using the CLI interpreter). The problem is, I
> cannot access the functions in the global namespace of the main script
> from my module. Is there anyway to do that ?
>
> Here is an example of what I meant. The function AddPlot() and
> DrawPlots() are added to the global namespace by the software CLI. If
> I do this:
>
> mainscript.py:
> ---
> AddPlot("scatter", "coordinate")
> # set other things here
> DrawPlots()
>
> it works fine. But I want to be able to do this:
>
> myModule.py:
> --
> def defaultScatterPlot():
>   AddPlot("scatter", "coordinate")
>   #do other things
>   DrawPlots()
>
> and then in mainscript.py:
> ---
> import myModule
> myModule.defaultScatterPlot()
>
> This won't work because myModule.py doesnot have access to AddPlot().
> How do I do something like this ?
>
> Thank you in advance for any help.
> RDB

I think you're doing it backwards. If you want access to AddPlot, then
you should import mainscript into that module instead of the other way
around. When I have common methods I want to call from different
scripts, I put those methods/functions into their own module/file.
Then I just import the module and call whatever script I need.



commonMods.py
-
AddPlot(*args, *kwargs):
# Do something
DrawPlots(*args, *kwargs):
# Do something
-


mainProgram.py

from commonMods import AddPlot
AddPlot("scatter", "coordinate")
# etc etc
-

myModule.py

from commonMods import AddPlot
AddPlot("scatter", "coordinate")
# etc etc
-



Hope that helps.

Mike

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


Re: Repository - file scanner

2007-06-11 Thread jigloo
On 6 9 ,   3 33 , HMS Surprise <[EMAIL PROTECTED]> wrote:
> Greetings,
>
> Could someone point my muddled head at a/the python repository. I know
> that one exists but cannot find it again. In particular I am looking
> for a standalone search tool that given a path searches files for a
> text string.
>
> Thanks,
>
> jvh

grep maybe the best choice.
if you want a pure python script
here it is.

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# File: grep.py
# Author: phus

try:
import psyco
psyco.full()
except ImportError:
print 'no mod psyco'

import os, re

def grep_r(rx, path):
root = path
dirstack = [root]
while len(dirstack) > 0:
dir = dirstack.pop()
try:
dirs = os.listdir(dir)
except:
print "os.listdir('%s') error: %s" % (dir, os.error)
continue
for name in dirs:
fullname = os.path.join(dir, name)
if os.path.isdir(fullname):
dirstack.append(fullname)
else:
grep(rx, fullname)

def grep(rx, file):
try:
f = open(file, "r")
for line in f:
if rx.findall(line):
print file, ":", line.strip()
f.close()
except:
print "grep error in %s" % file

if __name__ == "__main__":
patern = "blah blah"
rx = re.compile(patern, re.I)
grep_r(rx, '.')

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


Re: Python optimization (was Python's "only one way to do it" philosophy isn't good?)

2007-06-11 Thread John Nagle
Diez B. Roggisch wrote:
> Regardless of the possibility of speeding it up - why should one want 
> this? Coding speed is more important than speed of coding in 90%+ of all 
> cases. 

 When you have to start buying more servers for the server farm,
it's a real pain.  I'm actually facing that because Python's HTML
parsing is so slow.

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


Re: *Naming Conventions*

2007-06-11 Thread Neil Cerutti
On 2007-06-11, Marius Gedminas <[EMAIL PROTECTED]> wrote:
> On Jun 6, 3:18 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> > Since 'i' and 'j' are canonically loop indices, I find it
>> > totally confusing to use them to name the iteration variable -
>> > which is not an index.
>>
>> Certainly i and j are just as generic, but they have the
>> advantage over 'item' of being more terse.
>
> Python programmers usually prefer readability over terseness.
> Finding a variable named 'i' that is not an integer index would
> be surprising to me.

Terseness and readability can go together in some circumstances,
though. But every case should be handled with taste and the
application experience, obviously. In a situation where 'i' might
be misleading I wouldn't use it.

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


RE: Accessing global namespace from module

2007-06-11 Thread John Krukoff
On Jun 11, 11:02 am, reubendb <[EMAIL PROTECTED]> wrote:
> Hello,
> I am new to Python. I have the following question / problem.
> I have a visualization software with command-line interface (CLI),
> which essentially is a Python (v. 2.5) interpreter with functions
> added to the global namespace. I would like to keep my own functions
> in a separate module and then import that module to the main script
> (that will be executed using the CLI interpreter). The problem is, I
> cannot access the functions in the global namespace of the main script
> from my module. Is there anyway to do that ?
> 
> Here is an example of what I meant. The function AddPlot() and
> DrawPlots() are added to the global namespace by the software CLI. If
> I do this:
> 
> mainscript.py:
> ---
> AddPlot("scatter", "coordinate")
> # set other things here
> DrawPlots()
> 
> it works fine. But I want to be able to do this:
> 
> myModule.py:
> --
> def defaultScatterPlot():
>   AddPlot("scatter", "coordinate")
>   #do other things
>   DrawPlots()
> 
> and then in mainscript.py:
> ---
> import myModule
> myModule.defaultScatterPlot()
> 
> This won't work because myModule.py doesnot have access to AddPlot().
> How do I do something like this ?
> 
> Thank you in advance for any help.
> RDB
> 
> --
> http://mail.python.org/mailman/listinfo/python-list

Since the visulization software creator wasn't kind enough to bundle the
drawing functions up into a module for you, you can just do it yourself.

>>> import sys, new
>>> plotModule = new.module( 'plot' )
>>> plotModule.AddPlot = AddPlot
>>> plotModule.DrawPlots = DrawPlots
>>> sys.modules[ 'plot' ] = plotModule

Then, you can import your fake module from anywhere, and access its
contents.

>>> import plot
>>> plot

>>> plot.AddPlot


Hope that helps.

-
John Krukoff
[EMAIL PROTECTED]

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


Re: Accessing global namespace from module

2007-06-11 Thread reubendb
On Jun 11, 1:37 pm, [EMAIL PROTECTED] wrote:
> On Jun 11, 11:02 am, reubendb <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello,
> > I am new to Python. I have the following question / problem.
> > I have a visualization software with command-line interface (CLI),
> > which essentially is a Python (v. 2.5) interpreter with functions
> > added to the global namespace. I would like to keep my own functions
> > in a separate module and then import that module to the main script
> > (that will be executed using the CLI interpreter). The problem is, I
> > cannot access the functions in the global namespace of the main script
> > from my module. Is there anyway to do that ?
> 
>
> I think you're doing it backwards. If you want access to AddPlot, then
> you should import mainscript into that module instead of the other way
> around. When I have common methods I want to call from different
> scripts, I put those methods/functions into their own module/file.
> Then I just import the module and call whatever script I need.
>
> 
>
> commonMods.py
> -
> AddPlot(*args, *kwargs):
> # Do something
> DrawPlots(*args, *kwargs):
> # Do something
> -

Hi Mike,
The problem is I don't define the functions AddPlot() and DrawPlots().
It's built into the python interpreter of the CLI version of the
program I mentioned, and they are defined on the main script. I load
the main script using something like "software -cli -s
mainscript.py".
In the mainscript.py I import myModule, but of course myModule does
not have access to the functions defined in the global namespace of
mainscript.py.

Thanks.
RDB

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


REALLY need help with iterating a list.

2007-06-11 Thread Radamand
This has been driving me buggy for 2 days, i need to be able to
iterate a list of items until none are left, without regard to which
items are removed. I'll put the relevant portions of code below,
please forgive my attrocious naming conventions.
Basically i'm trying to spin up some subprocesses that will ping a
group of servers and then wait until all of them have completed (good
or bad), store the ping result and the return code, and move on.
The problem comes in the second block, when i try to iterate the
list of servers and remove the ones that are finished, for some reason
Python appears to re-index the list when I remove an item and the next
step through the loop it cant find the item its expecting because the
indexes have changed.
Any assistance would be appreciated...

=
for server in serverlist:
ping[server] = subprocess.Popen("ping -c 1 " + str(server) + " 5",
shell=True, stdout=subprocess.PIPE)

while len(serverlist) > 0:
for server in serverlist:
if ping[server].returncode==None:
ping[server].poll()
else:
pingresult[server] = ping[server].stdout.read()
pingreturncode[server] = ping[server].returncode
serverlist.remove(server)

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


Re: with as a reserved word

2007-06-11 Thread Fredrik Lundh
BBands wrote:

> I gather that 'with' is on its way to becoming a reserved word. Is
> this something that will break?

yes.

> import Gnuplot
> gp = Gnuplot.Gnuplot(debug=1)
> data = Gnuplot.Data([1,2,3,4,3,2,3,4,3,2,1], with='linespoints')

if you have Python 2.5, you can try it out yourself:

 >>> dict(with=1)
:1: Warning: 'with' will become a reserved keyword in Python 2.6
{'with': 1}

 >>> from __future__ import with_statement
 >>> dict(with=1)
   File "", line 1
 dict(with=1)
 ^
SyntaxError: invalid syntax



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


Re: REALLY need help with iterating a list.

2007-06-11 Thread alg
Reverse iteration should do the trick, if I understand your problem:

for server in reversed(serverlist):
...
else:
serverlist.remove(server)

On Jun 11, 11:30 am, Radamand <[EMAIL PROTECTED]> wrote:
> This has been driving me buggy for 2 days, i need to be able to
> iterate a list of items until none are left, without regard to which
> items are removed. I'll put the relevant portions of code below,
> please forgive my attrocious naming conventions.
> Basically i'm trying to spin up some subprocesses that will ping a
> group of servers and then wait until all of them have completed (good
> or bad), store the ping result and the return code, and move on.
> The problem comes in the second block, when i try to iterate the
> list of servers and remove the ones that are finished, for some reason
> Python appears to re-index the list when I remove an item and the next
> step through the loop it cant find the item its expecting because the
> indexes have changed.
> Any assistance would be appreciated...
>
> =
> for server in serverlist:
> ping[server] = subprocess.Popen("ping -c 1 " + str(server) + " 5",
> shell=True, stdout=subprocess.PIPE)
>
> while len(serverlist) > 0:
> for server in serverlist:
> if ping[server].returncode==None:
> ping[server].poll()
> else:
> pingresult[server] = ping[server].stdout.read()
> pingreturncode[server] = ping[server].returncode
> serverlist.remove(server)


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


Re: Python for embedded systems with memory constraints

2007-06-11 Thread vishnu

Hello,

Using the best fit for Python will not be a problem, because Python makes
allocations of lot of small size blocks.So those split blocks of small sizes
are used by Python sometime. And what I observed from my investigation with
the memory manager(MM) for Python is , with any MM we cannot eliminate
fragmentation and even though  Python is memory hungry I cannot allot some
50MB (or more) just for python application because it will add to the
embedded system memory cost.
So now I only see the solution to clear my memory pool and restart Python
without restarting the system (i.e. no power cycle to hardware). I tried to
do this when my memory pool is 60% used in these steps:
1) Py_Finalize( )
2) Reset my Memory pool (i.e. free list links)
3) Then Restart Python by calling Py_Initialize().

But this resulted in Python  crash during Py_Initialize(), where I found
that the static variables within embedded Python source code are still
holding some of the references to my memory pool. So now my question is how
do I restart Python (i.e. reinitialize Python) without restarting whole
system. Is there a way to reset/re-initilaize those static variables such
that it will be possible to re-Initialize Python.


Vishnu


On 6/10/07, MRAB <[EMAIL PROTECTED]> wrote:

On Jun 9, 1:33 pm, vishnu <[EMAIL PROTECTED]> wrote:
> Hi,
> Thanks Cameron for your suggestions.
> In fact I am using custom memory sub-allocator where I preallocate a
> pool of memory during initialization of my application and ensure that
> Python doesn't make any system mallocs later . With this arrangement,
> python seems to run out of preallocated memory (of 10MB) after running
> few simple scripts due to huge external fragmentation. My memory
> sub-allocator got a good design which uses the best-fit algorithm and
> coaelescing the adjacent blocks during each free call.
> If anybody out there used their own memory manager and ran Python
> without fragmentation , could provide some inputs on this.
>
>From what I remember, the best-fit algorithm isn't a good idea because
unless the free block was exactly the right size you'd tend to get
left with lots of small fragments. (Suppose that the best fit was a
free block only 4 bytes bigger than what you want; what can you do
with a free block of 4 bytes?)

A worst-fit algorithm would leave larger free blocks which are more
useful subsequently, but I think that the recommendation was next-fit
(ie use the first free block that's big enough, starting from where
you found the last one).

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

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

Re: Repository - file scanner

2007-06-11 Thread HMS Surprise


Thank you all.

jh

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


Re: REALLY need help with iterating a list.

2007-06-11 Thread infidel
On Jun 11, 11:30 am, Radamand <[EMAIL PROTECTED]> wrote:
> This has been driving me buggy for 2 days, i need to be able to
> iterate a list of items until none are left, without regard to which
> items are removed. I'll put the relevant portions of code below,
> please forgive my attrocious naming conventions.
> Basically i'm trying to spin up some subprocesses that will ping a
> group of servers and then wait until all of them have completed (good
> or bad), store the ping result and the return code, and move on.
> The problem comes in the second block, when i try to iterate the
> list of servers and remove the ones that are finished, for some reason
> Python appears to re-index the list when I remove an item and the next
> step through the loop it cant find the item its expecting because the
> indexes have changed.
> Any assistance would be appreciated...
>
> =
> for server in serverlist:
> ping[server] = subprocess.Popen("ping -c 1 " + str(server) + " 5",
> shell=True, stdout=subprocess.PIPE)
>
> while len(serverlist) > 0:
> for server in serverlist:
> if ping[server].returncode==None:
> ping[server].poll()
> else:
> pingresult[server] = ping[server].stdout.read()
> pingreturncode[server] = ping[server].returncode
> serverlist.remove(server)

How about something like this?

while serverlist:
server = serverlist.pop(0)
pinger = ping[server]
if pinger.returncode==None:
pinger.poll()
serverlist.append(server)
else:
pingresult[server] = pinger.stdout.read()
pingreturncode[server] = pinger.returncode

Basic idea:  as long as there are servers in the list, pop the first
one out of the list, see if it's done, and if it isn't, put it back on
the end of the list.

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


Re: Repository - file scanner

2007-06-11 Thread Paul Rudin
HMS Surprise <[EMAIL PROTECTED]> writes:

>>
>> Why not use grep?
>
> With Windows XP?

www.cygwin.com

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


Re: Repository - file scanner

2007-06-11 Thread John Machin
On Jun 12, 4:46 am, Paul Rudin <[EMAIL PROTECTED]> wrote:
> HMS Surprise <[EMAIL PROTECTED]> writes:
>
> >> Why not use grep?
>
> > With Windows XP?
>
> www.cygwin.com

Using cygwin for this problem is like using a sledgehammer to crack a
nut.

See http://gnuwin32.sourceforge.net/summary.html
*Lots* of goodies there.

HTH,
John

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


Re: with as a reserved word

2007-06-11 Thread BBands
On Jun 11, 11:34 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> if you have Python 2.5, you can try it out yourself:
>
>  >>> dict(with=1)
> :1: Warning: 'with' will become a reserved keyword in Python 2.6
> {'with': 1}
>
>  >>> from __future__ import with_statement
>  >>> dict(with=1)
>File "", line 1
>  dict(with=1)
>  ^
> SyntaxError: invalid syntax

I see that this change appears to be final.

http://www.python.org/dev/peps/pep-0343/

I don't have an opinion, pro or con, on this PEP, but I'll bet that it
breaks a lot of code.

jab

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


Re: REALLY need help with iterating a list.

2007-06-11 Thread Fredrik Lundh
infidel wrote:

> How about something like this?
> 
> while serverlist:
> server = serverlist.pop(0)
> pinger = ping[server]
> if pinger.returncode==None:
> pinger.poll()
> serverlist.append(server)
> else:
> pingresult[server] = pinger.stdout.read()
> pingreturncode[server] = pinger.returncode
> 
> Basic idea:  as long as there are servers in the list, pop the first
> one out of the list, see if it's done, and if it isn't, put it back on
> the end of the list.

here's a simple variation of that, which is a bit more efficient, and 
perhaps also a bit easier to use in the general case:

while serverlist:
 still_active = []
 for server in serverlist:
pinger = ping[server]
if pinger.returncode is None:
pinger.poll()
still_active.append(server)
else:
pingresult[server] = pinger.stdout.read()
pingreturncode[server] = pinger.returncode
 serverlist = still_active



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


Re: Accessing global namespace from module

2007-06-11 Thread Gabriel Genellina
En Mon, 11 Jun 2007 15:18:58 -0300, reubendb <[EMAIL PROTECTED]> escribió:

> The problem is I don't define the functions AddPlot() and DrawPlots().
> It's built into the python interpreter of the CLI version of the
> program I mentioned, and they are defined on the main script. I load
> the main script using something like "software -cli -s
> mainscript.py".
> In the mainscript.py I import myModule, but of course myModule does
> not have access to the functions defined in the global namespace of
> mainscript.py.

Don't you have some import statements at the top of mainscript.py that are  
responsible for bringing AddPlot and DrawPlots into the current namespace?  
Import the same things in your second module.

-- 
Gabriel Genellina

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


Re: Postpone creation of attributes until needed

2007-06-11 Thread Steven Bethard
George Sakkis wrote:
> On Jun 11, 8:27 am, Frank Millman <[EMAIL PROTECTED]> wrote:
>> On Jun 11, 1:56 pm, Steven D'Aprano
>>
>> <[EMAIL PROTECTED]> wrote:
>>
>>> Unless you have thousands and thousands of instances, __slots__ is almost
>>> certainly not the answer. __slots__ is an optimization to minimize the
>>> size of each instance. The fact that it prevents the creation of new
>>> attributes is a side-effect.
>> Understood - I am getting there slowly.
>>
>> I now have the following -
>>
> class A(object):
>> ...def __init__(self,x,y):
>> ...self.x = x
>> ...self.y = y
>> ...def __getattr__(self,name):
>> ...print 'getattr',name
>> ...self.compute()
>> ...return self.__dict__[name]
>> ...def compute(self):  # compute all missing attributes
>> ...self.__dict__['z'] = self.x * self.y
>>[there could be many of these]
>>
> a = A(3,4)
> a.x
>> 3
> a.y
>> 4
> a.z
>> getattr z
>> 12>>> a.z
>> 12
> a.q
>> KeyError: 'q'
>>
>> The only problem with this is that it raises KeyError instead of the
>> expected AttributeError.
>>
>>
>>
>>> You haven't told us what the 'compute' method is.
>>> Or if you have, I missed it.
>> Sorry - I made it more explicit above. It is the method that sets up
>> all the missing attributes. No matter which attribute is referenced
>> first, 'compute' sets up all of them, so they are all available for
>> any future reference.
>>
>> To be honest, it feels neater than setting up a property for each
>> attribute.
> 
> I don't see why this all-or-nothing approach is neater; what if you
> have a hundred expensive computed attributes but you just need one ?
> Unless you know this never happens in your specific situation because
> all missing attributes are tightly coupled, properties are a better
> way to go. The boilerplate code can be minimal too with an appropriate
> decorator, something like:
> 
> class A(object):
> 
> def __init__(self,x,y):
> self.x = x
> self.y = y
> 
> @cachedproperty
> def z(self):
> return self.x * self.y
> 
> 
> where cachedproperty is
> 
> def cachedproperty(func):
> name = '__' + func.__name__
> def wrapper(self):
> try: return getattr(self, name)
> except AttributeError: # raised only the first time
> value = func(self)
> setattr(self, name, value)
> return value
> return property(wrapper)

And, if you don't want to go through the property machinery every time, 
you can use a descriptor that only calls the function the first time:

 >>> class Once(object):
... def __init__(self, func):
... self.func = func
... def __get__(self, obj, cls=None):
... if obj is None:
... return self
... else:
... value = self.func(obj)
... setattr(obj, self.func.__name__, value)
... return value
...
 >>> class A(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
... @Once
... def z(self):
... print 'calculating z'
... return self.x * self.y
...
 >>> a = A(2, 3)
 >>> a.z
calculating z
6
 >>> a.z
6

With this approach, the first time 'z' is accessed, there is no 
instance-level 'z', so the descriptor's __get__ method is invoked. That 
method creates an instance-level 'z' so that every other time, the 
instance-level attribute is used (and the __get__ method is no longer 
invoked).

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


Re: Repository - file scanner

2007-06-11 Thread Gabriel Genellina
En Mon, 11 Jun 2007 15:46:51 -0300, Paul Rudin <[EMAIL PROTECTED]>  
escribió:

> HMS Surprise <[EMAIL PROTECTED]> writes:
>>>
>>> Why not use grep?
>>
>> With Windows XP?
>
> www.cygwin.com

Why? Try findstr /? at the command prompt.

-- 
Gabriel Genellina

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


Re: with as a reserved word

2007-06-11 Thread Fredrik Lundh
BBands wrote:

> I don't have an opinion, pro or con, on this PEP, but I'll bet that it
> breaks a lot of code.

that's why you get warnings in 2.5, so you have time to update your 
code; see:

 http://www.python.org/dev/peps/pep-0005/

estimating what "a lot" is isn't trivial, but it's worth noting that a 
search for "lang:python \swith\W" over at google's code search only 
brings up about 200 cases, and most of those are found in comments and 
string literals.  and in Zope.



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


Re: REALLY need help with iterating a list.

2007-06-11 Thread Radamand
On Jun 11, 1:23 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> infidel wrote:
> > How about something like this?
>
> > while serverlist:
> > server = serverlist.pop(0)
> > pinger = ping[server]
> > if pinger.returncode==None:
> > pinger.poll()
> > serverlist.append(server)
> > else:
> > pingresult[server] = pinger.stdout.read()
> > pingreturncode[server] = pinger.returncode
>
> > Basic idea:  as long as there are servers in the list, pop the first
> > one out of the list, see if it's done, and if it isn't, put it back on
> > the end of the list.
>
> here's a simple variation of that, which is a bit more efficient, and
> perhaps also a bit easier to use in the general case:
>
> while serverlist:
>  still_active = []
>  for server in serverlist:
> pinger = ping[server]
> if pinger.returncode is None:
> pinger.poll()
> still_active.append(server)
> else:
> pingresult[server] = pinger.stdout.read()
> pingreturncode[server] = pinger.returncode
>  serverlist = still_active
>
> 

Thats an interesting approach but, if the returncode for a given
server is None say, 20 times in a row you will have append'ed that
server to the list 20 times, i suppose you could check the list to see
if its already there but thats a bit kludgey...

also, the line "pinger = ping[server]" would have to be extracted from
this loop otherwise your going to ping the same server repeatedly
until it answers...

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


Link Dictionary

2007-06-11 Thread anush shetty
Hi,
I have two dictionaries

 dict1={'B8': set(['I8', 'H8', 'B2', 'B7', 'F8', 'C9', 'G8', 'B4',
'B5', 'B6', 'C8', 'E8', 'D8', 'B3', 'A9', 'A8', 'C7', 'B9', 'A7',
'B1']), 'B9': set(['I9', 'H9', 'A7', 'F9', 'B3', 'B6', 'G9', 'B4',
'B5', 'C9', 'B7', 'E9', 'B1', 'B2', 'D9', 'A9', 'A8', 'C8', 'B8',
'C7']), 'D1': set(['F1', 'F2', 'F3', 'G1', 'I1', 'D2', 'H1', 'A1',
'D4', 'B1', 'D8', 'D9', 'D6', 'D7', 'C1', 'D5', 'E1', 'D3', 'E3',
'E2'])}

and
dict2=
{'I6': '0', 'H9': '9', 'I2': '0', 'E8': '0', 'H3': '0', 'H7': '0',
'I7': '3', 'I4': '0', 'H5': '0', 'F9': '0', 'G7': '5', 'G6': '9',
'G5': '0', 'E1': '7', 'G3': '2', 'G2': '0', 'G1': '0', 'I1': '0',
'C8': '0', 'I3': '5', 'E5': '0', 'I5': '1', 'C9': '0', 'G9': '0',
'G8': '0', 'A1': '0', 'A3': '3', 'A2': '0', 'A5': '2', 'A4': '0',
'A7': '6', 'A6': '0', 'C3': '1', 'C2': '0', 'C1': '0', 'E6': '0',
'C7': '4', 'C6': '6', 'C5': '0', 'C4': '8', 'I9': '0', 'D8': '0',
'I8': '0', 'E4': '0', 'D9': '0', 'H8': '0', 'F6': '8', 'A9': '0',
'G4': '6', 'A8': '0', 'E7': '0', 'E3': '0', 'F1': '0', 'F2': '0',
'F3': '6', 'F4': '7', 'F5': '0', 'E2': '0', 'F7': '2', 'F8': '0',
'D2': '0', 'H1': '8', 'H6': '3', 'H2': '0', 'H4': '2', 'D3': '8',
'B4': '3', 'B5': '0', 'B6': '5', 'B7': '0', 'E9': '8', 'B1': '9',
'B2': '0', 'B3': '0', 'D6': '2', 'D7': '9', 'D4': '1', 'D5': '0',
'B8': '0', 'B9': '1', 'D1': '0'}

Now I want to create a dict which would have both the keys and values
to be of the corresponding values of dict2.

Something like this:

Eg. The first key in dict1 i.e. B8 as 0 (0 is the value of B8 in
dict2) mapped as set(['0','0','0',...]).

Can anyone help me out with this.
-
Anush

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


ANN: papyros 0.1

2007-06-11 Thread George Sakkis
I am pleased to announce the first alpha release of Papyros, a
lightweight platform-independent package for parallel processing.
Papyros provides a master-slave model: clients can submit jobs to a
master object which is monitored by one or more slave objects that do
the real work. Two main implementations are provided, one using
multiple threads and one multiple processes in one or more hosts
through Pyro (http://pyro.sourceforge.net/).

Papyros' primary design goal is simplicity: a time consuming loop in a
single-thread single-process program can be replaced with an
equivalent parallel version in a few lines, with minimal boilerplate
code overhead.

To get a copy, visit http://code.google.com/p/papyros/; also available
from the Cheeseshop at http://www.python.org/pypi/papyros/.

George


Sample code
==
Here's a basic example; for more details go through the README and the
included demo script.

import papyros

class FactorizationJob(papyros.Job):
'''A job for computing the prime factors of an integer.'''
def __call__(self, n):
# <-- find the prime factors here --> #
return factors

# create a multithreded master with three slave threads
from papyros.multithreaded import MultiThreadedMaster
master = MultiThreadedMaster(3)

# factorize concurrently ten random numbers
import random
for _ in xrange(10):
master.addJob(FactorizationJob(random.randrange(1e6,1e7)))

# fetch each job as soon as it finishes
for job in iter(master.popProcessedJob, None):
factors = job.result
print '%d prime factors for %d: %s' % (len(factors), job.args[0],
factors)

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


ANN: xlrd 0.6.1 final is now available

2007-06-11 Thread John Machin
The final release of version 0.6.1 of xlrd is now available from
http://www.lexicon.net/sjmachin/xlrd.htm and from the Cheeseshop
(http://cheeseshop.python.org/pypi/xlrd).

What is xlrd? It's a small (download approx 0.1 Mb) pure-Python
library for extracting information  from Microsoft Excel (tm) files,
anywhere Python 2.1 or later will run -- no need for Excel itself, nor
COM, nor even Windows. Further info: follow the links on the home
page.

This major release incorporates the functionality of 0.6.0 which was
not released independently for various reasons including the need to
push ahead with the 0.6.1 functionality.

New in 0.6.0: facility to access named cell ranges and named
constants (Excel UI: Insert/Name/Define).

New in 0.6.1: extracts formatting information for cells (font, "number
format", background, border, alignment and protection) and rows/
columns (height/width etc). To save memory and time for those who
don't need it, this information is extracted only if formatting_info=1
is supplied to the open_workbook() function. The cell records BLANK
and MULBLANKS which contain no data, only formatting information, will
continue to be ignored in the default (no formatting info) case.

There have been several changes made to handle anomalous files
(written by
3rd party software) which Excel will open without complaint, but
failed
with xlrd, usually because an assertion fails or xlrd deliberately
raises an exception. Refer to HISTORY.html for details. These have
been changed to accept the anomaly either silently or with a NOTE
message  or a WARNING message, as appropriate.

Many thanks are due to Simplistix Ltd
(http://www.simplistix.co.uk). for funding the new functionality in
0.6.1.

Since 0.6.1a4 was released in February, only one bug-fix and some
tidying up have been done --  see HISTORY.html for details.

Feedback: general discussion on the python-excel newsgroup (sign
up at http://groups.google.com.au/group/python-excel?lnk=li&hl=en) or
mailto: [EMAIL PROTECTED] preferably with [xlrd] as part of the
message
subject.

Cheers,
John

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


Re: REALLY need help with iterating a list.

2007-06-11 Thread Radamand
On Jun 11, 12:59 pm, infidel <[EMAIL PROTECTED]> wrote:
> On Jun 11, 11:30 am, Radamand <[EMAIL PROTECTED]> wrote:
>
>
>
> > This has been driving me buggy for 2 days, i need to be able to
> > iterate a list of items until none are left, without regard to which
> > items are removed. I'll put the relevant portions of code below,
> > please forgive my attrocious naming conventions.
> > Basically i'm trying to spin up some subprocesses that will ping a
> > group of servers and then wait until all of them have completed (good
> > or bad), store the ping result and the return code, and move on.
> > The problem comes in the second block, when i try to iterate the
> > list of servers and remove the ones that are finished, for some reason
> > Python appears to re-index the list when I remove an item and the next
> > step through the loop it cant find the item its expecting because the
> > indexes have changed.
> > Any assistance would be appreciated...
>
> > =
> > for server in serverlist:
> > ping[server] = subprocess.Popen("ping -c 1 " + str(server) + " 5",
> > shell=True, stdout=subprocess.PIPE)
>
> > while len(serverlist) > 0:
> > for server in serverlist:
> > if ping[server].returncode==None:
> > ping[server].poll()
> > else:
> > pingresult[server] = ping[server].stdout.read()
> > pingreturncode[server] = ping[server].returncode
> > serverlist.remove(server)
>
> How about something like this?
>
> while serverlist:
> server = serverlist.pop(0)
> pinger = ping[server]
> if pinger.returncode==None:
> pinger.poll()
> serverlist.append(server)
> else:
> pingresult[server] = pinger.stdout.read()
> pingreturncode[server] = pinger.returncode
>
> Basic idea:  as long as there are servers in the list, pop the first
> one out of the list, see if it's done, and if it isn't, put it back on
> the end of the list.

I like this idea, ill try it out asap.

ok, tried it, works perfectly!!  It never occurred to me to use pop to
pull one off and put it back on if it wasnt done, very nice!  Thank
You!!

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


Re: Accessing global namespace from module

2007-06-11 Thread reubendb
On Jun 11, 3:30 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Mon, 11 Jun 2007 15:18:58 -0300, reubendb <[EMAIL PROTECTED]> escribió:
>
> > The problem is I don't define the functions AddPlot() and DrawPlots().
> > It's built into the python interpreter of the CLI version of the
> > program I mentioned, and they are defined on the main script. I load
> > the main script using something like "software -cli -s
> > mainscript.py".
> > In the mainscript.py I import myModule, but of course myModule does
> > not have access to the functions defined in the global namespace of
> > mainscript.py.
>
> Don't you have some import statements at the top of mainscript.py that are
> responsible for bringing AddPlot and DrawPlots into the current namespace?
> Import the same things in your second module.

No, I *don't* have any import statement mainscript.py. When using this
software's CLI, AddPlot and DrawPlots are available to me
automagically from mainscript.py. Hence my question: How do I make
this available from other module. Is there any way at all ?

Thanks.
RDB

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

  1   2   >