selective logger disable/enable

2007-01-18 Thread Gary Jefferson
Suppose I have 3 modules that belong to a project, 'A', 'A.a' and 'B',
and each module has its own logger, created with:

module1logger = logging.getLogger('project.A')

and

module2logger = logging.getLogger('project.A.a')

and

module3logger = logging.getLogger('project.B')


And I want to selectively enable/disable these, per module (for
example, I only want logging from A and A.a, or just from B, etc).  It
seems like logging.Filter is supposed to let me do this, but I can't
see how to apply it globally.  Is there really no other way that to add
a addFilter(filter) call to each of these loggers individually?

logging.basicConfig gets inherited by all loggers, but it doesn't seem
capable of giving a Filter to all loggers.  Is there any way to do this?

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


Re: Why this script can work?

2007-01-18 Thread Robert Kern
Jm lists wrote:
> Please help with this script:
> 
> class ShortInputException(Exception):
> '''A user-defined exception class.'''
> def __init__(self,length,atleast):
> Exception.__init__(self)
> self.length=length
> self.atleast=atleast
> 
> try:
> s=raw_input('Enter something --> ')
> if len(s)<3:
> raise ShortInputException(len(s),3)
> # Other work can continue as usual here
> except EOFError:
> print '\nWhy did you do an EOF on me?'
> except ShortInputException,x:
> print 'ShortInputException: The input was of length %d, was
> expecting at least %d' %(x.length,x.atleast)
> else:
> print 'No exception was raised.'
> 
> 
> My questions are:
> 
> 1) ShortInputException,x:   what's the 'x'? where is it coming?

It's the actual ShortInputException instance that was raised. Try printing
x.length and x.atleast, for example.

> 2) The 'if' and 'else' are not in the same indent scope,why this can work?

This else: clause goes with the try: and except: clauses, not the if: clause. It
is executed if no exception was raised.

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

-- 
Robert Kern

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

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


Why this script can work?

2007-01-18 Thread Jm lists
Please help with this script:

class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast

try:
s=raw_input('Enter something --> ')
if len(s)<3:
raise ShortInputException(len(s),3)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException,x:
print 'ShortInputException: The input was of length %d, was
expecting at least %d' %(x.length,x.atleast)
else:
print 'No exception was raised.'


My questions are:

1) ShortInputException,x:   what's the 'x'? where is it coming?

2) The 'if' and 'else' are not in the same indent scope,why this can work?

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


Re: How to pass arguments to the function embedded in the timeit.Timer()

2007-01-18 Thread Gabriel Genellina

At Thursday 18/1/2007 21:31, Dongsheng Ruan wrote:


  Does anybody know how to pass multiple arguments to the function
tested in timeit.timer() in
python?

I googled and found how to pass one argument:

x=1
mytime = timeit.Timer( setup="from Createlst import createlst", stmt=
"createlst(%s)"%(x) )


This is the % operator for strings, and it's general, not related to 
the timeit module.
You can find it explained in almost every tutorial. The "official" 
tutorial explains it here:
 and for more 
detailed usage see here:



If you haven't already done it, I strongly recommend reading the 
Python tutorial (you should find it inside your Python installation, 
and you can read it online at  )



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Determining when a file is an Open Office Document

2007-01-18 Thread tubby
Ross Ridge wrote:
> tubby wrote:
>> Silly question, but here goes... what's a good way to determine when a
>> file is an Open Office document? I could look at the file extension, but
>> it seems there would be a better way. VI shows this info in the files:
>>
>> mimetypeapplication/vnd.oasis.opendocument.textPK
> 
> It's a ZIP archive. 

Thanks, I used this approach:

import zipfile
if zipfile.is_zipfile(filename):
...

Now, If only I could something like that on PDF files :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterator length

2007-01-18 Thread Gabriel Genellina

At Thursday 18/1/2007 20:26, [EMAIL PROTECTED] wrote:


def leniter(iterator):
"""leniter(iterator): return the length of an iterator,
consuming it."""
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements

Is it a good idea to extend the functionalities of the built-in len
function to cover such situation too?


I don't think so, because it may consume the iterator, and that's a 
big side effect that one would not expect from builtin len()



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Anyone has a nice "view_var" procedure ?

2007-01-18 Thread Gabriel Genellina

At Thursday 18/1/2007 19:24, Stef Mientki wrote:


> str(key)[7:-2] => key.__name__
I didn't know that one


It's here: http://docs.python.org/lib/specialattrs.html


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Making a simple script standalone

2007-01-18 Thread Ravi Teja


On Jan 18, 2:19 pm, Rikishi 42 <[EMAIL PROTECTED]> wrote:
> On Thursday 18 January 2007 10:13, robert wrote:
>
> > stay with py23 for "a script" (and more) and make <700kB
> > independent distros - UPX and 7zip involved:
>
> >http://groups.google.com/group/comp.lang.python/msg/edf469a1b3dc3802Thanks, 
> >that might be an option. But I might just convince the person to
> let me install Python.  :-(

Like you note, it is far simpler to just install Python. Rarely does a
proper cost benefit analysis show any advantage for all the time you
put in for saving a few MB off the installer (since you noted that you
got it working with Py2Exe), especially when you seem to be installing
the app for just one person. How big is your Exe with Py2Exe? Say 3MB?
Is making it 1 MB worth maybe 2 hrs of your time for 1 install?

But just for kicks, check out ShedSkin. Since you mentioned that you
were using very few modules (ShedSkin supports os, stat, string, time),
it might just work. ShedSkin translates your Python code to fast C++
code that can be compiled to a tight app.

http://sourceforge.net/projects/shedskin/

Ravi Teja.

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


subclassing pyrex extension types in python

2007-01-18 Thread Nitin
Hi All

I am trying to subclass an extension type in Python and add attributes
to the new class but I keep getting errors. I read the "Extension
Types" document on the Pyrex website but I couldn't get an answer from
it.

Here's the Spam extension type from Pyrex website:

cdef class Spam:

  cdef int amount

  def __new__(self):
self.amount = 0

  def get_amount(self):
return self.amount

Once compiled, here's how I am using this:

import spam

class mySpam(spam.Spam):
def __init__(self, name1=None, name2=None):
spam.Spam.__init__(self)
self.name1 = name1
self.name2 = name2

When I run this Python code, I get an error "TypeError: 'name2' is an
invalid keyword argument for this function"

Is there something I need to know about Pyrex extension types and
keyword arguments ? I tried to google for this but couldn't come up
with anything.

Thanks !
Nitin

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


Re: Match 2 words in a line of file

2007-01-18 Thread Rickard Lindberg
I see two potential problems with the non regex solutions.

1) Consider a line: "foo (bar)". When you split it you will only get
two strings, as split by default only splits the string on white space
characters. Thus "'bar' in words" will return false, even though bar is
a word in that line.

2) If you have a line something like this: "foobar hello" then "'foo'
in line" will return true, even though foo is not a word (it is part of
a word).

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


Re: More M2Crypto issues

2007-01-18 Thread Gabriel Genellina

At Thursday 18/1/2007 04:41, John Nagle wrote:


   I've been running M2Crypto successfully using Python 2.4 on Windows 2000,
and now I'm trying to get it to work on Python 2.3.4 on Linux.

   Attempting to initialize a context results in

Traceback (most recent call last):
   File "/www/htdocs/sitetruth.com/cgi/ratingdetails.cgi", line 46, in ?
 DetailsPageBuilder.detailspage(kdbfile,ktemplatefile,url)  # check and
display domain or URL as web page
   File "./sitetruth/DetailsPageBuilder.py", line 70, in detailspage
 sitecert = InfoSSL2.Certificate(siteinfo, kverifylocations, verbose)
   File "./sitetruth/InfoSSL2.py", line 147, in __init__
 self.ctx = createsslcontext(trustedcafile, verbose)# 
Generate general SSL

context
   File "./sitetruth/InfoSSL2.py", line 40, in createsslcontext
 ctx = 
SSL.Context('sslv3') 
  # Create context with SSL params
   File "/home/sitetruth/lib/python/M2Crypto/SSL/Context.py", line 
43, in __init__

 map()[long(self.ctx)] = self
ValueError: invalid literal for long(): _480e1008_p_SSL_CTX


On a previous version of M2Crypto that line said: map()[self.ctx] = 
self, and that failed too ("unhashable object", I think).
I changed the class _ctxmap (the map() above returns an instance of 
it) to use str(key) in the 3 places it was used. (That would be 
equivalent to use str(self.ctx) everywhere, instead of long(self.ctx) 
as your traceback is showing). All I can say is that no error 
happened afterwards, but I don't know if that broke something. (and I 
didn't care at the moment, I only needed a Zope instance running on 
Windows with SSL for less than a week - and if it were "cheating SSL" 
it was OK for me then)



which, when I look at the code and try some test cases, seems
legitimate.  The cacheing code is trying to convert a reference to an
object (a C object, in fact) into a "long".  Python 2.4 on Windows
will do that.  Python 2.3.4 on Linux converts it to a string first,
gets "_480e1008_p_SSL_CTX", and then tries to convert that to an
integer, which fails.


So using str() appears, at least on the surface, to be reasonable. 
But someone with more intimate knowledge of the library should 
confirm that. I don't even understand what's the point for the 
_ctxmap singleton - it's the same thing as a global dictionary, isn't it?



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Match 2 words in a line of file

2007-01-18 Thread bearophileHUGS
MrJean1 wrote:
> def lines_with_words(file, word1, word2):
> """Print all lines in file that have both words in it."""
> for line in file:
> words = line.split()
> if word1 in words and word2 in words:
> print line

This sounds better, it's probably faster than the RE version, Python
2.5 has a really fast str.__contains__ method, done by effbot:

def lines_with_words(file, word1, word2):
"""Print all lines in file that have both words in it.
(word1 may be the less frequent word of the two)."""
for line in file:
if word1 in line and word2 in line:
print line

Bye,
bearophile

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


Re: Match 2 words in a line of file

2007-01-18 Thread MrJean1
Without using re, this may work (untested ;-):

def lines_with_words(file, word1, word2):
"""Print all lines in file that have both words in it."""
for line in file:
words = line.split()
if word1 in words and word2 in words:
print line


/Jean Brouwers


Rickard Lindberg wrote:
> [EMAIL PROTECTED] wrote:
> > Hi
> >
> > Am pretty new to python and hence this question..
> >
> > I have file with an output of a process. I need to search this file one
> > line at a time and my pattern is that I am looking for the lines that
> > has the word 'event' and the word 'new'.
> >
> > Note that i need lines that has both the words only and not either one
> > of them..
> >
> > how do i write a regexp for this.. or better yet shd i even be using
> > regexp or is there a better way to do this
> >
> > thanks
>
> Maybe something like this would do:
>
> import re
>
> def lines_with_words(file, word1, word2):
> """Print all lines in file that have both words in it."""
> for line in file:
> if re.search(r"\b" + word1 + r"\b", line) and \
>re.search(r"\b" + word2 + r"\b", line):
> print line
>
> Just call the function with a file object and two strings that
> represent the words that you want to find in each line.
>
> To match a word in regex you write "\bWORD\b".
>
> I don't know if there is a better way of doing this, but I believe that
> this should at least work.

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


Re: Determining when a file is an Open Office Document

2007-01-18 Thread Ross Ridge
tubby wrote:
> Silly question, but here goes... what's a good way to determine when a
> file is an Open Office document? I could look at the file extension, but
> it seems there would be a better way. VI shows this info in the files:
>
> mimetypeapplication/vnd.oasis.opendocument.textPK

It's a ZIP archive.  The info you've found are the file name
"mimetype", the uncompressed contents of that file
"application/vnd.oasis.opendocument.text", and part of the ZIP magic
number "PK".  You should be able to use the "zipfile" module to check
to see if the file a ZIP file, if it has a member named "mimetype" and
if the contents of the file match one of the OpenOffice MIME types.

  Ross Ridge

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


Re: Determining when a file is an Open Office Document

2007-01-18 Thread Ross Ridge
tubby wrote:
> Silly question, but here goes... what's a good way to determine when a
> file is an Open Office document? I could look at the file extension, but
> it seems there would be a better way. VI shows this info in the files:
>
> mimetypeapplication/vnd.oasis.opendocument.textPK

It's a ZIP archive.  The info you've found are the file name
"mimetype", the uncompressed contents of that file
"application/vnd.oasis.opendocument.text", and part of the ZIP magic
number "PK".  You should be able to use the "zipfile" module to check
to see if the file a ZIP file, if it has a member named "mimetype" and
if the contents of the file match one of the OpenOffice MIME types.

  Ross Ridge

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


Re: Using lambda with a Pmw.ComboBox

2007-01-18 Thread Willie
I will post a sample tomorrow AM.

James Stroud wrote:
> Can you show us your code? Your question is ambiguous to me. Comboboxes
> do not hold widgets but display text.

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


Re: Determining when a file is an Open Office Document

2007-01-18 Thread Ben Finney
tubby <[EMAIL PROTECTED]> writes:

> Silly question, but here goes... what's a good way to determine when
> a file is an Open Office document? I could look at the file
> extension, but it seems there would be a better way.

Yes, the name of a file may be useful for communicating with humans
about that file's intended use, but is a lousy, unreliable way to make
a definite statement about the actual contents of the file.

The Unix 'file' command determines the type of a file by its contents,
not its name. This functionality is essentially a database of "magic"
byte patterns mapping to file types, and is provided by a library
called "libmagic", distributed with most GNU/Linux distributions.

http://packages.debian.org/testing/source/file>

There is a Python interface to the "magic" functionality. It's in
Debian; I'm not sure if it's part of the "magic" code base, or written
separately to interface with it. Either way, you can get the source
for those packages and find out more.

http://packages.debian.org/unstable/python/python-magic>

-- 
 \ "If life deals you lemons, why not go kill someone with the |
  `\  lemons (maybe by shoving them down his throat)."  -- Jack Handey |
_o__)  |
Ben Finney

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


Re: Iterator length

2007-01-18 Thread Ben Finney
[EMAIL PROTECTED] writes:

> But sometimes you don't need the elements of a given iterator, you
> just need to know how many elements it has.

AFAIK, the iterator protocol doesn't allow for that.

Bear in mind, too, that there's no way to tell from outside that an
iterater even has a finite length; also, many finite-length iterators
have termination conditions that preclude knowing the number of
iterations until the termination condition actually happens.

-- 
 \   "When a well-packaged web of lies has been sold to the masses |
  `\over generations, the truth will seem utterly preposterous and |
_o__) its speaker a raving lunatic."  -- Dresden James |
Ben Finney

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


Determining when a file is an Open Office Document

2007-01-18 Thread tubby
Silly question, but here goes... what's a good way to determine when a 
file is an Open Office document? I could look at the file extension, but 
it seems there would be a better way. VI shows this info in the files:

mimetypeapplication/vnd.oasis.opendocument.textPK
mimetypeapplication/vnd.oasis.opendocument.presentationPK
etc.

Not really a Python specific question but, how do you guys do this sort 
of thing? I've figured out how to break out the content.xml file in the 
new OOo XML format, and do re searching and matching on that, now I just 
need a fast, reliable way to determine when I need to do that versus 
just reading the file.

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


Re: Using lambda with a Pmw.ComboBox

2007-01-18 Thread James Stroud
Willie wrote:
> Hi,
> 
> I have an array of 2 ComboBoxes. I would like to use lambda to report
> on which widget is being accessed. When I use arrays of other widgets I
> just use lambda to return which item I am using as an argument. This
> does not seem to work with ComboBox, the only thing returned is the
> value changed.
> 
> Can someone refer me to some code which shows this in action? I have
> searched the web for a solution, without any luck.
> 
> Thanks,
> 
> Willie
> 

Can you show us your code? Your question is ambiguous to me. Comboboxes 
do not hold widgets but display text.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterator length

2007-01-18 Thread bearophileHUGS
George Sakkis:
> Is this a rhetorical question ? If not, try this:

It wasn't a rhetorical question.


> >>> x = (i for i in xrange(100) if i&1)
> >>> if leniter(x): print x.next()

What's your point? Maybe you mean that it consumes the given iterator?
I am aware of that, it's written in the function docstring too. But
sometimes you don't need the elements of a given iterator, you just
need to know how many elements it has. A very simple example:

s = "aaabaabb"
from itertools import groupby
print [(h,leniter(g)) for h,g in groupby(s)]

Bye,
bearophile

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


Re: *POLL* How many sheeple believe in the 911 fairy tale and willing to accept an Orwellian doublespeak and enslavement world ?

2007-01-18 Thread MRAB

David Bostwick wrote:
> In article <[EMAIL PROTECTED]>, "Robert Hicks" <[EMAIL PROTECTED]> wrote:
> >Please, none of the real facts points to anything else except what
> >actually happened. Two planes hit two towers and they came down.
> >
>
> You're talking to the wind.  This is a conspiracy precisely because people
> deny the crackpots.  Denial of their "evidence" proves that there is a
> coverup.  Logic is not involved, only belief that doesn't respond to
> dissenting evidence.
>
Anything that supports it is evidence; anything that refutes it is
faked. You can't win!

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


Re: Iterator length

2007-01-18 Thread George Sakkis
[EMAIL PROTECTED] wrote:

> Often I need to tell the len of an iterator, this is a stupid example:
>
> >>> l = (i for i in xrange(100) if i&1)
>
> len isn't able to tell it:
>
> >>> len(l)
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: object of type 'generator' has no len()
>
> This is a bad solution, it may need too much memory, etc:
>
> >>> len(list(l))
>
> This is a simple solution in a modern Python:
>
> >>> sum(1 for _ in l)
> 50
>
> This is a faster solution (and Psyco helps even more):
>
> def leniter(iterator):
> """leniter(iterator): return the length of an iterator,
> consuming it."""
> if hasattr(iterator, "__len__"):
> return len(iterator)
> nelements = 0
> for _ in iterator:
> nelements += 1
> return nelements
>
> Is it a good idea to extend the functionalities of the built-in len
> function to cover such situation too?
>
> Bye,
> bearophile

Is this a rhetorical question ? If not, try this:

>>> x = (i for i in xrange(100) if i&1)
>>> if leniter(x): print x.next()

George

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


Using lambda with a Pmw.ComboBox

2007-01-18 Thread Willie
Hi,

I have an array of 2 ComboBoxes. I would like to use lambda to report
on which widget is being accessed. When I use arrays of other widgets I
just use lambda to return which item I am using as an argument. This
does not seem to work with ComboBox, the only thing returned is the
value changed.

Can someone refer me to some code which shows this in action? I have
searched the web for a solution, without any luck.

Thanks,

Willie

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


Free Downloads, Wallpapers, Games, Eroticgames, Handy-Logos and much more

2007-01-18 Thread Major27104
 
-- 
http://mail.python.org/mailman/listinfo/python-list


How to pass arguments to the function embedded in the timeit.Timer()

2007-01-18 Thread Dongsheng Ruan
Hi

  Does anybody know how to pass multiple arguments to the function 
tested in timeit.timer() in
python?

I googled and found how to pass one argument:

x=1
mytime = timeit.Timer( setup="from Createlst import createlst", stmt=
"createlst(%s)"%(x) )

But how can I extend it to two or more arguments?

Like this:

p1=createlst.createlst(1)
p2=createlst.createlst(1)
mytime = timeit.Timer(setup="from list_concat_copy import list_concat_copy",
stmt="list_concat_copy.list_concat_copy(%x,%y)"%p1,p2 )

I don't know how to end the timeit.Timer. Should it be (%x,%y)"%p1,p2  or
(%x,%y)"%p1,%p2 or (%x,%y)"(%p1%p2) .

I tried and none worked. I just got error message like global variable "A'
not defined.

Can anybody help?

Thanks!



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


Re: Match 2 words in a line of file

2007-01-18 Thread Rickard Lindberg
[EMAIL PROTECTED] wrote:
> Hi
>
> Am pretty new to python and hence this question..
>
> I have file with an output of a process. I need to search this file one
> line at a time and my pattern is that I am looking for the lines that
> has the word 'event' and the word 'new'.
>
> Note that i need lines that has both the words only and not either one
> of them..
>
> how do i write a regexp for this.. or better yet shd i even be using
> regexp or is there a better way to do this
>
> thanks

Maybe something like this would do:

import re

def lines_with_words(file, word1, word2):
"""Print all lines in file that have both words in it."""
for line in file:
if re.search(r"\b" + word1 + r"\b", line) and \
   re.search(r"\b" + word2 + r"\b", line):
print line

Just call the function with a file object and two strings that
represent the words that you want to find in each line.

To match a word in regex you write "\bWORD\b".

I don't know if there is a better way of doing this, but I believe that
this should at least work.

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


Pass 'this' to a python script in an extended application

2007-01-18 Thread Stou Sandalski
Hi,

I have an application consisting of a main C++ class (and other
classes) stored inside a DLL.  The application uses a small main
executable that links against the main DLL, then initializes and runs
the core class.  The python bindings are inside a .pyd module that also
links against the core DLL file.  I was able to generate the python
bindings against the core class using SWIG.   The application can now
be run either by the bootstrap executable or through the python console
like:

import foo
s = foo.MainClass()
s.run();

This is awesome, however I want to be able to launch python scripts
from within the application itself (no matter how it was started) and
supply these scripts with a "pointer" to the already initialized main
Class something like:

import foo

s = foo.GetMainClass()
s.someMethod().

I found this:

http://docs.python.org/ext/extending-with-embedding.html

but the problem is that I don't know how to "give" the python
interpreter a "pointer" to my class that will be compatible with the
already defined bindings that SWIG generated.  I am trying to keep the
core application dll from knowing about the .pyd extension module.
 
I apologize if this post belongs in a group dedicated to SWIG. 

Stou

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


Re: *POLL* How many sheeple believe in the 911 fairy tale and willing to accept an Orwellian doublespeak and enslavement world ?

2007-01-18 Thread schoenfeld . one

[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> > [EMAIL PROTECTED] wrote:
> > [...]
> >
> > Ask yourself, how can all these people, supposed physicists, engineers,
> > software developers, people of supposed intelligence be incapable of
> > understanding that fire cannot make buildings free fall? How can they
> > not understand that a free falling WTC 7 means it was a demolished WTC
> > 7? How is this possible?
>
> Only 3 or 4 presented themselves as sheeple denying it. A lot of others
> know it in their heart of heart and are quiet. The sharpest of them
> knew it
> immediately. That exactly was the coded message broadcast by Noam
> Chomsky
> that everyone will exploit 911 for their own reasons. He immediately
> understood it was an inside job and its exact purpose.
> But he is smart and drew further conclusions.
> Remember, he was into Kennedy's investigation and said: those who can
> do it and get away must be too powerful to confront [directly]. But
> that
> was a murder. This involves too much physics and chemistry.
> All those who are quiet know it. The event was very accurately
> exploited by the British, Italian, French, Dutch, intelligence agencies
> or political establishments or administrations, where ever there was a
> vulnerability towards fascism. But consider countries in europe
> where fascism has not taken root. There was no response. Just look
> at videos of reaction of people in the controlled demolition industry
> in europe. The videos are available with translation. Their reaction
> to the WTC7 fall is shocking. They know it is a professional inside
> job. There are going to be many random events in the fall of a
> big building so that there will be twists and turns and halts in the
> fall and its never going to fall straight on its footprint into a neat
> rubble filling the basement to the foundation like a pool with water.

If 3/4 already understand it is an inside job then it must be that they
don't speak out because of selfish reasons or because of cowardice. A
lot of them, as you say, may even seek to exploit the situation for
their own gain, for vanity and power. Most of them though probably
settle for their more lowly pleasures of getting to hate 'ragheads' and
'arabs'. So much for objectivity and reason.The amazing thing is that
all universities, all mainstream media institutions and all governments
are covering this thing up.


> > The reality is that it is possible. That's why the money changers do
> > what they do, and do it without fear of reprisal.
>
> Most dont care, and only scream when personally in pain as the
> relatives
> of 911 victims the first responders and Cindy Sheehan are doing.
>
> > Perhaps it is the fate of those who's forefathers conquered a nation to
> > one day wake up homeless in that nation - herded, branded, traded and
> > sold for the slaughter by the Zionist as they did the Negro. Perhaps
> > these Zionists, or whoever it is who is responsible for these acts, is
> > ultimately destined to the same fate.
>
> If they dont hang together, they will hang separately.

Let's hope the patriots win in the end. That would be fine sight to
see. Anyway, keep up the good work. I'm sure these mongoloids will see
reason one day..

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


Re: A note on heapq module

2007-01-18 Thread Paul Rubin
Steven Bethard <[EMAIL PROTECTED]> writes:
>  Heap(sequence=None, inplace=False)
>  KeyedHeap(key, sequence=None)
> Of course, this approach ends up with a bunch of code duplication again.

Maybe there's a way to use a metaclass that can make either type of
heap but they'd share most methods.
-- 
http://mail.python.org/mailman/listinfo/python-list


Match 2 words in a line of file

2007-01-18 Thread elrondrules
Hi

Am pretty new to python and hence this question..

I have file with an output of a process. I need to search this file one
line at a time and my pattern is that I am looking for the lines that
has the word 'event' and the word 'new'.

Note that i need lines that has both the words only and not either one
of them..

how do i write a regexp for this.. or better yet shd i even be using
regexp or is there a better way to do this

thanks

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


Re: what can be used in a signal handler

2007-01-18 Thread hg
Nick Maclaren wrote:

> 
> In article <[EMAIL PROTECTED]>,
> hg <[EMAIL PROTECTED]> writes:
> |> 
> |> I posted an equivalent question earlier ... but am still not sure:
> |> 
> |> I currently (under Linux) have a program that uses Queue.put
> |> (raw_input('')) in a signal handler and Queue.get() in the main/only
> |> thread.
> |> 
> |> It works but I want to know if it is legal / what type of synchro API I
> |> have the right to use in a signal handler.
> 
> Strictly, no and none.
> 
> C and POSIX's specifications of signal handling is a complete mess.
> ALL handling of ALL real signals is undefined behaviour, though few
> programmers realise that and POSIX depends on it.  As that would make
> all Unices (and Microsoft systems) unusable, you can reasonably assume
> that there is some signal handling that will work.
> 
> But what?  Which is where you came in.
> 
> The situation is that most things that seem to work do actually work,
> in some environments and under some circumstances.  You can never be
> sure when they will stop working, however, and all bets are off when
> you port signal handling code to a new system.  And, really but REALLY,
> do not mix it with very high levels of optimisation or rely on it
> being in any way thread safe.
> 
> I can't tell you whether the code of Queue is intended to work if an
> active Queue.get is interrupted by a signal which then does a Queue.put,
> but that is the sort of circumstance where things get very hairy.  Even
> if Python has code to enable that case, it won't be 100% reliable on all
> systems.
> 
> Sorry.  But that is the situation :-(
> 
> 
> Regards,
> Nick Maclaren.

Fair, I'll find a way around then.

Regards,

hg


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


Re: A note on heapq module

2007-01-18 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> Steven Bethard wrote:
>> The current code fails when using unbound methods however::
> 
> I don't like your solution, this class was already slow enough. Don't
> use unbound methods with this class :-)
> Maybe there's a (better) solution to your problem: to make Heap a
> function (or classmethod) that return sone of two possibile objects
> created by one of two different classes that have different methods...

That's probably viable.  Maybe you should just have two separate 
classes: Heap and KeyedHeap.  The inplace= parameter doesn't really make 
sense for a KeyedHeap anway, so you could just have::

 Heap(sequence=None, inplace=False)
 KeyedHeap(key, sequence=None)

Of course, this approach ends up with a bunch of code duplication again.

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


Iterator length

2007-01-18 Thread bearophileHUGS
Often I need to tell the len of an iterator, this is a stupid example:

>>> l = (i for i in xrange(100) if i&1)

len isn't able to tell it:

>>> len(l)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: object of type 'generator' has no len()

This is a bad solution, it may need too much memory, etc:

>>> len(list(l))

This is a simple solution in a modern Python:

>>> sum(1 for _ in l)
50

This is a faster solution (and Psyco helps even more):

def leniter(iterator):
"""leniter(iterator): return the length of an iterator,
consuming it."""
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements

Is it a good idea to extend the functionalities of the built-in len
function to cover such situation too?

Bye,
bearophile

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


Re: Making a simple script standalone

2007-01-18 Thread Rikishi 42
On Thursday 18 January 2007 10:13, robert wrote:
> stay with py23 for "a script" (and more) and make <700kB
> independent distros - UPX and 7zip involved:
> 
> http://groups.google.com/group/comp.lang.python/msg/edf469a1b3dc3802

Thanks, that might be an option. But I might just convince the person to
let me install Python.  :-(

-- 
Research is what I'm doing, when I don't know what I'm doing.
(von Braun)

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


Re: Regex Question

2007-01-18 Thread Bill Mill
Gabriel Genellina wrote:
> At Tuesday 16/1/2007 16:36, Bill  Mill wrote:
>
> > > py> import re
> > > py> rgx = re.compile('1?')
> > > py> rgx.search('a1').groups()
> > > (None,)
> > > py> rgx = re.compile('(1)+')
> > > py> rgx.search('a1').groups()
> >
> >But shouldn't the ? be greedy, and thus prefer the one match to the
> >zero? This is my sticking point - I've seen that plus works, and this
> >just confuses me more.
>
> Perhaps you have misunderstood what search does.
> search( pattern, string[, flags])
>  Scan through string looking for a location where the regular
> expression pattern produces a match
>
> '1?' means 0 or 1 times '1', i.e., nothing or a single '1'.
> At the start of the target string, 'a1', we have nothing, so the re
> matches, and returns that occurrence. It doesnt matter that a few
> characters later there is *another* match, even if it is longer; once
> a match is found, the scan is done.
> If you want "the longest match of all possible matches along the
> string", you should use findall() instead of search().
>

That is exactly what I misunderstood. Thank you very much.

-Bill Mill
bill.mill at gmail.com

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


Re: How to find out if another process is using a file

2007-01-18 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Donn Cave <[EMAIL PROTECTED]> writes:
|> > |> 
|> > |> O_EXCL fails if the file exists at all - whether closed or open.
|> > 
|> > Yes.  In theory.  In practice, it usually works on normal files, provided
|> > that all opens are local.  Under some circumstances, it will even work
|> > for NFS mounted files, as far as I recall.
|> 
|> Mm, by "fail", I meant
|> 
|> An attempt to open with O_EXCL set will "fail" if the file exists at all,
|> i.e., the file will not be opened, a negative value will be returned,
|> and errno will be set to EEXIST.
|> 
|> What I neglected to mention is that this effect obtains when O_EXCL
|> is used in combination with O_CREAT.  Without O_CREAT, O_EXCL doesn't
|> mean anything and is ignored.
|> 
|> If there is any significant difference between theory and practice
|> in this matter, it's news to me.

Actually, it is undefined behaviour in POSIX, and I have used a Unix
where O_EXCL on its own failed if the file existed (of course, it also
failed if it DIDN'T exist, because of the lack of O_CREAT).  I can't
remember which - perhaps AIX or OSF/1 (not DEC).

But I was referring to a different problem.  Some remote and parallel
filing systems handle such things very badly, and it is often possible
to create a file even if it exists and O_CREAT|O_EXCL is set.  A similar
remark applies to 'special' files, even on fairly mainstream, local
filing systems.


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


Re: How to write code to get focuse the application which is open from server

2007-01-18 Thread Mark
Hi,

There are better places to find me then on comp.lang.python (just too
much traffic for me)
pywinauto forums: http://forums.openqa.org/forum.jspa?forumID=15
or subscribe pywinauto mailing list:
https://lists.sourceforge.net/lists/listinfo/pywinauto-users


vithi wrote:

> MatchError: Could not find 'Print' in '['', u'Transparent Windows
> Client0', u'Transparent Windows Client2', u'Transparent Windows
> Client1', u'Print - Remote', u'Transparent Windows Client', u'Print
> - RemoteTransparent Windows Client']'
>
> This is the code
> import sys
> import time
> import application
> app = application.Application()
> qi=app.window_(title_re = ".*ArcView.*")
> time.sleep(2)
> qi.TypeKeys("%FP")
> time.sleep(2)
>
> app.Print.Ok.CloseClick()
>
>
My guess is that problem above is that teh title of the window is
u"Print - \\Remote", and "Print"  is not enough information for
pywinauto to go on.

I suggest you replace the last line with one of the following...
app.PrintRemote.Ok.CloseClick()
app.window_(title_re = "Print - .*").Ok.CloseClick()

Someone also was wondering why they do not have to call
Application.Start() or Application.Connect() explicitly - that is
because the first call to app.window_() will initialize the application
appropriately.  The reason for this is that most usages ended up being
a) Connect to a window with specific title, then use that window in the
next line - so I was trying to avoid duplication.

Thanks
  Mark

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


Re: A note on heapq module

2007-01-18 Thread bearophileHUGS
Steven Bethard wrote:
> The current code fails when using unbound methods however::

I don't like your solution, this class was already slow enough. Don't
use unbound methods with this class :-)
Maybe there's a (better) solution to your problem: to make Heap a
function (or classmethod) that return sone of two possibile objects
created by one of two different classes that have different methods...

Beside that, I think __eq__ method needs more tests, because comparing
a Heap with key against another Heap without key may give some
problems...

I'll think about such problems/things.

Bye,
bearophile

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


Re: How to find out if another process is using a file

2007-01-18 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (Nick Maclaren) wrote:
> In article <[EMAIL PROTECTED]>,
> Donn Cave <[EMAIL PROTECTED]> writes:
> |> In article <[EMAIL PROTECTED]>,
> |>  "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> |> > "Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje 
> |> > news:[EMAIL PROTECTED]

> |> > Use os.open with the O_EXCL flag; will fail if the other process has the 
> |> > file still open (and will fail if another process is reading the file, 
> |> > too, 
> |> > not just if someone is writing).
> |> 
> |> O_EXCL fails if the file exists at all - whether closed or open.
> 
> Yes.  In theory.  In practice, it usually works on normal files, provided
> that all opens are local.  Under some circumstances, it will even work
> for NFS mounted files, as far as I recall.

Mm, by "fail", I meant

An attempt to open with O_EXCL set will "fail" if the file exists at all,
i.e., the file will not be opened, a negative value will be returned,
and errno will be set to EEXIST.

What I neglected to mention is that this effect obtains when O_EXCL
is used in combination with O_CREAT.  Without O_CREAT, O_EXCL doesn't
mean anything and is ignored.

If there is any significant difference between theory and practice
in this matter, it's news to me.

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

Re: Anyone has a nice "view_var" procedure ?

2007-01-18 Thread Stef Mientki
thanks Gabriel

> str(key)[7:-2] => key.__name__

I didn't know that one

> Nice to see you built a useful tool! It's a great way to learn a language.

Yes, and this group is helping me a whole lot, thanks !

cheers,
Stef Mientki

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


Re: Module name to filename and back?

2007-01-18 Thread Ron Adam
Ron Adam wrote:
> Is there a function to find a filename from a dotted module (or package) name 
> without importing it?
> 
> The imp function find_module() doesn't work with dotted file names.  And it 
> looks like it may import the file as it raises an ImportError error exception 
> if 
>   it can't find the module. (Shouldn't it raise an IOError instead?)
> 
> What I'm looking for is to be able to get the full module name when I have a 
> filename.  And get the full filename when I have the module name.  And do 
> both 
> of these without importing the module.
> 
> modulename <==> filename
> filename <==> modulename

I found a partial answer in trace.py.  It has a fullmodname() function, but it 
doesn't do any validation so the name it returns is a guess.  Starting with it 
I 
tried to make it a bit more complete, but it still needs work.  Seems like 
there 
should be an easier way.

Ron



def importname(path):
 """ Get module or package name from a path name.

 Return None if path is invalid, or name is not a
 valid (reachable) package or module.

 """
 path = os.path.normcase(path)
 if not os.path.exists(path):
 return
 if path.endswith(os.sep):
 path = path[:-1]
 longest = ""
 for dir in sys.path:
 dir = os.path.normcase(dir) + os.sep
 if path.startswith(dir):
 if len(dir) > len(longest):
 longest = dir
 if longest:
 base = path[len(longest):]
 else:
 # should check if in current dir?
 return   # path not in search sys.path

 # This need a bit more work, it should also check
 # for valid parent packages too.
 if os.path.isdir(path):
 valid = False
 for ext in ['.py', '.pyc', '.pyo']:
 if os.path.isfile(os.path.join(path, '__init__' + ext)):
 valid = True
 break
 else:
 return

 base, ext = os.path.splitext(base)
 name = base.replace(os.sep, ".")
 if os.altsep:
 name = name.replace(os.altsep, ".")
 return name


path = "c:\\python25\\lib\\xml\\sax\\handler.py"
print importname(path)

prints --> xml.sax.handler


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


Re: *POLL* How many sheeple believe in the 911 fairy tale and willing to accept an Orwellian doublespeak and enslavement world ?

2007-01-18 Thread st911

[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> [...]
>
> Ask yourself, how can all these people, supposed physicists, engineers,
> software developers, people of supposed intelligence be incapable of
> understanding that fire cannot make buildings free fall? How can they
> not understand that a free falling WTC 7 means it was a demolished WTC
> 7? How is this possible?

Only 3 or 4 presented themselves as sheeple denying it. A lot of others
know it in their heart of heart and are quiet. The sharpest of them
knew it
immediately. That exactly was the coded message broadcast by Noam
Chomsky
that everyone will exploit 911 for their own reasons. He immediately
understood it was an inside job and its exact purpose.
But he is smart and drew further conclusions.
Remember, he was into Kennedy's investigation and said: those who can
do it and get away must be too powerful to confront [directly]. But
that
was a murder. This involves too much physics and chemistry.
All those who are quiet know it. The event was very accurately
exploited by the British, Italian, French, Dutch, intelligence agencies
or political establishments or administrations, where ever there was a
vulnerability towards fascism. But consider countries in europe
where fascism has not taken root. There was no response. Just look
at videos of reaction of people in the controlled demolition industry
in europe. The videos are available with translation. Their reaction
to the WTC7 fall is shocking. They know it is a professional inside
job. There are going to be many random events in the fall of a
big building so that there will be twists and turns and halts in the
fall and its never going to fall straight on its footprint into a neat
rubble filling the basement to the foundation like a pool with water.

> The reality is that it is possible. That's why the money changers do
> what they do, and do it without fear of reprisal.

Most dont care, and only scream when personally in pain as the
relatives
of 911 victims the first responders and Cindy Sheehan are doing.

> Perhaps it is the fate of those who's forefathers conquered a nation to
> one day wake up homeless in that nation - herded, branded, traded and
> sold for the slaughter by the Zionist as they did the Negro. Perhaps
> these Zionists, or whoever it is who is responsible for these acts, is
> ultimately destined to the same fate.

If they dont hang together, they will hang separately.

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


Re: A note on heapq module

2007-01-18 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> Steven Bethard:
>> Antoon Pardon:
>>> For me, your class has the same drawback as the heappush, heappop
>>> procedurers: no way to specify a comparision function.
>> Agreed.  I'd love to see something like ``Heap(key=my_key_func)``.
> 
> It can be done, but the code becomes more complex and hairy:
> http://rafb.net/p/iCCmDz16.html

Cool!

The current code fails when using unbound methods however::

 >>> heap = Heap()
 >>> Heap.push(heap, 1)
 Traceback (most recent call last):
   File "", line 1, in 
 AttributeError: type object 'Heap' has no attribute 'push'

I would have written the code like::

 def smallest(self):
 result = self._heap[0]
 if self._key is not None:
 result = result[2]
 return result

 def push(self, item):
 if self._key is not None:
 item = self._key(item), self._itemid, item
 self._itemid += 1
 heappush(self._heap, item)

 def pop(self):
 result = heappop(self._heap)
 if self._key is not None:
 result = result[2]
 return result

 def popn(self, n):
 result = [heappop(self._heap) for _ in xrange(n)]
 if self._key is not None:
 result = [item[2] for item in result]
 return result

 def replace(self, item):
 if self._key is not None:
 item = self._key(item), self._itemid, item
 self._itemid += 1
 result = heapreplace(self._heap, item)
 if self._key is not None:
 result = result[2]
 return result

This allows unbound methods to work, and substantially lowers the code 
duplication. It does add a few extra if statements, but since they're 
``is`` tests, they should be pretty fast.

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


Re: import vs. subdirectory search

2007-01-18 Thread gordyt
John try this:

from M2Crypto import SSL

That should put your SSL module in the namespace as you want.

--gordy

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


Re: Traversing the properties of a Class

2007-01-18 Thread EdG
That works perfectly thank you.

Bruno Desthuilliers wrote:
> EdG a écrit :
> (top-post corrected)
> >
> > Neil Cerutti wrote:
> >
> >>On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
> >>
> >>>For debugging purposes, I would like to traverse the class
> >>>listing out all the properties.
> >>
> >>This is the first thing that came to mind.
> >>
> >>def show_properties(cls):
> >>  for attr in dir(cls):
> >>if isinstance(getattr(cls, attr), property):
> >>  print attr
> >>
>
>  > This works great.  I have one more question.  Now that I have the name
>  > of the property, how do I get it's value?
>  >
>  > I want to print  '%s = %s' % (attr,theattributesvalue)
>
>
> Then you need to have the instance...
>
> def list_properties(cls):
>return [
>  name for name in dir(cls)
>  if isinstance(getattr(cls, name), property)
>]
>
> def print_properties(obj):
>for name in list_properties(obj.__class__):
>  print "%s : %s" % (name, str(getattr(obj, name)))

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


Tiling and Spacefilling

2007-01-18 Thread [EMAIL PROTECTED]
[ slightly improved over Math Forum draft ]

Probably a fault line or cultural divide between acutely
differing schools of thought, is in this area of tiling
or mosaic making. Some schools consider this a stupid
waste of time, others a core topic, whereas a 3rd group
stays more neutral on the issue, and a tiny 4th group has
no idea what I'm talking about.

I'm in the second group (core topic) as tiling is to
spacefilling as figurate are to polyhedral numbers.
We may start in a plane, in deference to some millenia
of pre-NASA reflex conditioning, but we're still on a
runway, accelerating, and before long (way sooner than
in traditional curricula), we'll be airborne, moving
up into higher D. Tetrahedra are most definitely a
feature of K-5. If NCTM doesn't grasp that, it's
missing the boat.

Back to tiling: we have the classifications, the Escher
lithographs (which follow into Part Two), and the tie ins
to Mesopotamian religions, the three biggies especially,
and their respective sacred geometries. I know "sacred
geometry" is taboo in traditional mathematics, but this
is ~M!, Katrina Network type stuff, closer to George Bush
Sr.'s "voodoo economics" (except managed more by geeks
(Bush was more of a jock, not that we can't share power)).

Rolling forward, we get to the Kepler-Penrose aperiodic
tiling studies, various heuristics, again finding echoes
in Part Two (in what some Russians call stereometry),
where we likely look at Hargittai & Hargittai (Hungarian),
plus Chakovian coordinates (quadrays, simplicials,
whatever nomenclature).

I've already made the case for Polyhedra numerous times.
Thanks to breakthroughs in architecture in the 20th
century, we're obligated to teach about the hexapent in
some way shape or form. Katrina Network is strong on
this, but you'll find other sources. Top of my list
would be J. Baldwin's 'Bucky Works' (packed with ~M!).

For a more prefrequency approach, I recommend Cromwell's
'Polyhedra', and its cartoon proof of Euler's V + F =
E + 2 based on the interdigitating trees of Von Staudt's.

And of course we're not about to bleep over Fuller's
volumes tables, nor MITEs, nor the Jitterbug Trans-
formation -- all pure gold as far as we're concerned.

So to recap... Given I'm of a school which regards
tiling as core, I'm putting my shoulder behind two big
initiatives in computer science these days: CP4E and
HP4E.

CP4E was hatched by Guido, BDFL of Python Nation, and
DARPA, and carried forward billiantly (at least one
doctoral dissertation already on file, about our early
beginnings as a think tank slash on-line community [1]).

HP4E was hatched by yours trully, though mostly as a
marketing gimmick in homage to CP4E and Wanderer Glenn
Stockton's global matrix campaign. I certainly take
advantage of Python a lot, using its generators (a recent
feature) to spit out successive terms in figurate and
polyhedral number sequences, e.g. 1, 3, 6, 10... and
1, 12, 42, 92... (see my Focal Points for more details,
plus my CP4E website, one of many curriculum "hot springs"
in our cyberspace-based Python Nation [2][3]).

Kirby

[1] John Miller's PhD dissertation, Promoting Computer
Literacy Through Programming Python (1.37 MB), looks at
the issues around teaching with Python, and explores some
of the threads taken up on edu-sig.
http://www.python.org/community/sigs/current/edu-sig/

[2] Focal Points:
http://mybizmo.blogspot.com/2006/09/focal-points.html

[3] CP4E website: http://www.4dsolutions.net/ocn/cp4e.html

===

For more on ~M!:
http://worldgame.blogspot.com/2007/01/m.html

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


Re: Traversing the properties of a Class

2007-01-18 Thread Bruno Desthuilliers
EdG a écrit :
(top-post corrected)
> 
> Neil Cerutti wrote:
> 
>>On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
>>
>>>For debugging purposes, I would like to traverse the class
>>>listing out all the properties.
>>
>>This is the first thing that came to mind.
>>
>>def show_properties(cls):
>>  for attr in dir(cls):
>>if isinstance(getattr(cls, attr), property):
>>  print attr
>>

 > This works great.  I have one more question.  Now that I have the name
 > of the property, how do I get it's value?
 >
 > I want to print  '%s = %s' % (attr,theattributesvalue)


Then you need to have the instance...

def list_properties(cls):
   return [
 name for name in dir(cls)
 if isinstance(getattr(cls, name), property)
   ]

def print_properties(obj):
   for name in list_properties(obj.__class__):
 print "%s : %s" % (name, str(getattr(obj, name)))

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


distutils data file difficulties

2007-01-18 Thread Brian L. Troutwine
I am new to the use of distutils and am having difficulty getting
distutils recognize and install data files. Here are the relevant parts
of my source directory:

ExampleTree/
|-- __init__.py
|-- data
|   |-- Example1.txt
|   |-- Example2.txt
|   `-- __init__.py
|-- subPackage1
|   |-- (...)
`-- subPackage2
|-- (...)

I would like to install Example1.txt and Example2.txt under data/ upon
installation. I cannot seem to write a proper setup.py to accomplish
this. Here are the relevant bits of my setup.py:

#!/usr/bin/env python

from distutils.core import setup

setup(name="ExampleTree",
(...),
packages=['ExampleTree', ExampleTree/data',
'ExampleTree/subPackage1',
''ExampleTree/subPackage2'],
package_dir={'data' : 'ExampleTree/data'},
package_data={'data': ['Example1.txt', 'Example2.txt']},
)

What am I doing incorrectly?

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


Re: More M2Crypto issues

2007-01-18 Thread John Nagle
Upgraded to Python 2.5 on the Linux system, rebuild M2Crypto,
and it stil fails, but the last line of the error message changed to:

ValueError: invalid literal for long() with base 10: '_40f91a08_p_SSL_CTX'

Others have encountered this problem, from a Google search.

Is "long" supposed to operate on C objects?

John Nagle

John Nagle wrote:
>   I've been running M2Crypto successfully using Python 2.4 on Windows 2000,
> and now I'm trying to get it to work on Python 2.3.4 on Linux.
> 
>   Attempting to initialize a context results in
> 
> Traceback (most recent call last):
>   File "/www/htdocs/sitetruth.com/cgi/ratingdetails.cgi", line 46, in ?
> DetailsPageBuilder.detailspage(kdbfile,ktemplatefile,url)# check 
> and display domain or URL as web page
>   File "./sitetruth/DetailsPageBuilder.py", line 70, in detailspage
> sitecert = InfoSSL2.Certificate(siteinfo, kverifylocations, verbose)
>   File "./sitetruth/InfoSSL2.py", line 147, in __init__
> self.ctx = createsslcontext(trustedcafile, verbose)# Generate 
> general SSL context
>   File "./sitetruth/InfoSSL2.py", line 40, in createsslcontext
> ctx = SSL.Context('sslv3')# Create 
> context with SSL params
>   File "/home/sitetruth/lib/python/M2Crypto/SSL/Context.py", line 43, in 
> __init__
> map()[long(self.ctx)] = self
> ValueError: invalid literal for long(): _480e1008_p_SSL_CTX
> 
>which, when I look at the code and try some test cases, seems
> legitimate.  The cacheing code is trying to convert a reference to an
> object (a C object, in fact) into a "long".  Python 2.4 on Windows
> will do that.  Python 2.3.4 on Linux converts it to a string first,
> gets "_480e1008_p_SSL_CTX", and then tries to convert that to an
> integer, which fails.
> 
>M2Crypto is supposed to work with Python 2.3, so this should work.
> 
> John Nagle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] Deletion order when leaving a scope?

2007-01-18 Thread Terry Reedy

"Paul McGuire" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| "Calvin Spealman" <[EMAIL PROTECTED]> wrote in message
| news:[EMAIL PROTECTED]
| > Absolutely an irrelevent side effect, especially when you take into
| > consideration the 4 and counting alternative implementations of the
| > language.
| >
| > None the less, I can explain why it is as it is, keeping in mind its
| > not like that on purpose, its just how it is. Locals are optimized
| > into an array for fast lookup. Every name assigned to in a function is
| > known as a local in that function and this internal array holds its
| > reference. It is simply a product of the array indexes and deletion
| > order being the same, 0 to N.
| >
|
| Oh good!  Now I can write code that relies on this behavior!

According to a followup on python-dev, you can't.  The above is the normal 
behavior (for CPython) but it can be modified by imports and 
cross-references.

Or did you forget a smiley?

tjr



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


Re: Traversing the properties of a Class

2007-01-18 Thread EdG
This works great.  I have one more question.  Now that I have the name
of the property, how do I get it's value?

I want to print  '%s = %s' % (attr,theattributesvalue)

Thanks.

Neil Cerutti wrote:
> On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
> > For debugging purposes, I would like to traverse the class
> > listing out all the properties.
>
> This is the first thing that came to mind.
>
> def show_properties(cls):
>   for attr in dir(cls):
> if isinstance(getattr(cls, attr), property):
>   print attr
>
> --
> Neil Cerutti
> 
> -- 
> Posted via a free Usenet account from http://www.teranews.com

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


Re: How can I create a linked list in Python?

2007-01-18 Thread Neil Cerutti
On 2007-01-18, sturlamolden <[EMAIL PROTECTED]> wrote:
>
> Paul Rubin wrote:
>
>> But that's what Lisp does too.
>
> Ok, I may have to reread Paul Graham's book on ANSI Common Lisp
> then.

Here's something silly I whipped up to play with.

r""" Lisp style singly-linked lists called llist. 

"""

def consp(o):
return isinstance(o, Cons)

def car(c):
""" Return the car of a lisp-list. Undefined for nil. """
if null(c):
raise AttributeError("nil has no cdr")
return c.car

def cdr(c):
""" Return the cdr of a lisp=list. """
if null(c):
return nil
return c.cdr

def cons(o, c):
""" Build a new cons cell from an object and a Cons. """
return Cons(o, c)

def null(c):
return c is nil

def rplaca(c, o):
c.car = o
return c

def rplacd(c, o):
c.cdr = o
return c

def llist(li):
""" Build a llist from a list. """
c = nil
for a in reversed(li):
if isinstance(a, list):
c = cons(llist(a), c)
else:
c = cons(a, c)
return c

class Cons(object):
def __init__(self, car, cdr):
self.car = car
self.cdr = cdr
def __repr__(self):
def helper(li, s):
if null(li):
return s + ")"
else:
return helper(cdr(li), s + " %s" % repr(car(li)))
return helper(self.cdr, "(" + repr(self.car))

class Nil(Cons):
def __init__(self):
Cons.__init__(self, None, None)
def __repr__(self):
return '()'

nil = Nil()

print cons(5, nil)
print cons(5, cons(3, nil))
print cons(cons(5, (cons(7, nil))), cons(cons(5, cons(3, nil)), nil))
print nil
print llist([1, ['a', 'b', 'c'], 2, 3])

There's lots more more stuff to add, but the fun wore out. I'd
like if it the cdr of nil could actually be nil, instead of None
with a special case in cdr, but I couldn't figure out a neat way
to do it.

-- 
Neil Cerutti
I've had a wonderful evening, but this wasn't it. --Groucho Marx

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

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


Zope 3 Boot Camp and Sprint registration open

2007-01-18 Thread Chris Calloway
The Triangle (NC) Zope and Python Users Group invites you to register 
for Camp 5 and the BBQ Sprint:

http://trizpug.org/boot-camp/camp5/

This is a Zope 3 boot camp followed by a Plone 3 sprint. The boot camp 
is taught by Philipp von Weitershausen, author of Web Component 
Development with Zope 3. The training has previously only been offered 
in Europe and is now available in North America for the first time. The 
sprint includes several sponsored and invited sprinters.

TriZPUG hopes you will participate in Camp 5 in Chapel Hill, NC.

Camp 5: Saturday March 10 - Tuesday March 13, 2007
BBQ Sprint: Wednesday March 14 - Saturday March 17, 2007

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find out if another process is using a file

2007-01-18 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Donn Cave <[EMAIL PROTECTED]> writes:
|> In article <[EMAIL PROTECTED]>,
|>  "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
|> > "Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje 
|> > news:[EMAIL PROTECTED]
|> > 
|> > > I'm writing a program which reads a series of data files as they are 
|> > > dumped
|> > > into a directory by another process.  At the moment, it gets sporadic 
bugs
|> > > when it tries to read files which are only partially written.
|> > >
|> > > I'm looking for a function which will tell me if a file is opened in
|> > > write-mode by another process - if it is, my program will ignore it for 
|> > > now
|> > > and come back to it later.  This needs to work on linux and windows.  Mac
|> > > OS would be a bonus too.  An os-independent solution would be good, but I
|> > > could write os-specific options and have it pick the appropriate one.
|> > 
|> > Use os.open with the O_EXCL flag; will fail if the other process has the 
|> > file still open (and will fail if another process is reading the file, 
too, 
|> > not just if someone is writing).
|> 
|> O_EXCL fails if the file exists at all - whether closed or open.

Yes.  In theory.  In practice, it usually works on normal files, provided
that all opens are local.  Under some circumstances, it will even work
for NFS mounted files, as far as I recall.

MVS (now zOS) and other mainframe systems had what the poster wants, but
modern systems don't.  I shall not recommend that the poster asks IBM
for a copy of zOS, for reasons that will be well-known to anyone who used
MVS (which are NOT the ones claimed by the Unix brigade, which are mostly
bogus) :-)

Under Linux, you can do something with fuser, and I am pretty certain that
modern Macintoshes (i.e. BSD) will have an equivalent.  It can't be made
reliable (unlike under MVS), but might reduce the number of problems.


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

Re: PyMeld for html templates?

2007-01-18 Thread Bruno Desthuilliers
Sean Schertell a écrit :
> I'm trying to decide which template system to get married to. I think  
> I've narrowed it down to PyMeld, Cheetah, or Jinja  but leaning  heavily 
> toward PyMeld because I love the idea that your templates are  *totally* 
> clean and that get manipulated from behind the scenes. This  seems to be 
> elegantly inline with the Sacred Creed of separation of  logic from 
> presentation.

"separating logic from presentation" is often misunderstood. It should 
really read "separating application logic from presentation logic", not 
"separating presentation logic from html code".

> Of course I'm going to try them all

The don't forget to have a look at Genshi and Mako too.

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Traversing the properties of a Class

2007-01-18 Thread Bruno Desthuilliers
EdG a écrit :
> I'm using Python version 2.4 and I created a class with some properties
> like:
> 
> def GetCallAmount(self):
> return somedata


The recommended naming convention is all_lower,ie:
def get_call_amount(self):


And FWIW, there are idioms to avoid polluting the class namespace, like:

class Account(object):
 @apply
 def amount():
def fget(self):
return something
def fset(self, value):
do_something_with(value)
return property(**locals())

> For debugging purposes, I would like to traverse the class listing out
> all the properties.

cf Neil's answer.

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


Re: How to find out if another process is using a file

2007-01-18 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

> "Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje 
> news:[EMAIL PROTECTED]
> 
> > I'm writing a program which reads a series of data files as they are 
> > dumped
> > into a directory by another process.  At the moment, it gets sporadic bugs
> > when it tries to read files which are only partially written.
> >
> > I'm looking for a function which will tell me if a file is opened in
> > write-mode by another process - if it is, my program will ignore it for 
> > now
> > and come back to it later.  This needs to work on linux and windows.  Mac
> > OS would be a bonus too.  An os-independent solution would be good, but I
> > could write os-specific options and have it pick the appropriate one.
> 
> Use os.open with the O_EXCL flag; will fail if the other process has the 
> file still open (and will fail if another process is reading the file, too, 
> not just if someone is writing).

O_EXCL fails if the file exists at all - whether closed or open.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Web Frameworks

2007-01-18 Thread Ximo Nadal
Shortash wrote:
> Hi Gurus,
> 
> I want to build a Python web app but im not sure which one to go for. I
> prefer something like asp.Net , which would allow me to fully seperate
> the presentation layer from the logic. Please advise?
> 
> thanks,
> 
> "Shortash'
> 
Hi,

Look at  there are same of them.

Now I'm studing karrigell, it's very interesting.

bye,

-- 
Ximo Nadal <[EMAIL PROTECTED]>
Powered by Debian GNU/Linux 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spidering script

2007-01-18 Thread dubs
Check out the quick start section in the documentation at Beautiful
Soup http://www.crummy.com/software/BeautifulSoup/


Wes


Jonathan Curran wrote:
> On Thursday 18 January 2007 11:57, David Waizer wrote:
> > Hello..
> >
> > I'm  looking for a script (perl, python, sh...)or program (such as wget)
> > that will help me get a list of ALL the links on a website.
> >
> > For example ./magicscript.pl www.yahoo.com and outputs it to a file, it
> > would be kind of like a spidering software..
> >
> > Any suggestions would be appreciated.
> >
> > David
>
> David, this is a touchy topic but whatever :P Look into sgmllib, and you can
> filter on the "A" tag. The book 'Dive Into Python' covers it quite nicely:
> http://www.diveintopython.org/html_processing/index.html
> 
> Jonathan

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


Re: How can I create a linked list in Python?

2007-01-18 Thread sturlamolden

Paul Rubin wrote:

> But that's what Lisp does too.

Ok, I may have to reread Paul Graham's book on ANSI Common Lisp then.

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


Re: Traversing the properties of a Class

2007-01-18 Thread EdG
Thanks.

Daniel Nogradi wrote:
> > I'm using Python version 2.4 and I created a class with some properties
> > like:
> >
> > def GetCallAmount(self):
> > return somedata
> >
> > def GetCallCurrency(self):
> > return  somemoredata
> >
> > moredefs..etc.
> >
> > CallAmount   = property(GetCallAmount,None,None,None)
> > CallCurrency = property(GetCallCurrency, None, None, None)
> >
> > moreproperies..etc.
> >
> > For debugging purposes, I would like to traverse the class listing out
> > all the properties.
>
>
> for attr in dir( yourclass ):
> if repr( yourclass.__dict__[ attr ] ).startswith( ' print 'This looks like a property although can be something
> else too: ' + attr
> 
> :)

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


Re: Traversing the properties of a Class

2007-01-18 Thread EdG
Thanks.

Neil Cerutti wrote:
> On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
> > For debugging purposes, I would like to traverse the class
> > listing out all the properties.
>
> This is the first thing that came to mind.
>
> def show_properties(cls):
>   for attr in dir(cls):
> if isinstance(getattr(cls, attr), property):
>   print attr
>
> --
> Neil Cerutti
> 
> -- 
> Posted via a free Usenet account from http://www.teranews.com

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


Re: Traversing the properties of a Class

2007-01-18 Thread Neil Cerutti
On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
> For debugging purposes, I would like to traverse the class
> listing out all the properties.

This is the first thing that came to mind.

def show_properties(cls):
  for attr in dir(cls):
if isinstance(getattr(cls, attr), property):
  print attr

-- 
Neil Cerutti

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

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


Re: spidering script

2007-01-18 Thread Jonathan Curran
On Thursday 18 January 2007 11:57, David Waizer wrote:
> Hello..
>
> I'm  looking for a script (perl, python, sh...)or program (such as wget)
> that will help me get a list of ALL the links on a website.
>
> For example ./magicscript.pl www.yahoo.com and outputs it to a file, it
> would be kind of like a spidering software..
>
> Any suggestions would be appreciated.
>
> David

David, this is a touchy topic but whatever :P Look into sgmllib, and you can 
filter on the "A" tag. The book 'Dive Into Python' covers it quite nicely: 
http://www.diveintopython.org/html_processing/index.html

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


Re: Traversing the properties of a Class

2007-01-18 Thread Daniel Nogradi
> I'm using Python version 2.4 and I created a class with some properties
> like:
>
> def GetCallAmount(self):
> return somedata
>
> def GetCallCurrency(self):
> return  somemoredata
>
> moredefs..etc.
>
> CallAmount   = property(GetCallAmount,None,None,None)
> CallCurrency = property(GetCallCurrency, None, None, None)
>
> moreproperies..etc.
>
> For debugging purposes, I would like to traverse the class listing out
> all the properties.


for attr in dir( yourclass ):
if repr( yourclass.__dict__[ attr ] ).startswith( 'http://mail.python.org/mailman/listinfo/python-list


Re: Memory Management in Embedded Python

2007-01-18 Thread Martin v. Löwis
Huayang Xia schrieb:
> I have a piece of code like this:
> 
>   void funct(PyObject* pyobj)
>   {
>  char   str[128];
>  strncpy(str, "just a test string", sizeof(str));
>  PyObject* pydata = PyObject_CallMethod(pyobj, "method_x",
> "s", str);
>  Py_DECREF(pydata);
>   }
> 
> After the function is exited, the str is not there anymore. Will this
> affect python operation. How does python use the str? It's copied or it
> just uses the pointer?

The interpreter creates a string object, and passes that to method_x.
Creating a string object does indeed create a copy. The string object
will be refcounted, so it exists as long as there is a reference to it.
Likely (unless the method_x implementation somehow stores the string),
it gets deallocated before PyObject_Call returns.

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


Memory Management in Embedded Python

2007-01-18 Thread Huayang Xia
Hi there,

I have a piece of code like this:

  void funct(PyObject* pyobj)
  {
 char   str[128];
 strncpy(str, "just a test string", sizeof(str));
 PyObject* pydata = PyObject_CallMethod(pyobj, "method_x",
"s", str);
 Py_DECREF(pydata);
  }

After the function is exited, the str is not there anymore. Will this
affect python operation. How does python use the str? It's copied or it
just uses the pointer?

Thanks in advance.

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


Re: closing a "forever" Server Socket

2007-01-18 Thread Matimus
> I want to ask if someone knows a better way for closing a "forever
> server" or if there is a lack in my design.

Generally you don't create a 'forever server'. You create an 'until I
say stop' server. I would do this by looking at the 'serve_forever'
method, and implementing my own 'serve_until_?' method that is similar,
but will stop if a flag is set. Then you have to create a method for
setting that flag. It could be as simple as a keypress, or you could
add a quit method to your dispatcher that sets the flag when a certain
address is visited. That second method probably needs some added
security, otherwise anybody can just visit 'your.server.com/quit' and
shut it down.

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


spidering script

2007-01-18 Thread David Waizer
Hello..

I'm  looking for a script (perl, python, sh...)or program (such as wget) 
that will help me get a list of ALL the links on a website.

For example ./magicscript.pl www.yahoo.com and outputs it to a file, it 
would be kind of like a spidering software..

Any suggestions would be appreciated.

David 


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


Re: How to find out if another process is using a file

2007-01-18 Thread Jean-Paul Calderone
On Thu, 18 Jan 2007 14:34:52 -0300, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>"Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje
>news:[EMAIL PROTECTED]
>
>> I'm writing a program which reads a series of data files as they are
>> dumped
>> into a directory by another process.  At the moment, it gets sporadic bugs
>> when it tries to read files which are only partially written.
>>
>> I'm looking for a function which will tell me if a file is opened in
>> write-mode by another process - if it is, my program will ignore it for
>> now
>> and come back to it later.  This needs to work on linux and windows.  Mac
>> OS would be a bonus too.  An os-independent solution would be good, but I
>> could write os-specific options and have it pick the appropriate one.
>
>Use os.open with the O_EXCL flag; will fail if the other process has the
>file still open (and will fail if another process is reading the file, too,
>not just if someone is writing).

On what platform is this true?

A better solution is to name or place files which are begin written in a which 
is recognizable and only rename or move them to their final location when they 
have been completely written.

For example, name files ".new" as they are being written.  When they are fully 
written, drop the ".new" suffix.  On the reader side, ignore any file with a 
name ending in ".new".

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

Re: How to find out if another process is using a file

2007-01-18 Thread Gabriel Genellina
"Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> I'm writing a program which reads a series of data files as they are 
> dumped
> into a directory by another process.  At the moment, it gets sporadic bugs
> when it tries to read files which are only partially written.
>
> I'm looking for a function which will tell me if a file is opened in
> write-mode by another process - if it is, my program will ignore it for 
> now
> and come back to it later.  This needs to work on linux and windows.  Mac
> OS would be a bonus too.  An os-independent solution would be good, but I
> could write os-specific options and have it pick the appropriate one.

Use os.open with the O_EXCL flag; will fail if the other process has the 
file still open (and will fail if another process is reading the file, too, 
not just if someone is writing).

-- 
Gabriel Genellina 


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


Traversing the properties of a Class

2007-01-18 Thread EdG
I'm using Python version 2.4 and I created a class with some properties
like:

def GetCallAmount(self):
return somedata

def GetCallCurrency(self):
return  somemoredata

moredefs..etc.

CallAmount   = property(GetCallAmount,None,None,None)
CallCurrency = property(GetCallCurrency, None, None, None)

moreproperies..etc.

For debugging purposes, I would like to traverse the class listing out
all the properties.

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


Re: How to read and write huge binary files

2007-01-18 Thread Gabriel Genellina
"Lad" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> What is a good  way to read binary data from HUGE  file and write  it
> to another file?
Without processing the data read? shutil.copy2 or similar
Else, a lot of applications can follow the pattern read-process-write: read 
a logical block, process, write the output; where "logical block" depends on 
the application: a record, a frame, a chunk...

-- 
Gabriel Genellina 


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


Re: Is it possible to fasten the import of cgi?

2007-01-18 Thread Gabriel Genellina
"Cecil Westerhof" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]
> Gabriel Genellina wrote:
>
>> "Cecil Westerhof" <[EMAIL PROTECTED]> escribió en el mensaje
>> news:[EMAIL PROTECTED]
>>
>>>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse
>>>I
>>> can not time the time used to import time, but os and sys do not take
>>> more as a millisecond. My script itself takes 3 or 4 milliseconds. But
>>> importing
>>> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
>>> there a way to make this more fast? The import off cgi makes the script
>>> at least 20 times as slow. Something like mod-python is not a
>>> possibility. I could use it on my test machine, but not at the osting
>>> provider.
>> Surely os was imported earlier, and was already loaded. sys is a builtin
>> module. But I think your problem is not how much time takes importing 
>> cgi,
>> but how much time takes launching a new python process on each request.
>
> Nope, it was certainly cgi. When I fetch time after importing and after 
> the
> script finishes, the difference is 4 milliseconds. If I import the modules
> apart from cgi after I fetch the first time, there is added about 1
> millisecond to the difference. When I also import cgi after taking the
> time, the difference grows with 95 milliseconds. So for one reason ore
> another, cgi is very expensive.

I'll try to explain better: the cgi *protocol* (I'm not talking about the 
cgi *module*) requires a *new* python process to be created on *each* 
request. Try to measure the time it takes to launch Python, that is, the 
time from when you type `python ENTER` on your shell and the interpreter 
prompt appears. That time is wasted for *every* cgi request, and I bet it is 
much greater than the 95 ms you measure importing a module (be it cgi or 
whatever). You'll gain much more responsiveness if you can switch to another 
protocol, be it FastCGI, WSGI, mod_python or another.

Anyway, comparing the import time between os, sys, and cgi is not very 
meaningful. sys is a builtin module, so "import sys" does very little. os is 
likely to be already imported by the time your script begins, so "import os" 
just verifies that os is already in sys.modules. "import cgi" is the only 
example when Python actually has to load something, so it's not a surprise 
if it takes longer.

-- 
Gabriel Genellina 


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

Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread Roel Schroeven
Paul Rubin schreef:
> "Martin P. Hellwig" <[EMAIL PROTECTED]> writes:
>> Indeed it's not Afrikaans but just incorrect use of Dutch and not
>> related to python.
> 
> It was apparently posted by someone with a .be address, so I'll guess
> it was written a Belgian French speaker who knows some Dutch.  The
> "me" vs "mijn" error sounds like something a French speaker might have
> done.

To me (as a Belgian Dutch speaker) it sounds more like someone writing 
phonetically (probably because of a low education or low interest in 
writing correctly) and being from the Netherlands (since the 
pronunciation of 'mijn' sounds more like 'me' there then in Flanders).

It's not unlike the use of "I should of" instead of "I should've" or "I 
should have" in English, though much less common. At least I think and 
hope it's much less common, but actually I don't read all that much 
forums, newsgroups etc. in Dutch.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Catching wx events

2007-01-18 Thread Cruelemort

Chris Mellon wrote:

> On 18 Jan 2007 06:12:17 -0800, Cruelemort <[EMAIL PROTECTED]> wrote:
> > Hello all,
> >
> > I am new to this group (and new to Python) and was hoping someone would
> > be able to help me with something, it is not so much a problem it is
> > more of a general interest query about something i have a solution too
> > but am not sure it is the correct one.
> >
> > I have a class that contains a string ID and a name, and a list
> > containing a few objects of this type, i need to loop through this list
> > and create a button for each object (with the name as the label) i have
> > done this with the following code -
> >
> > for chan in self._channellist:
> > channelbutton = wx.Button(self, id=-1,
> > label=chan.getName())
> >
> > channelbutton.Bind(wx.EVT_BUTTON,self._channelChanged)
> >
> > My question is this - in the _channelChanged method, how do i know
> > which button has been pressed when i enter the channel changed method,
> > and so how do i retrieve the appropriate object depending on which
> > button has been pressed?
> >
> > I have potentially solved this problem using the UserData property in a
> > sizer, i have added all the buttons to a sizer for display purposes and
> > so SizerItem objects have been created, i can then set the original
> > object to the UserData object by putting the following line of code in
> > the loop
> >
> > sizeritem =
> > self.topsizer.Add(channelbutton,0,wx.ALIGN_RIGHT, userData=chan)
> >
> > This way i can retrieve the item in the _channelChanged method with the
> > following -
> >
> > def _channelChanged(self, event):
> > eventobj = event.GetEventObject()
> > chan = self.topsizer.GetItem(eventobj).GetUserData()
> >
> >
> > This works fine but by looking at the API it would appear the UserData
> > property is not really designed for this use ("userData - Allows an
> > extra object to be attached to the sizer item, for use in derived
> > classes when sizing information is more complex than the proportion and
> > flag will allow for").
> >
> > Another option would be to derive my own Button class and include the
> > object in there.
> >
> > Any advice on the best way to solve this problem would be appreciated.
> >
>
> Exactly how I would do it depends on the rest of the application. I
> would probably derive my own button - never be afraid to subclass.
>
> You could also generate the buttons IDs up front, and maintain a
> mapping between the IDs and the channels, like so:
>
> self.mapper = {}
> for channel in self.channels:
> id = wx.NewId()
> self.mapper[id] = channel
> channelbutton = wx.Button(self, id=id, label=channel.getName())
>
>
> def channelChanged(self, event):
> channel = self.mapper[event.Id]
>
>
> You could also use closures (lambdas or via a factory function) to
> bind the channel at the time you create the button:
>
> for channel in self.channels:
> channelbutton = wx.Button(self, label=channel.getName())
> self.Bind(wx.EVT_BUTTON, lambda event:
> self.channelChanged(channel), source=channelbutton)
>
> def channelChanged(self, channel):
> print "Channel changed to ", channel.getName()

Two good ideas, i used the mapping system, works and seems like a
slightly more elegant way of doing things.

Many thanks!

Ian

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


Re: A note on heapq module

2007-01-18 Thread Neil Cerutti
On 2007-01-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Neil Cerutti:
>> One more idea, cribbed from the linked list thread elsewhere:
>> it might be nice if your Heap could optionally use an
>> underlying collections.deque instead of a list. I don't know
>> how excellent Python's deque is, but it's possible a deque
>> would provide a faster heap than a contiguous array. C++'s
>> std::deque is the default implementation of C++'s
>> std::priority_queue for that reason (unless I'm confused
>> again).
>
> If you have some minutes you can do few speed tests and show us
> the code and the timing results...

collections.deque is the loser.

Here's the output of the program from my last run:

list: 5.81679827554
deque: 6.40347742423
C heapq: 2.24028186815

Here's the program. You can customize it somewhat to attempt to
model a real program. It builds up a heap of random integers to
some size, performs random pushes and pops for a while, and then
pops the heap down until it's empty.

import random
import timeit

OPCOUNT = 5000
HEAP_SIZE = 100

# Create a random sequence of pushes and pops.
pushes = 0
ops = []
for i in xrange(OPCOUNT):
x = random.randint(0, 1)
if x == 0 or pushes < HEAP_SIZE:
pushes += 1
ops.append(0)
else: 
pushes -= 1
ops.append(1)
# Pop off the rest
for i in xrange(pushes):
ops.append(1)

def test(mod, cont):
for op in ops:
if op:
mod.heappop(cont)
else:
mod.heappush(cont, random.randint(0, 150))

# heapqd is the pure Python heapq module without the C implementation.
t1 = timeit.Timer("test(heapqd, list())",
"from __main__ import test; import heapqd")
t2 = timeit.Timer("test(heapqd, deque())", 
"from __main__ import test; "\
"from collections import deque; "\
"import heapqd")
t3 = timeit.Timer("test(heapq, list())",
"from __main__ import test; import heapq")
print "list:", t1.timeit(100)
print "deque:", t2.timeit(100)
print "C heapq:", t3.timeit(100)

-- 
Neil Cerutti
The Pastor would appreciate it if the ladies of the congregation would lend
him their electric girdles for the pancake breakfast next Sunday morning.
--Church Bulletin Blooper

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

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


Re: How to read and write huge binary files

2007-01-18 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Lad wrote:

> What is a good  way to read binary data from HUGE  file and write  it
> to another file?

What about `shutil.copy()`?

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


Re: connection to server not accepted (but no error) only after several hours

2007-01-18 Thread seb
Hi Dennis,

I think I have some new informations.
My system is "blocked" now but the following change make it work again
!!!
I will test it for tonight to be sure of the improvements.

I changed :
   service.bind(("", self.PORT))
to
service.bind((socket.gethostname(), self.PORT))

The strange thing is that using the "" it works for a few hours.

Regards.
Sebastien.


Dennis Lee Bieber a écrit :
> On 17 Jan 2007 00:08:52 -0800, "seb" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
> >
> > 1) I have enabled one time server that can be run as a service (R C C
> > time server) and this service is responding correctly, when at the same
> > time (before I kill it ) the python time server is not responding.
> >
>
>   What behavior do you see if you don't run them as background
> services, but rather from a regular console login?
>
> > 2) I have also tried two python time server downloaded from effbot
> > site. Both are not responding after the "non response from the time
> > server I rn" even for the first interrogation once they are started.
> > (Of course I have killed my time server when I run a new one).
> > Same behaviour no response given but no error neither.
> >
>   If you've now got a total of three programs that are not reporting
> error conditions, I'd suspect there is something else wrong in the
> system...
>
> > It is only python programs that are listening from the port 37 that are
> > blocked at a certain time.
> > How is it possible (without firewall enabled) ?
> >
>   What response do you get from the clients attempting to connect to
> this server? (I'd expect a either a flat out "denied" or, for a
> stealthed firewall, a timeout with no response).
>
>
>   You also have a race condition in your log-file...
>
> > a.start()
> > a.set_log_file("log_nw.txt")
> > a.reset_log_file()
>
>   It is possible that the thread gets a few connections between the
> .start() and the .set_log_file() and logs them to the default file name.
> Also, it is possible for connections to be logged between the
> .set_log_file() and the .reset_log_file() (where you wipe out the
> contents of the log file).
>
>   I'd suggest putting the .start() call third in that list. That way
> you create the thread object, but it is not running. Change the log file
> name, wipe out any old contents, and THEN start the thread running.
>
>   My only other comment would be to add a few wolf-fences... Print
> statements (if running in a console), or more logging messages (you
> might want to make a method out of that internal logging so all you code
> is, say
>
>   self.slog("message")
>
> and "slog" does that time stamping, and file open/close...
>
>   By logging each main step (accept, send, close) you might find where
> it stops.
> --
>   WulfraedDennis Lee Bieber   KD6MOG
>   [EMAIL PROTECTED]   [EMAIL PROTECTED]
>   HTTP://wlfraed.home.netcom.com/
>   (Bestiaria Support Staff:   [EMAIL PROTECTED])
>   HTTP://www.bestiaria.com/

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

Re: How to find out if another process is using a file

2007-01-18 Thread js
How about using lock?
Let writing process locks the files before writing, and unlock after
the job's done.

I think it'd work  file in most environment.

On 1/19/07, Tom Wright <[EMAIL PROTECTED]> wrote:
> I'm writing a program which reads a series of data files as they are dumped
> into a directory by another process.  At the moment, it gets sporadic bugs
> when it tries to read files which are only partially written.
>
> I'm looking for a function which will tell me if a file is opened in
> write-mode by another process - if it is, my program will ignore it for now
> and come back to it later.  This needs to work on linux and windows.  Mac
> OS would be a bonus too.  An os-independent solution would be good, but I
> could write os-specific options and have it pick the appropriate one.
>
> Is there any way of doing this? I've drawn a blank with google so far.
>
> A nasty hack would be to use the file modification time, and wait until
> that's a few seconds in the past, but is there a nice solution?
>
>
> --
> I'm at CAMbridge, not SPAMbridge
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


nsis and command-line argument

2007-01-18 Thread manouchk
Hi,

is there a standart way to prepare a single exe with nsis that pass the
command line to an exe created by py2exe on windows?

py2exe allows to prepare an exe that get the command-line but needs
some lib file so that it is not so elegant to ditribute. I tried a
simple setup.nsis script to prepare a single file exe with works fine
except that it does get the command-line.

Is there a way do get the command line with the setup.nsis script?
or any other simple method ?

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


Re: urllib2 and transfer-encoding = chunked

2007-01-18 Thread jdvolz
Haha!  My mistake.

The error is that when a web server is chunking a web page only the
first chunk appears to be acquired by the urllib2.urlopen call.  If you
check the headers, there is no 'Content-length' (as expected) and
instead there is 'transfer-encoding' = 'chunked'.  I am getting about
the first 30Kb, and then nothing else.

I don't get a ValueError like described at the following post:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/e3f87a65c4c7e875/8a3ea9ca84b28669?lnk=gst&q=chunked&rnum=1#8a3ea9ca84b28669

Here's the code that I think is failing, it's basically textbook Python
for accessing a url:

file = urllib2.urlopen(url)
contenttype = file.info().type
if contenttype and contenttype.find('text') > -1:
return file.read()
#
# I am checking the content type because I don't want to download
.jpegs and the like
#

I have typed similar commands into the interpreter, which also produces
only about the first 30KB of the url.

Sorry for the confusion.

Gabriel Genellina wrote:
> <[EMAIL PROTECTED]> escribió en el mensaje
> news:[EMAIL PROTECTED]
> >I am having errors which appear to be linked to a previous bug in
> > urllib2 (and urllib) for v2.4 and v2.5 of Python.  Has this been fixed?
> > Has anyone established a standard workaround?  I keep finding old
> > posts about it, that basically give up and say "well it's a known bug."
> > Any help would be greatly appreciated.
>
> Perhaps if you said what the supposed error is...
> 
> -- 
> Gabriel Genellina

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


How to find out if another process is using a file

2007-01-18 Thread Tom Wright
I'm writing a program which reads a series of data files as they are dumped
into a directory by another process.  At the moment, it gets sporadic bugs
when it tries to read files which are only partially written.

I'm looking for a function which will tell me if a file is opened in
write-mode by another process - if it is, my program will ignore it for now
and come back to it later.  This needs to work on linux and windows.  Mac
OS would be a bonus too.  An os-independent solution would be good, but I
could write os-specific options and have it pick the appropriate one.

Is there any way of doing this? I've drawn a blank with google so far.

A nasty hack would be to use the file modification time, and wait until
that's a few seconds in the past, but is there a nice solution?


-- 
I'm at CAMbridge, not SPAMbridge
-- 
http://mail.python.org/mailman/listinfo/python-list


How to read and write huge binary files

2007-01-18 Thread Lad
What is a good  way to read binary data from HUGE  file and write  it
to another file?
Thanks for help
La.

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


Re: variable scope

2007-01-18 Thread Bruno Desthuilliers
gonzlobo a écrit :
> Greetings,
> I've been using Python to successfully parse files. When the entire
> program was smaller, the variable firstMsg worked fine, but now
> doesn't because it's used in function PID_MinMax. I know it's a result
> of variables and their scope.
> 
> I declare the variable 'firstMsg = 0' in the main loop, pass it to the
> function 'PID_MinMax(firstMsg, PID)'. When the function increments the
> variable, it doesn't pass it back to the main program. What am I doing
> wrong?
> 
> 
>  major snippage) ---
> firstMsg = 0
(snip)
> def PID_MinMax(firstMsg, PID):
(snip)
>if firstMsg != 0:
  if firstMsg:
>tDelta = tCurrent - pLast[idx]
>if tDelta > pMax[idx]:
>pMax[idx] = tDelta
>if tDelta < pMin[idx]:
>pMin[idx] = tDelta
>elif firstMsg == 0:
  else:
>firstMsg = 1
>pLast[idx] = tCurrent
>print pMin, pMax
>return firstMsg

> ## main ##
(snip)
> if PID in pPIDs:
> PID_MinMax(firstMsg, PID)
   firstMsg = PID_MinMax(firstMsg, PID)

You're returning firstMsg from PID_MinMax, but discarding the value...
-- 
http://mail.python.org/mailman/listinfo/python-list


Module name to filename and back?

2007-01-18 Thread Ron Adam

Is there a function to find a filename from a dotted module (or package) name 
without importing it?

The imp function find_module() doesn't work with dotted file names.  And it 
looks like it may import the file as it raises an ImportError error exception 
if 
  it can't find the module. (Shouldn't it raise an IOError instead?)

What I'm looking for is to be able to get the full module name when I have a 
filename.  And get the full filename when I have the module name.  And do both 
of these without importing the module.

modulename <==> filename
filename <==> modulename

Ron


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


Re: The proper use of QSignalMapper

2007-01-18 Thread David Boddie
borntonetwork wrote:
> Thanks, David, for you help.
>
> When I change the slot function to what you show in your second
> example, I get the same results: nothing.

This may be due to something I missed in your code. When you
connect the signal from the signal mapper to your class, you
need to specify the signal as a C++ signature as well:

self.connect(self.signalMapper, QtCore.SIGNAL(
 "mapped(int)"),
 self.deleteProductIngredient)

The second example should now work.

Looking at the first example, which uses SLOT() rather than specifying
a Python method, the following might be due to the way you call
connect, though it is surprising:

> When I change it to what you
> have in your first example, I get the following:
>
> Object::connect: No such slot QApplication::map()
> Object::connect:  (sender name:   'chkProductIngredientsDelete_1')
> Object::connect:  (receiver name: 'main.py')

[...]

It looks like you should try something like this:

 self.connect(w, QtCore.SIGNAL("stateChanged(int)"),
  self.signalMapper,
  QtCore.SLOT("map()"))

I can't understand why calling self.app.connect() would cause the
connection to be attempted between self.signalMapper and self.app.

Maybe someone on the PyQt/PyKDE mailing list would be able to
explain the behaviour you're seeing:

  http://mats.imk.fraunhofer.de/mailman/listinfo/pykde

David

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


Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread Paul Rubin
"Martin P. Hellwig" <[EMAIL PROTECTED]> writes:
> Indeed it's not Afrikaans but just incorrect use of Dutch and not
> related to python.

It was apparently posted by someone with a .be address, so I'll guess
it was written a Belgian French speaker who knows some Dutch.  The
"me" vs "mijn" error sounds like something a French speaker might have
done.
-- 
http://mail.python.org/mailman/listinfo/python-list


variable scope

2007-01-18 Thread gonzlobo
Greetings,
I've been using Python to successfully parse files. When the entire
program was smaller, the variable firstMsg worked fine, but now
doesn't because it's used in function PID_MinMax. I know it's a result
of variables and their scope.

I declare the variable 'firstMsg = 0' in the main loop, pass it to the
function 'PID_MinMax(firstMsg, PID)'. When the function increments the
variable, it doesn't pass it back to the main program. What am I doing
wrong?


 major snippage) ---
firstMsg = 0
skipHeader = 13

pPIDs = ['0321'] # hundreds more
pLen = len(pPIDs)
pMsgNum = pLen * [0]
pMax = pLen * [0]
pMin = pLen * [10]
pLast = pLen * [0]


def PID_MinMax(firstMsg, PID):
idx = pPIDs.index(PID)
pMsgNum[idx] += 1
# Need to have 2 samples to determine Delta
if firstMsg != 0:
tDelta = tCurrent - pLast[idx]
if tDelta > pMax[idx]:
pMax[idx] = tDelta
if tDelta < pMin[idx]:
pMin[idx] = tDelta
elif firstMsg == 0:
firstMsg = 1
pLast[idx] = tCurrent
print pMin, pMax
return firstMsg


## main ##
bf_file = file('bf_data/sByteflightLog_wISS.txt', 'r')
for line in bf_file:
# skip header
if skipHeader != 0:
skipHeader -= 1
# skip footer
elif line == '\n':
break
else:
 raw_msg = line.split()
 tCurrent = int(raw_msg[0], 16) * 0.0001
 PID = raw_msg[2]

 if PID in pPIDs:
 PID_MinMax(firstMsg, PID)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to fasten the import of cgi?

2007-01-18 Thread Cecil Westerhof
Gabriel Genellina wrote:

> "Cecil Westerhof" <[EMAIL PROTECTED]> escribió en el mensaje
> news:[EMAIL PROTECTED]
> 
>>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse
>>I
>> can not time the time used to import time, but os and sys do not take
>> more as a millisecond. My script itself takes 3 or 4 milliseconds. But
>> importing
>> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
>> there a way to make this more fast? The import off cgi makes the script
>> at least 20 times as slow. Something like mod-python is not a
>> possibility. I could use it on my test machine, but not at the osting
>> provider.
> Surely os was imported earlier, and was already loaded. sys is a builtin
> module. But I think your problem is not how much time takes importing cgi,
> but how much time takes launching a new python process on each request.

Nope, it was certainly cgi. When I fetch time after importing and after the
script finishes, the difference is 4 milliseconds. If I import the modules
apart from cgi after I fetch the first time, there is added about 1
millisecond to the difference. When I also import cgi after taking the
time, the difference grows with 95 milliseconds. So for one reason ore
another, cgi is very expensive.

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

Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread Martin P. Hellwig
Stef Mientki wrote:
> [EMAIL PROTECTED] wrote:
>> Got a note about a new page on the Python Wiki:
>>
>>> "Wade" == Wade McDaniel <[EMAIL PROTECTED]> writes:
>>
>> http://wiki.python.org/moin/Selcuk_Altun
>>
>> I suspect it's junk since it doesn't seem to mention Python and the 
>> website
>> it mentions doesn't seem to exist.  Still, just in case...
> The only (incorrect) Dutch sentence on the whole site is:
>   "Welkom op me site www.keriwar.nl",
> which should have been
>   "Welkom op mijn site www.keriwar.nl"
Well actually in the next sentence "De site is online als je vragen hebt 
lees eerst te F.A.Q." is incorrect too, "te F.A.Q." is grammatical and 
logical incorrect, should be "de F.A.Q.".
Indeed it's not Afrikaans but just incorrect use of Dutch and not 
related to python.

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


Re: Catching wx events

2007-01-18 Thread Chris Mellon
On 18 Jan 2007 06:12:17 -0800, Cruelemort <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> I am new to this group (and new to Python) and was hoping someone would
> be able to help me with something, it is not so much a problem it is
> more of a general interest query about something i have a solution too
> but am not sure it is the correct one.
>
> I have a class that contains a string ID and a name, and a list
> containing a few objects of this type, i need to loop through this list
> and create a button for each object (with the name as the label) i have
> done this with the following code -
>
> for chan in self._channellist:
> channelbutton = wx.Button(self, id=-1,
> label=chan.getName())
>
> channelbutton.Bind(wx.EVT_BUTTON,self._channelChanged)
>
> My question is this - in the _channelChanged method, how do i know
> which button has been pressed when i enter the channel changed method,
> and so how do i retrieve the appropriate object depending on which
> button has been pressed?
>
> I have potentially solved this problem using the UserData property in a
> sizer, i have added all the buttons to a sizer for display purposes and
> so SizerItem objects have been created, i can then set the original
> object to the UserData object by putting the following line of code in
> the loop
>
> sizeritem =
> self.topsizer.Add(channelbutton,0,wx.ALIGN_RIGHT, userData=chan)
>
> This way i can retrieve the item in the _channelChanged method with the
> following -
>
> def _channelChanged(self, event):
> eventobj = event.GetEventObject()
> chan = self.topsizer.GetItem(eventobj).GetUserData()
>
>
> This works fine but by looking at the API it would appear the UserData
> property is not really designed for this use ("userData - Allows an
> extra object to be attached to the sizer item, for use in derived
> classes when sizing information is more complex than the proportion and
> flag will allow for").
>
> Another option would be to derive my own Button class and include the
> object in there.
>
> Any advice on the best way to solve this problem would be appreciated.
>

Exactly how I would do it depends on the rest of the application. I
would probably derive my own button - never be afraid to subclass.

You could also generate the buttons IDs up front, and maintain a
mapping between the IDs and the channels, like so:

self.mapper = {}
for channel in self.channels:
id = wx.NewId()
self.mapper[id] = channel
channelbutton = wx.Button(self, id=id, label=channel.getName())


def channelChanged(self, event):
channel = self.mapper[event.Id]


You could also use closures (lambdas or via a factory function) to
bind the channel at the time you create the button:

for channel in self.channels:
channelbutton = wx.Button(self, label=channel.getName())
self.Bind(wx.EVT_BUTTON, lambda event:
self.channelChanged(channel), source=channelbutton)

def channelChanged(self, channel):
print "Channel changed to ", channel.getName()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asyncore select statement problem

2007-01-18 Thread Gabriel Genellina
"JamesHoward" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

>I have a problem with python's asyncore module throwing a bad file
> descriptor error.  The code might be difficult to copy here, but the
> problem is essentially:
>
> The server wants to sever the connection of an open Asyncore socket.
> Calling the socket.close() nor the socket.shutdown(2) calls seem to
> work.  The only way I can close the connection without creating the
> error below is to have the client close the connection.

You have to use the dispatcher's close() method, else, the asyncore map 
won't be updated, keeping a reference to the closed socket.

-- 
Gabriel Genellina 


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


Re: import vs. subdirectory search

2007-01-18 Thread Gabriel Genellina
"John Nagle" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

>I'm running Python 2.3.4 from a CGI script on a shared hosting Linux 
> system.
> The CGI program is being executed from Apache, as "nobody".  I have some
> local modules installed in "~myname/lib/python"; these include
> "MySQLdb" and "M2Crypto".
>
>Since this is running as "nobody", I append
>
> /home/myname/lib/python
>
> to sys.path.
>
>Within the CGI programs,
>
> import MySQLdb # works fine
> import M2Crypto # works fine
> import SSL # "No module named SSL"
>
> The problem is that SSL is in a subdirectory of the M2Crypto directory,
> and that's not being searched.
And should *not* be searched, unless the importing module is itself in the 
M2Crypto directory.

> I can execute "import M2Crypto.SSL",
> but that doesn't have the same effect; it puts SSL in a different
> place in the namespace.  I'm trying to avoid that; it causes obscure
> aliasing problems.
You *could* do: from M2Crypto import SSL, but I think this is not your 
problem.

>On Python 2.4 under Windows 2000, importing from a subdirectory
> appears to work.  Is that a Python 2.3.4 thing, or a Linux thing,
> or something else?
No, it should not work as you describe it. Either you have another SSL 
module in another place, or sys.path includes the M2Crypto directory.
On your 2.4 Windows, try this:
import sys
import SSL
print SSL.__file__
print sys.path
and see what happens



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


PythonTidy 1.10

2007-01-18 Thread Chuck Rhode
PythonTidy cleans up, regularizes, and reformats the text of Python
scripts.

It is released under the GNU General Public License.  

Python scripts are usually so good looking that no beautification is
required.  However, from time to time, it may be necessary to alter
the style to conform to changing standards.  This script converts
programs in a consistent way.  It abstracts the pretty presentation of
the symbolic code from the humdrum process of writing it and getting
it to work.

This is an upgrade.  There was a big problem with earlier versions:
Canonical values were substituted for strings and numbers.  For
example, decimal integers were substituted for hexadecimal, and
escaped strings for raw strings.  Authors of Python scripts usually
use peculiar notations for peculiar purposes, and doing away with the
peculiarity negatively impacts the readability of the code.

This version preserves the original constants (parsed by *tokenize*)
in a literal pool indexed by the value they evaluate to.  The
canonical values (output by *compiler*) are then translated back (when
possible) to the original constants by looking them up in the literal
pool.

-- 
http://www.lacusveris.com/PythonTidy/PythonTidy-1.10.python";>PythonTidy
1.10 - Cleans up, regularizes, and reformats the text of Python
scripts. (18-Jan-07)

.. Chuck Rhode, Sheboygan, WI, USA
.. mailto:[EMAIL PROTECTED]
.. Weather:  http://LacusVeris.com/WX
.. 20° — Wind WNW 13 mph

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

Re: urllib2 and transfer-encoding = chunked

2007-01-18 Thread Gabriel Genellina
<[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]
>I am having errors which appear to be linked to a previous bug in
> urllib2 (and urllib) for v2.4 and v2.5 of Python.  Has this been fixed?
> Has anyone established a standard workaround?  I keep finding old
> posts about it, that basically give up and say "well it's a known bug."
> Any help would be greatly appreciated.

Perhaps if you said what the supposed error is...

-- 
Gabriel Genellina 


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


Re: One more regular expressions question

2007-01-18 Thread Neil Cerutti
On 2007-01-18, Victor Polukcht <[EMAIL PROTECTED]> wrote:
> My pattern now is:
>
> (?P[^(]+)(?P\d+)\)\s+(?P\d+)
>
> And i expect to get:
>
> var1 = "Unassigned Number "
> var2 = "1"
> var3 = "32"
>
> I'm sure my regexp is incorrect, but can't understand where
> exactly.

Break it up using verbose notation to help yourself. Also, use
more helpful names. With names like var1 and var2 you might as
well not used named groups.

r = re.compile(r"""(?x)
(?P [^(]+ )
(?P \d+ )
\)
\s+
(?P \d+ )""")

This way it's clearer that there's a \) with no matching \(.

-- 
Neil Cerutti
This team is one execution away from being a very good basketball team. --Doc
Rivers

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

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


Re: Is it possible to fasten the import of cgi?

2007-01-18 Thread Gabriel Genellina
"Cecil Westerhof" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I
> can not time the time used to import time, but os and sys do not take more
> as a millisecond. My script itself takes 3 or 4 milliseconds. But 
> importing
> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
> there a way to make this more fast? The import off cgi makes the script at
> least 20 times as slow. Something like mod-python is not a possibility. I
> could use it on my test machine, but not at the osting provider.
Surely os was imported earlier, and was already loaded. sys is a builtin 
module. But I think your problem is not how much time takes importing cgi, 
but how much time takes launching a new python process on each request.

-- 
Gabriel Genellina 


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


Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread skip

Martin> Could be Afrikaans too, but the page is gone now so I can't
Martin> check.

Actually, you can... ;-) Even though it's a nonexistent page, its history
still exists.  Poke the "Get Info" link and view the first revision of the
file.

Skip

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


  1   2   >