http call.

2006-10-24 Thread Kirt
Hi!

I have a php program (test.php) on a server. eg:
http://abc.xyz.com/test.php

I need my python scripts to make a http call to these program pass some
data and get back a secret key from the php program..

Could anyone help me this, what will i need to make a http call to the
php application?

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


Re: Tkinter question

2006-10-24 Thread Eric Brunel
On Tue, 24 Oct 2006 07:48:51 +0200, Hendrik van Rooyen  
<[EMAIL PROTECTED]> wrote:
>  Sorin Schwimmer  wrote:
> Hi All,
>
> Is it possible to have a widget id while it is created?
> Something like this:
>
> Button(root, text='...', command= lambda v=: fn(v)).grid()
>
> and then the function:
>
> def fn(v):
>   v['bg']='BLUE' # or maybe nametowidget(v)['bg']='BLUE'

This cannot be done this way: when you create your lambda passed to the  
'command' option, the widget itself is not yet created. So there's no way  
at all to get the 'id' it will have when created.

Alternatively, you can simply split the widget creation in several lines:

b = Button(root, text='...')
b.grid()
b.configure(command=lambda b=b: fn(b))


But Hendrik's solution is better, since it avoids the use of lambda, which  
is often difficult to understand.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


can't open word document after string replacements

2006-10-24 Thread Antoine De Groote
Hi there,

I have a word document containing pictures and text. This documents 
holds several 'ABCDEF' strings which serve as a placeholder for names. 
Now I want to replace these occurences with names in a list (members). I 
open both input and output file in binary mode and do the 
transformation. However, I can't open the resulting file, Word just 
telling that there was an error. Does anybody what I am doing wrong?

Oh, and is this approach pythonic anyway? (I have a strong Java background.)

Regards,
antoine


import os

members = somelist

os.chdir(somefolder)

doc = file('ttt.doc', 'rb')
docout = file('ttt1.doc', 'wb')

counter = 0

for line in doc:
 while line.find('ABCDEF') > -1:
 try:
 line = line.replace('ABCDEF', members[counter], 1)
 docout.write(line)
 counter += 1
 except:
 docout.write(line.replace('ABCDEF', '', 1))
 else:
 docout.write(line)

doc.close()
docout.close()

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


Re: Attempting to parse free-form ANSI text.

2006-10-24 Thread Frederic Rentsch

Steve Holden wrote:

Frederic Rentsch wrote:
  

Frederic Rentsch wrote:



Frederic Rentsch wrote:
 

  

Paul McGuire wrote:
 
   


"Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message 
   
 
  
Sorry about the line wrap mess in the previous message. I try again with 
another setting:


Frederic
 
  

I give up!




Don't give up, attach it as a file!

regards
  Steve
  


Thank you for the encourangement!

Frederic

The following code does everything Mike needs to do, except interact with wx. 
It is written to run standing alone. To incorporate it in Mike's class the 
functions would be methods and the globals would be instance attributes. 
Running it does this:

>>> chunk_1 = """This is a test string containing some ANSI sequences.
Sequence 1 Valid code, invalid numbers: \x1b[10;12mEnd of sequence 1
Sequence 2 Not an 'm'-code: \x1b[30;4;77hEnd of sequence 2
Sequence 3 Color setting code: \x1b[30;45mEnd of sequence 3
Sequence 4 Parameter setting code: \x1b[7mEnd of sequence 4
Sequence 5 Color setting code spanning calls: \x1b[3"""

>>> chunk_2 = """7;42mEnd of sequence 5
Sequence 6 Invalid code: \x1b[End of sequence 6
Sequence 7 A valid code at the end: \x1b[9m
"""

>>> init ()
>>> process_text (chunk_1)
>>> process_text (chunk_2)
>>> print output

This is a test string containing some ANSI sequences.
Sequence 1 Valid code, invalid numbers:  >>!!!Ignoring unknown number 10!!!<<  
>>!!!Ignoring unknown number 1!!!<< End of sequence 1
Sequence 2 Not an 'm'-code: End of sequence 2
Sequence 3 Color setting code:  >>setting foreground BLACK<<  >>setting 
background MAGENTA<< End of sequence 3
Sequence 4 Parameter setting code:  >>Calling parameter setting function 7<< 
End of sequence 4
Sequence 5 Color setting code spanning calls:  >>setting foreground GREY<<  
>>setting background GREEN<< End of sequence 5
Sequence 6 Invalid code: nd of sequence 6
Sequence 7 A valid code at the end:  >>Calling parameter setting function 9<<


#


def init (): # This would have to be added to __init__ ()

   import SE   # SEL is less import overhead but doesn't have interactive 
development features (not needed in production versions)
  
   global output  #-> For testing
   global Pre_Processor, digits_re, Colors, truncated_escape_hold   # global -> 
instance attributes
  
   # Screening out invalid characters and all ansi escape sequences except 
those controlling color
   grit = '\n'.join (['(%d)=' % i for i in range (128,255)]) + ' (13)= '  # 
Makes 127 fixed expressions plus deletion of \r
   # Regular expression r'[\x80-\xff\r]' would work fine but is four times 
slower than 127 fixed expressions
   all_escapes   = r'\x1b\[\d*(;\d*)*[A-Za-z]'
   color_escapes = r'\x1b\[\d*(;\d*)*m'
   Pre_Processor = SE.SE ('%s ~%s~= ~%s~==' % (grit, all_escapes, 
color_escapes))  # SEL.SEL for production
   # 'all_escapes' also matches what 'color_escapes' matches. With identical 
regular expression matches the last regex definition applies.
  
   # Isolating digits.
   digits_re = re.compile ('\d+')
  
   # Color numbers to color names
   Colors = SE.SE ('''
   30=BLACK40=BLACK
   31=RED  41=RED
   32=GREEN42=GREEN
   33=YELLOW   43=YELLOW
   34=BLUE 44=BLUE
   35=MAGENTA  45=MAGENTA
   36=CYAN 46=CYAN
   37=GREY 47=GREY
   39=GREY 49=BLACK
   
   ''')
  
   truncated_escape_hold = ''  #-> self.truncated_escape_hold
   output= ''  #-> For testing only



# What follows replaces all others of Mike's methods in class 
AnsiTextCtrl(wx.TextCtrl)

def process_text (text):

   global output  #-> For testing
   global truncated_escape_hold, digits_re, Pre_Processor, Colors
   
   purged_text = truncated_escape_hold + Pre_Processor (text)
   # Text is now clean except for color codes, which beginning with ESC
   
   ansi_controlled_sections = purged_text.split ('\x1b')
   # Each section starts with a color control, except the first one (leftmost 
split-off)
   
   if ansi_controlled_sections:
  #-> self.AppendText(ansi_controlled_sections [0]) #-> For real
  output += ansi_controlled_sections [0]#-> For 
testing
  for section in ansi_controlled_sections [1:]:
 if section == '': continue
 try: escape_ansi_controlled_section, data = section.split ('m', 1)
 except ValueError:   # Truncated escape
truncated_escape_hold = '\x1b' + section  # Restore ESC removed by 
split ('\x1b')
 else:
escapes = escape_ansi_controlled_section.split (';')
for escape in escapes:
   try: number = digits_re.search (escape).group ()
   except AttributeError:
  output += ' >>!!!Invalid number %s!!!<<< ' % escape#-> 
For testing
  continue
   _set_wx (number)
#-> self.AppendText(data) #-> For real
out

Re: Sorting by item_in_another_list

2006-10-24 Thread Cameron Walsh
Delaney, Timothy (Tim) wrote:
> Cameron Walsh wrote:
> 
>> Hi,
>>
>> I have two lists, A and B, such that B is a subset of A.
>>
>> I wish to sort A such that the elements in B are at the beginning of
>> A, and keep the existing order otherwise, i.e. stable sort.  The
>> order of elements in B will always be correct.
>>
>> for example:
>>
>> A = [0,1,2,3,4,5,6,7,8,9,10]
>> B = [2,3,7,8]
>>
>> desired_result = [2,3,7,8,0,1,4,5,6,9,10]
> 
> c = set(B)
> a.sort(key=c.__contains__, reverse=True)
> 
> Tim Delaney

Depressingly simple.  I like it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Protecting against SQL injection

2006-10-24 Thread Tor Erik Soenvisen
Hi,

How safe is the following code against SQL injection:

# Get user privilege
digest = sha.new(pw).hexdigest()
# Protect against SQL injection by escaping quotes
uname = uname.replace("'", "''")
sql = 'SELECT privilege FROM staff WHERE ' + \
  'username=\'%s\' AND password=\'%s\'' % (uname, digest)
res = self.oraDB.query(sql)

pw is the supplied password abd uname is the supplied password.

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


Re: Protecting against SQL injection

2006-10-24 Thread Paul Rubin
Tor Erik Soenvisen <[EMAIL PROTECTED]> writes:
> # Protect against SQL injection by escaping quotes

Don't ever do that, safe or not.  Use query parameters instead.
That's what they're for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 ; Effbot console ; thank ; pb release.

2006-10-24 Thread Ben Finney
"Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:

[quoting problems fixed]

>  "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:
> > some days, I ask myself why I shouldn't just use GPL for
> > everything I do, and ship it as source code only.
>
> because then you would deny your work to thousands of ungrateful,
> unmotivated lazy buggers like me...

Not necessarily. All it needs is one person (with the same platform
you want to use) to take the source, build it for that platform, and
make it available. All the other "ungrateful, unmotivated lazy
buggers" can then take advantage of that -- and reward the person with
whatever praise they require :-)

-- 
 \  "Behind every successful man is a woman, behind her is his |
  `\   wife."  -- Groucho Marx |
_o__)  |
Ben Finney

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


Re: Python 2.5 ; Effbot console ; thank ; pb release.

2006-10-24 Thread Thomas Heller
Ben Finney schrieb:
> "Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
> 
> [quoting problems fixed]
> 
>>  "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:
>> > some days, I ask myself why I shouldn't just use GPL for
>> > everything I do, and ship it as source code only.
>>
>> because then you would deny your work to thousands of ungrateful,
>> unmotivated lazy buggers like me...
> 
> Not necessarily. All it needs is one person (with the same platform
> you want to use) to take the source, build it for that platform, and
> make it available. All the other "ungrateful, unmotivated lazy
> buggers" can then take advantage of that -- and reward the person with
> whatever praise they require :-)
> 
I wonder if it would be possible to setup a windows box which provides
a (web-)service that allows to build Python packages.

Any ideas how this could be made secure?

Thomas

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


Re: pretty basic instantiation question

2006-10-24 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Why do you need to know the number of instances. I know that Python
> does not support Class Variable,

Plain wrong.

class Class(object):
  classvar = ["w", "t", "f"]

print Class.classvar

c = Class()
c.classvar.append("???")
print c.classvar


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


Re: pytho servlet engine

2006-10-24 Thread Bruno Desthuilliers
makerjoe wrote:
> hi, all
> i would like to know which is the best PSE

"best" according to what metrics ?

> i have to choose to use
> servlets with mod_python in my HRYDROGEN project
> (http://makerjoe.sytes.net/pycrud/query.psp)




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


Re: Protecting against SQL injection

2006-10-24 Thread Ben Finney
Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes:

> Tor Erik Soenvisen <[EMAIL PROTECTED]> writes:
> > # Protect against SQL injection by escaping quotes
>
> Don't ever do that, safe or not.  Use query parameters instead.
> That's what they're for.

More specifically: They've been debugged for just these kinds of
purposes, and every time you code an ad-hoc escaping-and-formatting
SQL query, you're inviting all the bugs that have been found and
removed before.

-- 
 \ "Welchen Teil von 'Gestalt' verstehen Sie nicht?  [What part of |
  `\ 'gestalt' don't you understand?]"  -- Karsten M. Self |
_o__)  |
Ben Finney

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


Re: http call.

2006-10-24 Thread Bruno Desthuilliers
Kirt wrote:
> Hi!
> 
> I have a php program (test.php) on a server. eg:
> http://abc.xyz.com/test.php
> 
> I need my python scripts to make a http call to these program pass some
> data and get back a secret key from the php program..
> 
> Could anyone help me this, what will i need to make a http call to the
> php application?
> 
The fact that it's a PHP (or Java or Python or .NET or whatever)
application is totally orthogonal as long as you're using HTTP. And you
may want to have a look at the urllib and urllib2 modules in the
standard lib.

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


Re: can't open word document after string replacements

2006-10-24 Thread Daniel Dittmar
Antoine De Groote wrote:
> I have a word document containing pictures and text. This documents 
> holds several 'ABCDEF' strings which serve as a placeholder for names. 
> Now I want to replace these occurences with names in a list (members). I 
> open both input and output file in binary mode and do the 
> transformation. However, I can't open the resulting file, Word just 
> telling that there was an error. Does anybody what I am doing wrong?

The Word document format probably contains some length information about 
paragraphs etc. If you change a string to another one of a different 
length, this length information will no longer match the data and the 
document structure will be hosed.

Possible solutions:
1. Use OLE automation (in the python win32 package) to open the file in 
Word and use Word search and replace. Your script could then directly 
print the document, which you probably have to do anyway.

2. Export the template document to RTF. This is a text format and can be 
more easily manipulated with Python.

> for line in doc:

I don't think that what you get here is actually a line of you document. 
Due to the binary nature of the format, it is an arbitrary chunk.

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


Re: can't open word document after string replacements

2006-10-24 Thread Bruno Desthuilliers
Antoine De Groote wrote:
> Hi there,
> 
> I have a word document containing pictures and text. This documents
> holds several 'ABCDEF' strings which serve as a placeholder for names.
> Now I want to replace these occurences with names in a list (members).

Do you know that MS Word already provides this kind of features ?

> I
> open both input and output file in binary mode and do the
> transformation. However, I can't open the resulting file, Word just
> telling that there was an error. Does anybody what I am doing wrong?

Hand-editing a non-documented binary format may lead to undesirable
results...

> Oh, and is this approach pythonic anyway? 

The pythonic approach is usually to start looking for existing
solutions... In this case, using Word's builtin features and Python/COM
integration would be a better choice IMHO.

> (I have a strong Java
> background.)

Nobody's perfect !-)

> Regards,
> antoine
> 
> 
> import os
> 
> members = somelist
> 
> os.chdir(somefolder)
> 
> doc = file('ttt.doc', 'rb')
> docout = file('ttt1.doc', 'wb')
> 
> counter = 0
> 
> for line in doc:

Since you opened the file as binary, you should use file.read() instead.
Ever wondered what your 'lines' look like ?-)

> while line.find('ABCDEF') > -1:

.doc is a binary format. You may find such a byte sequence in it's
content in places that are *not* text content.

> try:
> line = line.replace('ABCDEF', members[counter], 1)
> docout.write(line)

You're writing back the whole chunk on each iteration. No surprise the
resulting document is corrupted.

> counter += 1

seq = list("abcd")
for indice, item in enumerate(seq):
  print "%02d : %s" % (indice, item)


> except:
> docout.write(line.replace('ABCDEF', '', 1))
> else:
> docout.write(line)
> 
> doc.close()
> docout.close()
> 



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


Re: can't open word document after string replacements

2006-10-24 Thread Jon Clements

Antoine De Groote wrote:

> Hi there,
>
> I have a word document containing pictures and text. This documents
> holds several 'ABCDEF' strings which serve as a placeholder for names.
> Now I want to replace these occurences with names in a list (members). I
> open both input and output file in binary mode and do the
> transformation. However, I can't open the resulting file, Word just
> telling that there was an error. Does anybody what I am doing wrong?
>
> Oh, and is this approach pythonic anyway? (I have a strong Java background.)
>
> Regards,
> antoine
>
>
> import os
>
> members = somelist
>
> os.chdir(somefolder)
>
> doc = file('ttt.doc', 'rb')
> docout = file('ttt1.doc', 'wb')
>
> counter = 0
>
> for line in doc:
>  while line.find('ABCDEF') > -1:
>  try:
>  line = line.replace('ABCDEF', members[counter], 1)
>  docout.write(line)
>  counter += 1
>  except:
>  docout.write(line.replace('ABCDEF', '', 1))
>  else:
>  docout.write(line)
>
> doc.close()
> docout.close()

Errr I wouldn't even attempt to do this; how do you know each
'line' isn't going to be split arbitarily, and that 'ABCDEF' doesn't
happen to be part of an image. As you've noted, this is binary data so
you can't assume anything about it. Doing it this way is a Bad Idea
(tm).

If you want to do something like this, why not use templated HTML, or
possibly templated PDFs? Or heaven forbid, Word's mail-merge facility?


(I think MS Office documents are effectively self-contained file
systems, so there is probably some module out there which can
read/write them).

Jon.

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


forcing a definition to be called on attribute change

2006-10-24 Thread Michael Malinowski
Hey All, 
Apologies if this is a stupidly obvious or simple question. If I have a
class with a series of attributes, is there a way to run a function
definition in the class whenever a specific attribute is changed?

Something like the following 

class cSphere() :

def __init__(self):
Self.myAttr = 0

def runThisFunctionWhenMyAttrChanged() :
Pass




Thanks

Mike.

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


Re: Protecting against SQL injection

2006-10-24 Thread Fredrik Lundh
Ben Finney wrote:

> More specifically: They've been debugged for just these kinds of
> purposes

in a well-designed database, the SQL parser never sees the parameter values,
so *injection* attacks are simply not possible.

 



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


Re: Tkinter question

2006-10-24 Thread Fredrik Lundh
Eric Brunel wrote:

> But Hendrik's solution is better, since it avoids the use of lambda, which
> is often difficult to understand.

storing the button reference in a variable doesn't help if you want to use the
same callback for multiple buttons, though...

 



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


Re: How to get each pixel value from a picture file!

2006-10-24 Thread Fredrik Lundh
Dennis Lee Bieber wrote:

>> 2) i think putpixel((44, 55), (0, 0, 0)) and putpixel((44,55),0) is
>> same.
>
> It shouldn't be... The former is three separate data values, the
> latter is one.

the "putpixel" API is polymorphic; you can use either tuples or integers
for RGB pixels (the latter should have the form 0xAARRGGBB).

 



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


Re: Screen capture on Linux

2006-10-24 Thread Fredrik Lundh
Paolo Pantaleo wrote:

> If needed, I was thinking to write a C module too. I never did it
> before, but I am a not so bad C programmer... any suggestion? What
> code can I read and eventually reuse? Would the xwd be useful?
>
> Anyway doesn't it exist a Python binding for let's say X APIs ?

http://sourceforge.net/projects/python-xlib

(that's an X protocol client, not a binding to X's standard C library).

 



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


Re: Python 2.5 ; Effbot console ; thank ; pb release.

2006-10-24 Thread Laurent Pointal
Thomas Heller a écrit :
> Ben Finney schrieb:
>> "Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
>>
>> [quoting problems fixed]
>>
>>>  "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:
 some days, I ask myself why I shouldn't just use GPL for
 everything I do, and ship it as source code only.
>>> because then you would deny your work to thousands of ungrateful,
>>> unmotivated lazy buggers like me...
>> Not necessarily. All it needs is one person (with the same platform
>> you want to use) to take the source, build it for that platform, and
>> make it available. All the other "ungrateful, unmotivated lazy
>> buggers" can then take advantage of that -- and reward the person with
>> whatever praise they require :-)
>>
> I wonder if it would be possible to setup a windows box which provides
> a (web-)service that allows to build Python packages.

You will have the problem of third-party libraries dependancies (and
installation).

> Any ideas how this could be made secure?
> 
> Thomas
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Socket module bug on OpenVMS

2006-10-24 Thread Jean-François Piéronne
Irmen de Jong wrote:
> Martin v. Löwis wrote:
[snip]
>> Perhaps you had some different work-around in mind?
> 
> Nope, I was indeed thinking about splitting up the recv() into
> smaller blocks internally.
> Maybe a more elaborate check in Python's build system (to remove
> the MSG_WAITALL on VMS) would qualify as some sort of work-around
> as well. Although that would not yet solve the errors you get when
> using too big recv() buffer sizes.
> 

I have contact some guys from HP, unofficial reply is if it's not
documented it's not supported... Why it's defined in socket.h may be
because the TCP/IP stack from HP on OpenVMS is a port of the Tru64 Unix
stack and the flag was present in Tru64.
We will also investigate if the behaviour on OpenVMS when you use
MSG_WAITALL is broken or not.

So I will, in a forthcoming kit don't export this symbol under OpenVMS
(if it's not documented it's not supported).
I have also take a look at the problem of using big recv() buffer and
found a bug when the buffer size is > 32767, only the first 32767 bytes
are read, this will be also fixed in the next kit (only Python 2.5).

I expect to have a new kit which include all these fixes be available
before the end of the week.


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


Re: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-24 Thread Paul Boddie
Martin v. Löwis wrote:
> Georg Brandl schrieb:
> > Perhaps you can bring up a discussion on python-dev about your improvements
> > and how they could be integrated into the standard library...
>
> Let me second this. The compiler package is largely unmaintained and
> was known to be broken (and perhaps still is). A replacement
> implementation, especially if it comes with a new maintainer, would
> be welcome.

I don't agree entirely with the "broken" assessment. Although I'm not
chasing the latest language constructs, the AST construction part of
the package seems good enough to me, and apparent bugs like duplicate
parameters in function signatures are actually documented shortcomings
of the functionality provided. I certainly don't like the level of code
documentation; from the baroque compiler.visitor, for example:

# XXX should probably rename ASTVisitor to ASTWalker
# XXX can it be made even more generic?

However, a cursory scan of the bugs filed against the compiler module,
trying hard to filter out other compiler-related things, reveals that
most of the complaints are related to code generation, and the
compiler2 module appears to be squarely aimed at this domain.

I find the compiler package useful - at least the bits not related to
code generation - and despite apparent unawareness of its existence in
the community (judging from observed usage of the parser and tokenizer
modules in cases where the compiler module would have been more
appropriate), I'd be unhappy to see it dropped.

Paul

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


Re: forcing a definition to be called on attribute change

2006-10-24 Thread Fredrik Lundh
Michael Malinowski wrote:

> Apologies if this is a stupidly obvious or simple question. If I have a
> class with a series of attributes, is there a way to run a function
> definition in the class whenever a specific attribute is changed?

you can implement a __setattr__ hook, or, in Python 2.2 and newer, use
properties:


http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION00034

note that "setter" properties only work if you inherit from "object".

 



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


Re: python GUIs comparison (want)

2006-10-24 Thread Paul Boddie
Cameron Walsh wrote:
>
> I googled "python gui compare" a while back and got
> www.awaretek.com/toolkits.html as the first result.

See also the python.org Wiki for more information:

http://wiki.python.org/moin/UsefulModules
http://wiki.python.org/moin/GuiProgramming (big list!)

> Every variation on the values I entered seemed to point me to wxPython,
> which I'm still using now.  However, they seem to think that EasyGUI is
> the easiest to learn, but that it suffers on "Maturity, documentation,
> breadth of widget selection".

The figures behind the scenes are quite enlightening for that
particular page. If you (or community experiences) don't agree with the
rankings (wxPython apparently even easier to learn than PythonCard and
Tkinter, a bunch of Gtk-based toolkits having more or less "full" Linux
scores) then you'll have some surprises, I'm sure. Nevertheless, it's
an interesting concept.

Paul

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


Re: Python 2.5 ; Effbot console ; thank ; pb release.

2006-10-24 Thread Paul Boddie
Thomas Heller wrote:
>
> I wonder if it would be possible to setup a windows box which provides
> a (web-)service that allows to build Python packages.

Isn't this the kind of service your distribution vendor should be
providing, especially if you've paid them good money? Oh wait! That
would be Microsoft, wouldn't it? ;-)

Still, there's always ActiveState, and I guess they still have that PPM
installer utility for people wanting some kind of binary package
download mechanism.

Paul

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


RE: python thread state

2006-10-24 Thread Stefan Schukat
For this use case the PyGILState API was introduced. 

e.g. try
PyGILState_STATE state = PyGILState_Ensure()
run python code
PyGILState_Release(state) 

Stefan

> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On 
> Behalf Of Bryan
> Sent: Monday, October 23, 2006 2:32 PM
> To: [email protected]
> Subject: python thread state
> 
> hi,
> 
> i'm trying to write a multithreaded embedded python 
> application and i'm having some trouble.  i found this 
> article "embedding python in multi-threaded c/c++ 
> applications" in the python journal
> (http://www.linuxjournal.com/article/3641) but there still 
> seems to be a step missing for me.
> 
> each time a function in my c module is called, it's called on 
> a different c thread.  i would then like to call a function 
> in an embedded python script.
> from my understanding of the article, you can associate a 
> python script with a c thread by calling PyThreadState_New as 
> in this code:
> 
> // save main thread state
> PyThreadState * mainThreadState = NULL;
> mainThreadState = PyThreadState_Get();
> PyEval_ReleaseLock();
> 
> // setup for each thread
> PyEval_AcquireLock();
> PyInterpreterState * mainInterpreterState = 
> mainThreadState->interp PyThreadState * myThreadState = 
> PyThreadState_New(mainInterpreterState);
> PyEval_ReleaseLock();
> 
> //execute python code
> PyEval_AcquireLock();
> PyThreadState_Swap(myThreadState);
> # execute python code
> PyThreadState_Swap(NULL);
> PyEval_ReleaseLock();
> 
> 
> unfortunately, this doesn't work for me because each time i 
> get called to execute python code, i'm in a new c thread and 
> PyThreadState_Swap seems to want to be executed in the same c 
> thread that PyThreadState_New was executed in.  if this isn't 
> the case, please let know.  
> 
> i then called PyThreadState_New each time i wanted to call a 
> python function in the script, but PyThreadState_New wipes 
> out, or rather gives you a new global dictionary, because i 
> lost all my global variables.  the article assumes you have 
> one c thread per python thread state, but i want multiple c 
> threads per python thread state. Is there a c api function 
> that will associate a c thread without resetting the global 
> dictionary?
> 
> thank you,
> 
> bryan
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't open word document after string replacements

2006-10-24 Thread Antoine De Groote
Thank you all for your comments.

I ended up saving the word document in XML and then using (a slightly 
modified version of) my script of the OP. For those interested, there 
was also a problem with encodings.

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


Re: can't open word document after string replacements

2006-10-24 Thread Antoine De Groote
Bruno Desthuilliers wrote:
> Antoine De Groote wrote:
>> Hi there,
>>
>> I have a word document containing pictures and text. This documents
>> holds several 'ABCDEF' strings which serve as a placeholder for names.
>> Now I want to replace these occurences with names in a list (members).
> 
> Do you know that MS Word already provides this kind of features ?


No, I don't. Sounds interesting... What is this feature called?

> 
>> I
>> open both input and output file in binary mode and do the
>> transformation. However, I can't open the resulting file, Word just
>> telling that there was an error. Does anybody what I am doing wrong?
> 
> Hand-editing a non-documented binary format may lead to undesirable
> results...
> 
>> Oh, and is this approach pythonic anyway? 
> 
> The pythonic approach is usually to start looking for existing
> solutions... In this case, using Word's builtin features and Python/COM
> integration would be a better choice IMHO.
> 
>> (I have a strong Java
>> background.)
> 
> Nobody's perfect !-)
> 
>> Regards,
>> antoine
>>
>>
>> import os
>>
>> members = somelist
>>
>> os.chdir(somefolder)
>>
>> doc = file('ttt.doc', 'rb')
>> docout = file('ttt1.doc', 'wb')
>>
>> counter = 0
>>
>> for line in doc:
> 
> Since you opened the file as binary, you should use file.read() instead.
> Ever wondered what your 'lines' look like ?-)
> 
>> while line.find('ABCDEF') > -1:
> 
> .doc is a binary format. You may find such a byte sequence in it's
> content in places that are *not* text content.
> 
>> try:
>> line = line.replace('ABCDEF', members[counter], 1)
>> docout.write(line)
> 
> You're writing back the whole chunk on each iteration. No surprise the
> resulting document is corrupted.
> 
>> counter += 1
> 
> seq = list("abcd")
> for indice, item in enumerate(seq):
>   print "%02d : %s" % (indice, item)
> 
> 
>> except:
>> docout.write(line.replace('ABCDEF', '', 1))
>> else:
>> docout.write(line)
>>
>> doc.close()
>> docout.close()
>>
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multythreading app memory consumption

2006-10-24 Thread Andrew MacIntyre
Bryan Olson wrote:

> In Python 2.5, each thread will be allocated
> 
>  thread.stack_size()
> 
> bytes of stack address space. Note that address space is
> not physical memory, nor even virtual memory. On modern
> operating systems, the memory gets allocated as needed,
> and 150 threads is not be a problem.

Just a note that [thread|threading].stack_size() returns 0 to indicate
the platform default, and that value will always be returned unless an
explicit value has previously been set.

The Posix thread platforms (those that support programmatic setting of
this parameter) have the best support for sanity checking the requested
size - the value gets checked when actually set, rather than when the
thread creation is attempted.

The platform default thread stack sizes I can recall are:
Windows:  1MB (though this may be affected by linker options)
Linux:1MB or 8MB depending on threading library and/or distro
FreeBSD:  64kB

-- 
-
Andrew I MacIntyre "These thoughts are mine alone..."
E-mail: [EMAIL PROTECTED]  (pref) | Snail: PO Box 370
[EMAIL PROTECTED] (alt) |Belconnen ACT 2616
Web:http://www.andymac.org/   |Australia
-- 
http://mail.python.org/mailman/listinfo/python-list


[OT] Re: can't open word document after string replacements

2006-10-24 Thread Bruno Desthuilliers
Antoine De Groote wrote:
> Bruno Desthuilliers wrote:
>> Antoine De Groote wrote:
>>> Hi there,
>>>
>>> I have a word document containing pictures and text. This documents
>>> holds several 'ABCDEF' strings which serve as a placeholder for names.
>>> Now I want to replace these occurences with names in a list (members).
>>
>> Do you know that MS Word already provides this kind of features ?
> 
> 
> No, I don't. Sounds interesting... What is this feature called?

I don't know how it's named in english, but in french it's (well - it
was last time I used MS Word, which is quite some times ago???) "fusion
de documents".



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


Re: sharing persisten cache between modules

2006-10-24 Thread Bart Ogryczak

Dennis Lee Bieber wrote:
> f-i-* creates local names initially bound to the objects inside a
> module, but any "assignment" to such a name later results in the name
> being rebound to the new object -- disconnecting from the original.

Great! That was it. Thank you! :-)

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


Re: forcing a definition to be called on attribute change

2006-10-24 Thread Bruno Desthuilliers
Michael Malinowski wrote:
> Hey All, 
> Apologies if this is a stupidly obvious or simple question. If I have a
> class with a series of attributes, is there a way to run a function
> definition in the class

s/run a function definition in the class/call a method/

> whenever a specific attribute is changed?

Yes : properties.

> Something like the following 
> 
> class cSphere() :

OT : prefixing classes names with 'c' is totally unpythonic.

>   def __init__(self):
>   Self.myAttr = 0

s/Self/self/

>   def runThisFunctionWhenMyAttrChanged() :
>   Pass


class MyClass(object):
  def __init__(self):
self.my_attr = 0 # will call the setter
# use direct attribute access instead if you don't
# want to call the setter, ie:
# self._my_attr = 0

  def _get_my_attr(self):
return self._my_attr

  def _set_my_attr(self, val):
self._my_attr = val
self.runThisFunctionWhenMyAttrChanged()

  my_attr = property(_get_my_attr, _set_my_attr)

HTH

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


Re: sharing persisten cache between modules

2006-10-24 Thread Steve Holden
Dennis Lee Bieber wrote:
> On 23 Oct 2006 09:45:33 -0700, "Bart Ogryczak" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> 
> 
>>The problem is, that then it is not shared. If I do it like that, each
>>module has it´s own copy of the cache. Maybe I´m doing something
>>wrong. I´ve made a cache module, imported it in each of the
>>submodules. I don´t know how to make the data "static".
> 
> 
>   Let me guess... You are using
> 
> from cache_module import *
> 
> to save having to qualify names with "cache_module."
> 
> f-i-* creates local names initially bound to the objects inside a
> module, but any "assignment" to such a name later results in the name
> being rebound to the new object -- disconnecting from the original.
> 
> import cache_module
> 
> cache_module.some_name = some_object
> 
> maintains the linkage that the name is inside the module, so all other
> references that use cache_module.some_name will see the same object.

Note that you can also do

   import cache_module_with_long_name as cm

and then qualify cm to get at the module's attributes, should you have 
chosen to call your module something inappropriately long. This reduces 
the typing still further.

always-looking-to-avoid-typos-ly y'rs  - steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: numpy error

2006-10-24 Thread Juergen Kareta

> Or install the numpy-1.0rc2 binary which is now again available on 
> sourceforge.

Hello Travis,

thanks for your help. Going back to the 1.0rc2 release was successful. 
Ok, I had also to copy wxmsw26uh_vc.dll to my path and get around 
wx.PrindData.SetPrinterCommand, but that's because I run wxpython 
2.7.1.2. Since it's really fresh it'll take a little time to adapt in 
all third parties.

Jürgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: http call.

2006-10-24 Thread Steve Holden
Kirt wrote:
> Hi!
> 
> I have a php program (test.php) on a server. eg:
> http://abc.xyz.com/test.php
> 
> I need my python scripts to make a http call to these program pass some
> data and get back a secret key from the php program..
> 
> Could anyone help me this, what will i need to make a http call to the
> php application?
> 

import urllib
nf = urllib.urlopen('http://abc.xyz.com/test.php')
data = nf.read()

Should get you started. Look for the "mechanize" and "ClientForm" (?) 
modules to help with the site interactions. It doesn't matter what 
language the server uses: you will be talking HTTP to it!

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

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


Re: can't open word document after string replacements

2006-10-24 Thread Steve Holden
Antoine De Groote wrote:
> Bruno Desthuilliers wrote:
> 
>>Antoine De Groote wrote:
>>
>>>Hi there,
>>>
>>>I have a word document containing pictures and text. This documents
>>>holds several 'ABCDEF' strings which serve as a placeholder for names.
>>>Now I want to replace these occurences with names in a list (members).
>>
>>Do you know that MS Word already provides this kind of features ?
> 
> 
> 
> No, I don't. Sounds interesting... What is this feature called?
> 
Mail-merge, I believe.

However, if your document can be adequately represented in RTF 
(rich-text format) then you could consider doing string replacements on 
that. I invoice the PyCon sponsors using this rather inelegant technique.

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

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


Re: FTP over SSL

2006-10-24 Thread Stefan Schwarzer
On 2006-10-20 15:50, Tor Erik Soenvisen wrote:
> Anyone know about existing code supporting FTP over SSL?
> I guess pycurl http://pycurl.sourceforge.net/ could be used, but that
> requires knowledge of libcurl, which I haven't.

Possibly you could use M2Crypto [1]. It has a FTP_TLS class
in module ftpslib which is similar to ftplib.FTP. To use FTP
more easily, you can use ftputil [2] (I'm its author). You
should be able to use M2Crypto via ftputil [3].

[1] http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto#Downloads
[2] http://ftputil.sschwarzer.net
[3] 
http://ftputil.sschwarzer.net/trac/browser/branches/add_stat_caching/ftputil.txt?rev=622
line 893

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


Python Crytographic Toolkit, AES and OpenPGP

2006-10-24 Thread ml1n
Hello,
Does anybody have an example of using Crypto.Cipher.AES to encrypt an
OpenPGP literal data packet?  I can't get MODE_PGP to work at all (gpg
doesn't recognise the unencrypted packet), with MODE_CFB gpg correctly
identifies the packet after decryption but it's body is incorrect
(suggesting the first 2 bytes decrypt/encrypt ok but the rest
doesn't?). I know the plain text version of the packet is ok because I
can add it to the stream without encryption and gpg will process it ok.

Here is what I'm trying (text is the pre constructed packet):

aes_obj =
Crypto.Cipher.AES.new(self.sessionKey,Crypto.Cipher.AES.MODE_CFB,"\x00"*16)
padding = self.randPool.get_bytes(Crypto.Cipher.AES.block_size)
padding = "%s%s" % (padding,padding[-2:])
self.enc_text = aes_obj.encrypt("%s%s" % (padding,text))

I'm sure I'm missing something obvious, Any pointers gratefully
recieved.

Thanks.
M.

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


Re: Protecting against SQL injection

2006-10-24 Thread Steve Holden
Tor Erik Soenvisen wrote:
> Hi,
> 
> How safe is the following code against SQL injection:
> 
> # Get user privilege
> digest = sha.new(pw).hexdigest()
> # Protect against SQL injection by escaping quotes
> uname = uname.replace("'", "''")
> sql = 'SELECT privilege FROM staff WHERE ' + \
>   'username=\'%s\' AND password=\'%s\'' % (uname, digest)
> res = self.oraDB.query(sql)
> 
> pw is the supplied password abd uname is the supplied password.
> 
Slightly safer than not doing anything to the user-supplied inputs, but 
nowehere near as safe as it needs to be. Use parameterized queries!

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

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


Change on file

2006-10-24 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


Hello,

I was thinking about use md5 check to se if a file had changes since last 
check. Am I correct?
Is there any other light method?

F

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


Re: python GUIs comparison (want)

2006-10-24 Thread Peter Decker
On 23 Oct 2006 22:07:39 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Now i began to learn GUI programming. There are so many
> choices of GUI in the python world, wxPython, pyGTK, PyQT,
> Tkinter, .etc, it's difficult for a novice to decide, however.
> Can you draw a comparison among them on easy coding, pythonish design,
> beautiful and generous looking, powerful development toolkit, and
> sufficient documentation, .etc.
> It's helpful for a GUI beginner.
> Thank you.

I've used several, and I think that Dabo (http://dabodev.com) is the
best choice. Dabo is an entire application framework, but you can just
use the dabo.ui parts if that's all you need. Then when you are no
longer a beginner and you want to develop more complex apps, you won't
need to change tools.

-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Change on file

2006-10-24 Thread Sybren Stuvel
Fulvio enlightened us with:
> I was thinking about use md5 check to se if a file had changes since
> last check. Am I correct?

You can do that, but a check on the mtime (os.stat) would be a lot
easier.

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


Re: Change on file

2006-10-24 Thread Marshall
You could use ctime to see it by the time.

MD5 it's a most secure way to a file that CAN'T be modified. If you
just want to see if the file has been modified (like to make a cache),
use ctime.

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


Re: [OT] Re: can't open word document after string replacements

2006-10-24 Thread Richie Hindle

[Antoine]
> I have a word document containing pictures and text. This documents
> holds several 'ABCDEF' strings which serve as a placeholder for names.
> Now I want to replace these occurences with names in a list (members).

[Bruno]
> I don't know how it's named in english, but in french it's (well - it
> was last time I used MS Word, which is quite some times ago???) "fusion
> de documents".

"Mail Merge"?

-- 
Richie Hindle
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Change on file

2006-10-24 Thread Alan Franzoni
Il Tue, 24 Oct 2006 19:47:43 +0800, Fulvio ha scritto:

> Hello,
> 
> I was thinking about use md5 check to se if a file had changes since last 
> check. Am I correct?
> Is there any other light method?

It's OK, but if you have a lot of files to check and they're large, and
changes frequent, it could put the system under severe workload.

If you just need to know if a file has changed, you can check via
date/time, or if you don't trust somebody who's got access to it (because
he could have manually altered the datetime) you could go for a simpler
algorithm, like sfv.

-- 
Alan Franzoni <[EMAIL PROTECTED]>
-
Togli .xyz dalla mia email per contattarmi.
Remove .xyz from my address in order to contact me.
-
GPG Key Fingerprint (Key ID = FE068F3E):
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E 
-- 
http://mail.python.org/mailman/listinfo/python-list


A py2exe like tool for Linux

2006-10-24 Thread Paolo Pantaleo
Hi,

is thre something like py2exe for Linux? I don't need to build a
standalone executable (most Linuxes have python instaled), but at
least I need to provide all the needed libraries togheter with my
source code, so users just need to download one file, and not several
libraries.

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


Re: A py2exe like tool for Linux

2006-10-24 Thread Ben Finney
"Paolo Pantaleo" <[EMAIL PROTECTED]> writes:

> Hi,
>
> is thre something like py2exe for Linux? I don't need to build a
> standalone executable (most Linuxes have python instaled), but at
> least I need to provide all the needed libraries togheter with my
> source code, so users just need to download one file, and not several
> libraries.

Users of GNU/Linux expect, for the most part, to use their package
manager to install software. so you want something that will turn your
package into a package easily installed that way.

Fortunately, 'setuptools' has a 'bdist_rpm' target. (Search for
"Creating System Packages".)

http://peak.telecommunity.com/DevCenter/setuptools>

-- 
 \  "You've got to think about big things while you're doing small |
  `\  things, so that all the small things go in the right |
_o__)direction."  -- Alvin Toffler |
Ben Finney

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


Tutorial on setuptools

2006-10-24 Thread Thomas W
I'm might just be dumb, but I cannot get the hang of usting setuptools
based on the docs at
http://peak.telecommunity.com/DevCenter/setuptools. Is there a simple
example available showing how to pack a few modules, a few scripts,
some resources files ( images ) and list a few dependencies ?

I've searched google and the links I found seemed to be dead or not
about setuptools at all, but as I allready mentioned; I might be
loosing my mind over here so ...

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


Re: A py2exe like tool for Linux

2006-10-24 Thread Bruno Desthuilliers
Paolo Pantaleo wrote:
> Hi,
> 
> is thre something like py2exe for Linux? I don't need to build a
> standalone executable (most Linuxes have python instaled), but at
> least I need to provide all the needed libraries togheter with my
> source code, so users just need to download one file, and not several
> libraries.

Then google for easy_install + "python-eggs".

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


Re: multythreading app memory consumption

2006-10-24 Thread Roman Petrichev
Thank you guys for your replies.
I've just realized that there was no memory leak and it was just my 
mistake to think so. I've almost disappointed with my favorite 
programming language before addressing the problem. Actually the app 
consume as much memory as it should and I've just miscalculated.
Regards
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tutorial on setuptools

2006-10-24 Thread Ben Finney
"Thomas W" <[EMAIL PROTECTED]> writes:

> I'm might just be dumb, but I cannot get the hang of usting
> setuptools based on the docs at
> http://peak.telecommunity.com/DevCenter/setuptools.

Yes, the documentation there is long on verbiage and short on
realistic examples. It is also hard to navigate, being one big page of
mostly-unfamilar concepts.

I suppose it doesn't help that I was never familiar with 'distutils'
before being convinced (in theory) that 'setuptools' was
better. setuptools leverages the existing distutils system and
knowledge -- but conversely, it seems to *depend* on that knowledge.

> Is there a simple example available showing how to pack a few
> modules, a few scripts, some resources files ( images ) and list a
> few dependencies ?

I'm also interested in this.

-- 
 \  "I don't like country music, but I don't mean to denigrate |
  `\  those who do. And for the people who like country music, |
_o__) denigrate means 'put down'."  -- Bob Newhart |
Ben Finney

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


Re: HTML Templates (Sitemesh/Tiles concept) in Python

2006-10-24 Thread metaperl

Suren wrote:


> It seems error prone as well as bad design to scatter this logic in
> each content page. Is there a template logic like Sitemesh or Tiles
> concept that can decorate a desired page just before show time?
>

Suren, you are looking for push-style templating. I list a number of
alternatives here:
http://www.livingcosmos.org/Members/sundevil/software-engineering/push-style-templating-systems/view

I use meld3 personally, but Templess looks pretty good and Webstring
also. Depends on your tastes.

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


Re: A py2exe like tool for Linux

2006-10-24 Thread Sybren Stuvel
Paolo Pantaleo enlightened us with:
> is thre something like py2exe for Linux? I don't need to build a
> standalone executable (most Linuxes have python instaled), but at
> least I need to provide all the needed libraries togheter with my
> source code, so users just need to download one file, and not
> several libraries.

You can use Freeze:
http://lists.fourthought.com/pipermail/4suite/2005-March/007127.html

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


Re: Getting a lot of SPAM from this list

2006-10-24 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
> Larry> Does anyone have a suggestion as to a way that I can get less of
> Larry> this spam?    I'm running spamassassin
> 
> Get a better spam filter?
> 
> Skip
Any suggestions for Firefox?

Colin W.

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


Re: Protecting against SQL injection

2006-10-24 Thread Aahz
In article <[EMAIL PROTECTED]>,
Tor Erik Soenvisen  <[EMAIL PROTECTED]> wrote:
>
>How safe is the following code against SQL injection:
>
># Get user privilege
>digest = sha.new(pw).hexdigest()
># Protect against SQL injection by escaping quotes
>uname = uname.replace("'", "''")
>sql = 'SELECT privilege FROM staff WHERE ' + \
>  'username=\'%s\' AND password=\'%s\'' % (uname, digest)
>res = self.oraDB.query(sql)

Do yourself a favor at least and switch to using double-quotes for the
string.  I also recommend switching to triple-quotes to avoid the
backslash continuation.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you don't know what your program is supposed to do, you'd better not
start writing it."  --Dijkstra
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a lot of SPAM from this list

2006-10-24 Thread skip
>> Get a better spam filter?

Colin> Any suggestions for Firefox?

You can try SpamBayes (http://www.spambayes.org/).  It has both POP3 and
IMAP filters that sit between your mail client and mail server.  You control
and train them via a local web interface.

Skip

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


Re: Network Simulator in Python

2006-10-24 Thread Daniel
Any help ?


Daniel wrote:
> Hi,
>
> I was wondering if anybody can give me pointers on an existing network
> simulator in Python somthing like ns2 which would model all the real
> world internet dynamics including TCP stacks, congestion, flow control
> etc.
> 
> Every help is appreciated,
> 
> Thanks

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


return same type of object

2006-10-24 Thread David Isaac
Instances of MyClass have a method that
returns another instance.  Ignoring the details
of why I might wish to do this, I could
return MyClass()
or
return self.__class__()

I like that latter better.  Should I?
Should I do something else altogether?

Thanks,
Alan Isaac


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


FTP over TLS

2006-10-24 Thread Yogesh Chawla - PD
Hello All,
The state of wisc. wrote a script to do FTP over TLS
using pycurl.  I can post this here, but first need to
yank a bunch of password info out and get some
security clearance.  If someone is interested and
wants to email me offline, please do so at this
address.

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


The format of filename

2006-10-24 Thread Neil Cerutti
Where can I find documentation of what Python accepts as the
filename argument to the builtin function file?

As an example, I'm aware (through osmosis?) that I can use '/' as
a directory separator in filenames on both Unix and Dos. But
where is this documented?

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


Re: return same type of object

2006-10-24 Thread Bruno Desthuilliers
David Isaac wrote:
> Instances of MyClass have a method that
> returns another instance.  

This is usually known as a 'factory method'.

> Ignoring the details
> of why I might wish to do this, I could
> return MyClass()
> or
> return self.__class__()
>
> I like that latter better.  Should I?

You do realise that both solutions are *not* strictky equilavent, do you?

class PsychoRigid(object):
  def create(self):
return PsychoRigid()

class PsychoRigidChild(PsychoRigid):
  pass

pr1 = PsychoRigidChild()
pr2 = pr1.create()
print "pr2 is a ", type(pr2)

class Virtual(object):
  def create(self):
return self.__class__()

class VirtualChild(Virtual):
  pass

vc1 = VirtualChild()
vc2 = vc1.create()
print "vc2 is a ", type(vc2)


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


Re: The format of filename

2006-10-24 Thread Leif K-Brooks
Neil Cerutti wrote:
> Where can I find documentation of what Python accepts as the
> filename argument to the builtin function file?

Python will accept whatever the OS accepts.

> As an example, I'm aware (through osmosis?) that I can use '/' as
> a directory separator in filenames on both Unix and Dos. But
> where is this documented?

It's documented in the OS's documentation. It can be queried with os.sep 
and os.altsep.
-- 
http://mail.python.org/mailman/listinfo/python-list


Visibility against an unknown background

2006-10-24 Thread Odalrick
I need to draw visible lines on pictures with wxPython. That means I
can't simply use, for instance, a black line since it wont be visible
on a black or dark picture.

Painting applications like the GIMP accomplish this by altering the
colour of the line based on the colour of the pixel it covers, but the
only way I can think of doing that is getting each pixel, transforming
the colour then painting it on the screen, which seems like a horribly
inefficient way do it.

I could use alternating colour on the lines, but I don't think that
will be good enough for my taste.

I think I will use a partially transparent bitmap with a hole in the
appropriate place and move the hole as needed.

I realized the last solution as I was writing this and I think it will
work fairly well, but I'm still wondering if there is another, better
solution i might have missed.

/Odalrick

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


Re: The format of filename

2006-10-24 Thread Fredrik Lundh
Neil Cerutti wrote:

> Where can I find documentation of what Python accepts as the
> filename argument to the builtin function file?
> 
> As an example, I'm aware (through osmosis?) that I can use '/' as
> a directory separator in filenames on both Unix and Dos. But
> where is this documented?

in the documentation for your operating system.  Python doesn't do 
anything with the filenames.



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


Re: A py2exe like tool for Linux

2006-10-24 Thread Fredrik Lundh
Paolo Pantaleo wrote:

> is thre something like py2exe for Linux? I don't need to build a
> standalone executable (most Linuxes have python instaled), but at
> least I need to provide all the needed libraries togheter with my
> source code, so users just need to download one file, and not several
> libraries.

"installer" and "cx_freeze" are the two most common alternatives; see 
this page for links:

 http://effbot.org/zone/python-compile.htm

you can also build frozen interpreter binaries; see Tools/freeze/README 
in the source distribution for details.



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


Re: The format of filename

2006-10-24 Thread Neil Cerutti
On 2006-10-24, Leif K-Brooks <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>> As an example, I'm aware (through osmosis?) that I can use '/'
>> as a directory separator in filenames on both Unix and Dos.
>> But where is this documented?
>
> It's documented in the OS's documentation. It can be queried
> with os.sep and os.altsep.

Thanks. The contents of 6.1.6 Miscellanious System Information
seems to be what I'm looking for.

-- 
Neil Cerutti
I've had a wonderful evening, but this wasn't it. --Groucho Marx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The format of filename

2006-10-24 Thread Neil Cerutti
On 2006-10-24, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>
>> Where can I find documentation of what Python accepts as the
>> filename argument to the builtin function file?
>> 
>> As an example, I'm aware (through osmosis?) that I can use '/' as
>> a directory separator in filenames on both Unix and Dos. But
>> where is this documented?
>
> in the documentation for your operating system.  Python doesn't
> do anything with the filenames.

Is translation of '/' to '\\' a feature of Windows or Python?

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


Re: How to upgrade python from 2.4.3 to 2.4.4 ?

2006-10-24 Thread Fredrik Lundh
Tim Roberts wrote:

> Further, as I understand it, Python 2.4 extensions can be built with the
> free "express edition" compiler from Microsoft.

or MinGW.



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


Re: The format of filename

2006-10-24 Thread Leif K-Brooks
Neil Cerutti wrote:
> Is translation of '/' to '\\' a feature of Windows or Python?

It's a feature of Windows, but it isn't a translation. Both slashes are 
valid path separators on Windows; backslashes are just the canonical form.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The format of filename

2006-10-24 Thread Neil Cerutti
On 2006-10-24, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> Is translation of '/' to '\\' a feature of Windows or Python?

Well, *that* was easy to discover on my own. ;-)

Thanks for the pointers.

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


Re: The format of filename

2006-10-24 Thread Fredrik Lundh
Neil Cerutti wrote:

> Is translation of '/' to '\\' a feature of Windows or Python?

Windows.  Random MSDN link:

 http://msdn2.microsoft.com/en-us/library/77859s1t.aspx

 Win32 operating systems support both the backslash (\) and
 the forward slash (/). /.../ (However, the Windows operating
 system command shell, CMD.EXE, does not support the forward
 slash in commands entered at the command prompt.)

for general file naming guidelines for Windows (including the shell), see:

 http://msdn.microsoft.com/library/en-us/fileio/fs/naming_a_file.asp



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


Re: The format of filename

2006-10-24 Thread Tim Chase
>> As an example, I'm aware (through osmosis?) that I can use '/' as
>> a directory separator in filenames on both Unix and Dos. But
>> where is this documented?
> 
> in the documentation for your operating system.  Python doesn't do 
> anything with the filenames.

Windows seems to be (occasionally) doing the translation as /F 
mentions:

C:\temp> python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> for line in file('subdir/test.txt'):
... print line.strip()
...
1
2
3
 >>> ^Z

C:\temp> REM try the same filename convention from dos prompt
C:\temp> type subdir/test.txt
The syntax of the command is incorrect.
C:\temp> REM try with quotes, just in case...
C:\temp> type "subdir/test.txt"
The syntax of the command is incorrect.
C:\temp> notepad subdir/test.txt
C:\temp> REM correctly opened the text file in notepad

Windows seems to doing the translation inconsistently (I know 
that comes as a shock...)

-tkc





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


Re: Visibility against an unknown background

2006-10-24 Thread Paul McGuire
"Odalrick" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I need to draw visible lines on pictures with wxPython. That means I
> can't simply use, for instance, a black line since it wont be visible
> on a black or dark picture.
>
> Painting applications like the GIMP accomplish this by altering the
> colour of the line based on the colour of the pixel it covers, but the
> only way I can think of doing that is getting each pixel, transforming
> the colour then painting it on the screen, which seems like a horribly
> inefficient way do it.
>
> I could use alternating colour on the lines, but I don't think that
> will be good enough for my taste.
>
> I think I will use a partially transparent bitmap with a hole in the
> appropriate place and move the hole as needed.
>
> I realized the last solution as I was writing this and I think it will
> work fairly well, but I'm still wondering if there is another, better
> solution i might have missed.
>
> /Odalrick
>
You could try outlining in a light color.  For example, draw a 3-pixel-wide 
white or light gray line, and then overlay your 1-pixel-wide black line. 
Over light backgrounds, the outline will disappear; over dark backgrounds, 
the outline will look like a hole in the background to show your black line.

-- Paul


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


Re: The format of filename

2006-10-24 Thread Neil Cerutti
On 2006-10-24, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2006-10-24, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> Is translation of '/' to '\\' a feature of Windows or Python?
>
> Well, *that* was easy to discover on my own. ;-)
>
> Thanks for the pointers.

Some experimentation shows that Python does seem to provide
*some* translation. Windows lets me use '/' as a path separator,
but not as the name of the root of a partition name. But perhaps
this a peculiarity of the commands themselves, and not of Windows
path names in particular.

  C:\PYTHON24>CD /
  The syntax of the command is incorrect.
  
  C:\PYTHON24>CD \
  C:\>EDIT /PYTHON24/README
  The syntax of the command is incorrect.

-- 
Neil Cerutti
The outreach committee has enlisted 25 visitors to make calls on
people who are not afflicted with any church. --Church Bulletin
Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forcing a definition to be called on attribute change

2006-10-24 Thread Rob Williscroft
Bruno Desthuilliers wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

>> class cSphere() :
> 
> OT : prefixing classes names with 'c' is totally unpythonic.

My understanding of "pythonic" is that its about how you use the 
language not what style you code in.

Here's a variation of the usual example of pythonic:

use:

  for i in some_list:
pass

not:

  i = 0
  while i < len( some_list ):
i += 1

IOW, pythonic code is code that uses the features of the language
for the purpose they are intended, not code that ignores python's
features and tries to adapt features or idiom's from other languages.

I guess we could claim that one-liners are unpythonic (because 
indentation is a language feature), but claiming a all PEP 8 
violating styles are unpyhonic seems to me to be devaluing the 
term.

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


Re: Default location while open an Excel file

2006-10-24 Thread J. Clifford Dyer
Try this:

 >>> import os
 >>> os.getcwd()
'C:\\Python24'

I ran it from the interpreter.  Dunno what it does from a script in an 
arbitrary location.  YMMV.

Cheers,
Cliff

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


Re: Visibility against an unknown background

2006-10-24 Thread Grant Edwards
On 2006-10-24, Odalrick <[EMAIL PROTECTED]> wrote:

> I need to draw visible lines on pictures with wxPython. That means I
> can't simply use, for instance, a black line since it wont be visible
> on a black or dark picture.
>
> Painting applications like the GIMP accomplish this by altering the
> colour of the line based on the colour of the pixel it covers,

Yup.

> but the only way I can think of doing that is getting each
> pixel, transforming the colour then painting it on the screen,
> which seems like a horribly inefficient way do it.

That's not how it's generally done.  When you draw a line, most
graphics toolkits allow you to specify an "operator" that is
applied to the existing pixel and the line-color to determine
the new pixel color.  The traditional way to draw lines on
something with varying colors is to use the "xor" operator when
drawing the lines.

-- 
Grant Edwards   grante Yow!  Can you MAIL a BEAN
  at   CAKE?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting by item_in_another_list

2006-10-24 Thread Gabriel Genellina

At Tuesday 24/10/2006 04:35, Cameron Walsh wrote:


> c = set(B)
> a.sort(key=c.__contains__, reverse=True)
>
> Tim Delaney

Depressingly simple.  I like it.


...and fast!


--
Gabriel Genellina
Softlab SRL 


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

Re: Visibility against an unknown background

2006-10-24 Thread Grant Edwards
On 2006-10-24, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2006-10-24, Odalrick <[EMAIL PROTECTED]> wrote:
>
>> I need to draw visible lines on pictures with wxPython. That means I
>> can't simply use, for instance, a black line since it wont be visible
>> on a black or dark picture.
>>
>> Painting applications like the GIMP accomplish this by altering the
>> colour of the line based on the colour of the pixel it covers,
>
> Yup.
>
>> but the only way I can think of doing that is getting each
>> pixel, transforming the colour then painting it on the screen,
>> which seems like a horribly inefficient way do it.
>
> That's not how it's generally done.  When you draw a line, most
> graphics toolkits allow you to specify an "operator" that is
> applied to the existing pixel and the line-color to determine
> the new pixel color.  The traditional way to draw lines on
> something with varying colors is to use the "xor" operator when
> drawing the lines.

Oh, another big benefit from using the xor operator is that you
can restore the pixmap to it's original state by simply
repeating the exact same line-draw operation.  That makes it
trivial to do things like rubber-banding.

-- 
Grant Edwards   grante Yow!  I just forgot my
  at   whole philosophy of life!!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Visibility against an unknown background

2006-10-24 Thread Sergei Organov
"Odalrick" <[EMAIL PROTECTED]> writes:

> I need to draw visible lines on pictures with wxPython. That means I
> can't simply use, for instance, a black line since it wont be visible
> on a black or dark picture.
>
> Painting applications like the GIMP accomplish this by altering the
> colour of the line based on the colour of the pixel it covers, but the
> only way I can think of doing that is getting each pixel, transforming
> the colour then painting it on the screen, which seems like a horribly
> inefficient way do it.

There is a better way to do it. Check if the toolkit has line drawing
mode that XORs the line color with the background, then draw using this
mode and white color of the line.

-- Sergei.

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


Re: python GUIs comparison (want)

2006-10-24 Thread Kevin Walzer
[EMAIL PROTECTED] wrote:
> Now i began to learn GUI programming. There are so many
> choices of GUI in the python world, wxPython, pyGTK, PyQT,
> Tkinter, .etc, it's difficult for a novice to decide, however.
> Can you draw a comparison among them on easy coding, pythonish design,
> beautiful and generous looking, powerful development toolkit, and
> sufficient documentation, .etc.
> It's helpful for a GUI beginner.
> Thank you.
> 
> 
> :)Sorry for my poor english.
> 

Tkinter:
Pro: Default GUI library for Python; stable; well-supported
Con: Needs extension for complex/rich GUI's; core widgets are dated in
look and feel; many modern extensions in Tcl/Tk have not made it into
Tkinter or are not widely used (Tile, Tablelist)

wxPython:
Pro: Popular, actively developed, wraps native widgets, looks great on
Windows, commercial-friendly license
Con: Based on C++ toolkit; docs assume knowledge of C++; some think
coding style is too much like C++; complex to build and deploy on Linux
 (wraps Gtk)

PyQt:
Pro: Powerful, cross-platform, sophisticated GUI's
Con: Based on C++ toolkit; docs assume knowledge of C++; commercial
deployment is expensive; free deployment must be GPL; smaller
development and user community than wxPython

PyGtk:
Pro: Sophisticated GUI's, cross-platform (Linux and Win32); very popular
on some platforms; active development community
Con: Not native on OS X





-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting by item_in_another_list

2006-10-24 Thread Carsten Haese
On Tue, 2006-10-24 at 11:31, Gabriel Genellina wrote:
> At Tuesday 24/10/2006 04:35, Cameron Walsh wrote:
> 
> > > c = set(B)
> > > a.sort(key=c.__contains__, reverse=True)
> > >
> > > Tim Delaney
> >
> >Depressingly simple.  I like it.
> 
> ...and fast!

...and not guaranteed to be correct:

http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html states:

"""
Whether the sort() method is stable is not defined by the language (a
sort is stable if it guarantees not to change the relative order of
elements that compare equal). In the C implementation of Python, sorts
were stable only by accident through Python 2.2. The C implementation of
Python 2.3 introduced a stable sort() method, but code that intends to
be portable across implementations and versions must not rely on
stability.
"""

-Carsten


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


Re: Sorting by item_in_another_list

2006-10-24 Thread Carsten Haese
On Tue, 2006-10-24 at 11:41, Carsten Haese wrote:
> On Tue, 2006-10-24 at 11:31, Gabriel Genellina wrote:
> > At Tuesday 24/10/2006 04:35, Cameron Walsh wrote:
> > 
> > > > c = set(B)
> > > > a.sort(key=c.__contains__, reverse=True)
> > > >
> > > > Tim Delaney
> > >
> > >Depressingly simple.  I like it.
> > 
> > ...and fast!
> 
> ...and not guaranteed to be correct:
> 
> http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html states:
> 
> """
> Whether the sort() method is stable is not defined by the language (a
> sort is stable if it guarantees not to change the relative order of
> elements that compare equal). In the C implementation of Python, sorts
> were stable only by accident through Python 2.2. The C implementation of
> Python 2.3 introduced a stable sort() method, but code that intends to
> be portable across implementations and versions must not rely on
> stability.
> """
> 
> -Carsten

And I noticed a bit to late that the search on python.org lead me to an
outdated version of the docs.

The current documentation states that "Starting with Python 2.3, the
sort() method is guaranteed to be stable." However, it's not clear
whether this specifies language behavior that all implementations must
adhere to, or whether it simply documents an implementation detail of
CPython.

-Carsten


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


Re: The format of filename

2006-10-24 Thread Fredrik Lundh
Tim Chase wrote:

> Windows seems to be (occasionally) doing the translation as /F 
> mentions:

as leif pointed out, there's no translation.

> C:\temp> REM try the same filename convention from dos prompt
> C:\temp> type subdir/test.txt
> The syntax of the command is incorrect.
> C:\temp> REM try with quotes, just in case...
> C:\temp> type "subdir/test.txt"
> The syntax of the command is incorrect.

"type" is built into the command shell.  it's the command shell that 
refuses to deal with forward slashes, not the underlying API:s.

> Windows seems to doing the translation inconsistently (I know 
> that comes as a shock...)

it's a documented inconsistency, which is preserved mostly for 
historical reasons (the shell syntax hasn't changed much since
the CP/M days)



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


Re: return same type of object

2006-10-24 Thread Steve Holden
David Isaac wrote:
> Instances of MyClass have a method that
> returns another instance.  Ignoring the details
> of why I might wish to do this, I could
> return MyClass()
> or
> return self.__class__()
> 
> I like that latter better.  Should I?
> Should I do something else altogether?
>  
The latter solution is more Pythonic, IMHO, as it works for subclasses.

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

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


Re: Sorting by item_in_another_list

2006-10-24 Thread Peter Otten
Carsten Haese wrote:

> On Tue, 2006-10-24 at 11:31, Gabriel Genellina wrote:
>> At Tuesday 24/10/2006 04:35, Cameron Walsh wrote:
>> 
>> > > c = set(B)
>> > > a.sort(key=c.__contains__, reverse=True)
>> > >
>> > > Tim Delaney
>> >
>> >Depressingly simple.  I like it.
>> 
>> ...and fast!
> 
> ...and not guaranteed to be correct:
> 
> http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html states:
> 
> """
> Whether the sort() method is stable is not defined by the language (a
> sort is stable if it guarantees not to change the relative order of
> elements that compare equal). In the C implementation of Python, sorts
> were stable only by accident through Python 2.2. The C implementation of
> Python 2.3 introduced a stable sort() method, but code that intends to
> be portable across implementations and versions must not rely on
> stability.
> """

I'd say you need not worry about stability since the key parameter to the
list.sort() method was introduced in Python 2.4...

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


Re: The format of filename

2006-10-24 Thread Steve Holden
Tim Chase wrote:
>>>As an example, I'm aware (through osmosis?) that I can use '/' as
>>>a directory separator in filenames on both Unix and Dos. But
>>>where is this documented?
>>
>>in the documentation for your operating system.  Python doesn't do 
>>anything with the filenames.
> 
> 
> Windows seems to be (occasionally) doing the translation as /F 
> mentions:
> 
> C:\temp> python
> Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit 
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more 
> information.
>  >>> for line in file('subdir/test.txt'):
>   print line.strip()
> 
> 1
> 2
> 3
>  >>> ^Z
> 
> C:\temp> REM try the same filename convention from dos prompt
> C:\temp> type subdir/test.txt
> The syntax of the command is incorrect.
> C:\temp> REM try with quotes, just in case...
> C:\temp> type "subdir/test.txt"
> The syntax of the command is incorrect.
> C:\temp> notepad subdir/test.txt
> C:\temp> REM correctly opened the text file in notepad
> 
> Windows seems to doing the translation inconsistently (I know 
> that comes as a shock...)
> 
The command line processor parses the slash as a switch delimiter, but 
the system call interface doesn't know about such refinements and treats 
forward and backward slashes as filename component separators.

Just the same it's always cleanest to use os.path routines (or similar) 
to analyze and construct filenames.

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

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


Re: Visibility against an unknown background

2006-10-24 Thread Fredrik Lundh
Sergei Organov wrote:

> There is a better way to do it. Check if the toolkit has line drawing
> mode that XORs the line color with the background, then draw using this
> mode and white color of the line.

which means that the selection looks like crap most of the time, and 
doesn't work at all on medium gray or b/w dithered patterns.

for most cases, "marching ants" is a much better approach (usually done 
by drawing alternating stippled patterns).  see e.g.

 http://en.wikipedia.org/wiki/Marching_ants

for some background.



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


[ANN] argparse 0.2 - Command-line parsing library

2006-10-24 Thread Steven Bethard
Announcing argparse 0.2
---

argparse home:
 http://argparse.python-hosting.com/

argparse single module download:
 http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw

argparse bundled downloads at PyPI:
 http://www.python.org/pypi/argparse/


About this release
==

This release fixes a few minor bugs, modifies the 'store_true' and
'store_false' actions to have more natural defaults, and adds an
epilog= keyword argument to ArgumentParser for text to be printed
after the help messages. (The latter is in line with the `updates to
optparse`_ for Python 2.5.)

.. _updates to optparse: http://www.python.org/doc/2.5/whatsnew/modules.html

New in this release
===

* The 'store_true' action's default is now False (instead of None).
* The 'store_false' action's default is now True (instead of None).
* ArgumentParser objects now accept an epilog= keyword argument.


About argparse
==

The argparse module is an optparse-inspired command line parser that
improves on optparse by:

* handling both optional and positional arguments
* supporting parsers that dispatch to sub-parsers
* producing more informative usage messages
* supporting actions that consume any number of command-line args
* allowing types and actions to be specified with simple callables
instead of hacking class attributes like STORE_ACTIONS or
CHECK_METHODS

as well as including a number of other more minor improvements on the
optparse API. To whet your appetite, here's a simple program that sums
its command-line arguments and writes them to a file::

   parser = argparse.ArgumentParser()
   parser.add_argument('integers', type=int, nargs='+')
   parser.add_argument('--log', type='outfile', default=sys.stdout)
   args = parser.parse_args()
   args.log.write('%s\n' % sum(args.integers))
   args.log.close()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python GUIs comparison (want)

2006-10-24 Thread Christophe
Kevin Walzer a écrit :
> [EMAIL PROTECTED] wrote:
>> Now i began to learn GUI programming. There are so many
>> choices of GUI in the python world, wxPython, pyGTK, PyQT,
>> Tkinter, .etc, it's difficult for a novice to decide, however.
>> Can you draw a comparison among them on easy coding, pythonish design,
>> beautiful and generous looking, powerful development toolkit, and
>> sufficient documentation, .etc.
>> It's helpful for a GUI beginner.
>> Thank you.
>>
>>
>> :)Sorry for my poor english.
>>
> 
> Tkinter:
> Pro: Default GUI library for Python; stable; well-supported
> Con: Needs extension for complex/rich GUI's; core widgets are dated in
> look and feel; many modern extensions in Tcl/Tk have not made it into
> Tkinter or are not widely used (Tile, Tablelist)
Also, the Tkinter API is far less elegant than the others.

> wxPython:
> Pro: Popular, actively developed, wraps native widgets, looks great on
> Windows, commercial-friendly license
> Con: Based on C++ toolkit; docs assume knowledge of C++; some think
> coding style is too much like C++; complex to build and deploy on Linux
>  (wraps Gtk)
See PyQt remarks. And I would add that the coding style is too much like 
MFC and Win32 as a con.

> PyQt:
> Pro: Powerful, cross-platform, sophisticated GUI's
> Con: Based on C++ toolkit; docs assume knowledge of C++; commercial
> deployment is expensive; free deployment must be GPL; smaller
> development and user community than wxPython
Since when is "based on C++ toolkit" a con?

> PyGtk:
> Pro: Sophisticated GUI's, cross-platform (Linux and Win32); very popular
> on some platforms; active development community
> Con: Not native on OS X

You forgot that it is rather buggy on Win32 ( in my experience )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using mmap on large (> 2 Gig) files

2006-10-24 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "sturlamolden" <[EMAIL PROTECTED]> wrote:
...
> It seems that Python does take a length argument, but not an offset
> argument (unlike the Windows' CreateFileMapping/MapViewOfFile and UNIX'
> mmap), so you always map from the beginning of the file. Of course if
> you have ever worked with memory mapping files in C, you will probably
> have experienced that mapping a large file from beginning to end is a
> major slowdown.

I certainly have not experienced that.  mmap itself takes nearly
no time, there should be no I/O.  Access to mapped pages may
require I/O, but there is no way around that in any case.

> I haven't looked at the source, but I'd be surprised if Python actually
> maps the file into the process image when mmap is called. I believe
> Python is not memory mapping at all; rather, it just opens a file in
> the file system and uses fseek to move around.

Wow, you're sure a wizard!  Most people would need to look before
making statements like that.

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


Re: python GUIs comparison (want)

2006-10-24 Thread Kevin Walzer
Christophe wrote:

> Since when is "based on C++ toolkit" a con?
> 

If you don't know C++ (as is the case with me), then it's difficult to
do a C++-to-Python translation in looking at code examples.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't open word document after string replacements

2006-10-24 Thread Frederic Rentsch
Antoine De Groote wrote:
> Hi there,
>
> I have a word document containing pictures and text. This documents 
> holds several 'ABCDEF' strings which serve as a placeholder for names. 
> Now I want to replace these occurences with names in a list (members). I 
> open both input and output file in binary mode and do the 
> transformation. However, I can't open the resulting file, Word just 
> telling that there was an error. Does anybody what I am doing wrong?
>
> Oh, and is this approach pythonic anyway? (I have a strong Java background.)
>
> Regards,
> antoine
>
>
> import os
>
> members = somelist
>
> os.chdir(somefolder)
>
> doc = file('ttt.doc', 'rb')
> docout = file('ttt1.doc', 'wb')
>
> counter = 0
>
> for line in doc:
>  while line.find('ABCDEF') > -1:
>  try:
>  line = line.replace('ABCDEF', members[counter], 1)
>  docout.write(line)
>  counter += 1
>  except:
>  docout.write(line.replace('ABCDEF', '', 1))
>  else:
>  docout.write(line)
>
> doc.close()
> docout.close()
>
>   
DOC files contain housekeeping info which becomes inconsistent if you 
change text. Possibly you can exchange stuff of equal length but that 
wouldn't serve your purpose. RTF files let you do substitutions and they 
save a lot of space too. But I kind of doubt whether RTF files can 
contain pictures.

Frederic



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


RE: Talks at PyCon that Teach How to Be Better Programmers

2006-10-24 Thread Robert Brewer
Jeff Rush wrote:
> ...we need more talks that actually teach you how
> to be better programmers...What the Heck Does
> "Pythonic Programming Style" Mean Anyway?

I'm finishing an outline for a talk which will overlap this one a bit,
but under the topic "What makes a great API?" that will be directed more
at library authors than users:


I. Zero learning required
=

"""Civilization advances by extending the number of important operations
which we can perform without thinking about them."""
-- Alfred North Whitehead, Introduction to Mathematics (1911)
http://www.quotationspage.com/quote/30283.html

"""To be Pythonic is to avoid surprising experienced Python programmers
with unfamiliar ways to accomplish a task."""
-- Martijn Faassen
http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0

1. Use native types, functions and idioms.
a. Bare functions are better than class collections
b. getters and setters considered harmful
2. Inventing new types: use Python idioms instead of inventing your own
a. conform to Python API's
b. subclass builtins rather than delegating
c. judicious use of descriptors
3. DSLs suck
4. "Imagine your dream code and figure out how to make it happen"

But when you need to learn/remember something, the API must be...

II. Inspectable
===

1. If help() is to be helpful, you must reduce [len(dir(obj)) for obj in
all_obj].
2. Dynamic languages naturally more lang-maven oriented?
   See http://osteele.com/archives/2004/11/ides

III. Programmable
=

1. Config and other "declarative" modes: No "XML sit-ups"

IV. Readable = Simple
=

1. Parameterization and customization


Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting by item_in_another_list

2006-10-24 Thread bearophileHUGS
Carsten Haese:
> However, it's not clear
> whether this specifies language behavior that all implementations must
> adhere to, or whether it simply documents an implementation detail of
> CPython.

I think it's CPython-specific, but maybe here people expert in Jython
and IronPython can tell if their sort is stable.

Bye,
bearophile

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


Re: python GUIs comparison (want)

2006-10-24 Thread Christophe
Kevin Walzer a écrit :
> Christophe wrote:
> 
>> Since when is "based on C++ toolkit" a con?
>>
> 
> If you don't know C++ (as is the case with me), then it's difficult to
> do a C++-to-Python translation in looking at code examples.

As if a toolkit based on C would be much easier.

In fact, I would even say that C++ -> Python is much much easier than C 
-> Python for GUI toolkits.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Handling emails

2006-10-24 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Tuesday 24 October 2006 01:12, Dennis Lee Bieber wrote:
> Message-id:
> <[EMAIL PROTECTED]>
>
> as the ID is generally created when the message is submitted to the
> delivery system

Well, that's what I'm dealing with, since a couple of weeks :-) indeed.
Some might not have one, but Kmail should had fixed.
The second will be the way to get the whole email from the mbox file. My 
problem still remain, partially. I'm not sure if the below procedure will 
give me the emails off including multipart ones.

8<-8<-8<-8<-8<-
#! /usr/bin/env python

from __future__ import generators

import email, re
import mailbox
import email.Message

def getmbox(name):
"""Return an mbox iterator given a file/directory/folder name."""
fp = open(name, "rb")
mbox = mailbox.PortableUnixMailbox(fp, get_message)
return iter(mbox)

def get_message(obj):
"""Return an email Message object."""

if isinstance(obj, email.Message.Message):
return obj
# Create an email Message object.
if hasattr(obj, "read"):
obj = obj.read()
try:
msg = email.message_from_string(obj)
except email.Errors.MessageParseError:

obj = obj[len(headers):]
msg = email.Message.Message()
return msg

header_break_re = re.compile(r"\r?\n(\r?\n)")

def extract_headers(text):
"""Very simple-minded header extraction"""

m = header_break_re.search(text)
if m:
eol = m.start(1)
text = text[:eol]
if ':' not in text:
text = ""
return text

if __name__ == '__main__':
#simple trial with local mbox file
import sys
try:
file =sys.argv[1]
except IOError:
print 'Must give a mbox file program /path/to_mbox'
sys.exit()
k = getmbox(file)
while 1:
full_email = get_message(k.next())
print '%78s' %full_email
answer= raw_input('More? Y/N')
if answer.lower() == 'n': break

8<-8<-8<-8<-8<-
I admit that not all code is my genuine design, ;-) some other programs 
extrapolating have been done.

F


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


Re: Handling emails

2006-10-24 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Tuesday 24 October 2006 03:07, Gerard Flanagan wrote:
> The 'PopClient' class here might help you:
Thank you, both for the replies.
Gerard,
Surely I'll peep on that code ;-) to gather a wider perspective. A small 
negative point is that for pop deals I've gotten a good success :-) But I 
don't give up, perhaps it there'll be some good idea.
I'm more interested for the IMAP side of the issue, even I might avoid for my 
own purposes.

Last, suppose to publish the "thing" where will it be the appropriate site?
At the present my program can do filtering and sincronizing with local MUA 
trash. Small problems with IMAP protocol, but it may work for POP3 or  IMAP4 
on regex filter options. Alfa testers (cooperators) needed ;-)

F


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


  1   2   3   >