Jinja 1.0 Released

2007-03-24 Thread Armin Ronacher
Jinja 1.0 Released
==

Jinja 1.0 is out now. Jinja is a sandboxed  template engine written in
pure Python
licensed under the BSD license. It provides a Django-like non-XML
syntax and
compiles templates into executable python code. It's basically a
combination
of Django templates and python code.

Differences to Django
-

While the Jinja default syntax looks pretty much like Django the rest
of the
template engine works completely different. Jinja was designed to be
used
without Django and to support Python expressions.

Features that Jinja has in common with Django:

* filter functions
* block based template inheritance
* the {% cycle %} and {% filter %} tag
* being sandboxed
* similar default syntax

Differences:

* advanced lexer that allows escaping of tags
* generation of bytecode for faster template execution
* definition of macros (often recurring tasks like rendering
dialog
  boxes, form elements etc.)
* raw blocks
* uncoupled internationalization support
* expression support in any tag
* abbility of modifying the context from the template by using the
  {% set %} tag.
* support for function calling with arguments
* filters can be called with a variable argument count
* full unicode support
* deferred objects (objects that are resolved on first access, not
on
  context instanciation)
* Missing support for {{ block.super }}
* Support for recursing by using recursing for loops or self
calling
  macros.
* If blocks have support for multiple elif statements
* for loops have an optional else block executed if there was no
  iteration.
* test functions like is even etc.
* block delimiters are exchangeable.
* no implicit function calling
* {% endblock %} doesn't support the optional name argument
* {% ifchanged %} is not implemented because of performance
reasons.
  If there's enough interest an implementation might be added
* {% templatetag %} is not implemented because Jinja supports
escaping
  via {% raw %} or the variable syntax
* {% comment %} is not implemented, rather use for commenting out
stuff.
* {% now %} is not implemented because Jinja doesn't handle l10n.
  Datetime specific stuff should be provided by the application.
* {% load %}, loading components for Jinja works from the
application
  side. Template designers don't have to import stuff on their
own.
* {% debug %} is not implemented. You can use the global function
debug().
* custom tags are not supported. Most of the stuff that is
possible with
  django template tags is possible with either functions, filters,
tests
  or a combination of them.
* using keywords like endfor as identifer raises an exception.

Links
-

* Webpage - http://jinja.pocoo.org/
* Downloads - http://jinja.pocoo.org/download.html
* Documentation - http://jinja.pocoo.org/documentation/

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Multi-line strings with formatting

2007-03-24 Thread Steven Bethard
On Fri, 2007-03-23 at 09:54 -0700, [EMAIL PROTECTED] wrote:
  When constructing a particularly long and complicated command to be
  sent to the shell, I usually do something like this, to make the
  command as easy as possible to follow:
  commands.getoutput(
  'mycommand -S %d -T %d ' % (s_switch, t_switch)   +
  '-f1 %s -f2 %s ' % (filename1, filename2) +
  ' %s'   % (log_filename)
  )
  Can anyone suggest a better way to construct the command, especially
  without the + sign at the end of each line (except the last) ?

Paul McGuire wrote:
 This list might be even simpler to follow:
 
 l = [
  'mycommand',
  '-S', s_switch,
  '-T', t_switch,
  '-f1', filename1,
  '-f2', filename2,
  '', log_filename
 ]
 cmd =  .join(l)

And if you use the subprocess module, you won't even need (or want) the 
final join.

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


Re: On text processing

2007-03-24 Thread Daniel Nogradi
  I'm in a process of rewriting a bash/awk/sed script -- that grew to
  big -- in python. I can rewrite it in a simple line-by-line way but
  that results in ugly python code and I'm sure there is a simple
  pythonic way.
 
  The bash script processed text files of the form:
 
  ###
  key1value1
  key2value2
  key3value3
 
  key4value4
  spec11  spec12   spec13   spec14
  spec21  spec22   spec23   spec24
  spec31  spec32   spec33   spec34
 
  key5value5
  key6value6
 
  key7value7
  more11   more12   more13
  more21   more22   more23
 
  key8value8
  ###
 
  I guess you get the point. If a line has two entries it is a key/value
  pair which should end up in a dictionary. If a key/value pair is
  followed by consequtive lines with more then two entries, it is a
  matrix that should end up in a list of lists (matrix) that can be
  identified by the key preceeding it. The empty line after the last
  line of a matrix signifies that the matrix is finished and we are back
  to a key/value situation. Note that a matrix is always preceeded by a
  key/value pair so that it can really be identified by the key.
 
  Any elegant solution for this?


 My solution expects correctly formatted input and parses it into
 separate key/value and matrix holding dicts:


 from StringIO import StringIO

 fileText = '''\
  key1value1
 key2value2
 key3value3

 key4value4
 spec11  spec12   spec13   spec14
 spec21  spec22   spec23   spec24
 spec31  spec32   spec33   spec34

 key5value5
 key6value6

 key7value7
 more11   more12   more13
 more21   more22   more23

 key8value8
 '''
 infile = StringIO(fileText)

 keyvalues = {}
 matrices  = {}
 for line in infile:
 fields = line.strip().split()
 if len(fields) == 2:
 keyvalues[fields[0]] = fields[1]
 lastkey = fields[0]
 elif fields:
 matrices.setdefault(lastkey, []).append(fields)

 ==
 Here is the sample output:

  from pprint import pprint as pp
  pp(keyvalues)
 {'key1': 'value1',
  'key2': 'value2',
  'key3': 'value3',
  'key4': 'value4',
  'key5': 'value5',
  'key6': 'value6',
  'key7': 'value7',
  'key8': 'value8'}
  pp(matrices)
 {'key4': [['spec11', 'spec12', 'spec13', 'spec14'],
   ['spec21', 'spec22', 'spec23', 'spec24'],
   ['spec31', 'spec32', 'spec33', 'spec34']],
  'key7': [['more11', 'more12', 'more13'], ['more21', 'more22',
 'more23']]}
 

Paddy, thanks, this looks even better.
Paul, pyparsing looks like an overkill, even the config parser module
is something that is too complex for me for such a simple task. The
text files are actually input files to a program and will never be
longer than 20-30 lines so Paddy's solution is perfectly fine. In any
case it's good to know that there exists a module called pyparsing :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python object overhead?

2007-03-24 Thread John Machin
On 24/03/2007 8:11 AM, Matt Garman wrote:
 I'm trying to use Python to work with large pipe ('|') delimited data
 files.  The files range in size from 25 MB to 200 MB.
 
 Since each line corresponds to a record, what I'm trying to do is
 create an object from each record.

An object with only 1 attribute and no useful methods seems a little 
pointless; I presume you will elaborate it later.

  However, it seems that doing this
 causes the memory overhead to go up two or three times.
 
 See the two examples below: running each on the same input file
 results in 3x the memory usage for Example 2.  (Memory usage is
 checked using top.)
 
 This happens for both Python 2.4.3 on Gentoo Linux (64bit) and Python
 2.3.4 on CentOS 4.4 (64bit).
 
 Is this just the way it is or am I overlooking something obvious?
 
 Thanks,
 Matt
 
 
 Example 1: read lines into list:
 # begin readlines.py

Interesting name for the file :-)
How about using the file.readlines() method?
Why do you want all 200Mb in memory at once anyway?

 import sys, time
 filedata = list()
 file = open(sys.argv[1])

You have just clobbered the builtin file() function/type. In this case 
it doesn't matter, but you should lose the habit, quickly.

 while True:
line = file.readline()
if len(line) == 0: break # EOF
filedata.append(line)
 file.close()
 print data read; sleeping 20 seconds...
 time.sleep(20) # gives time to check top

How about using raw_input('Hit the Any key...') ?

 # end readlines.py
 
 
 Example 2: read lines into objects:
 # begin readobjects.py
 import sys, time
 class FileRecord:
def __init__(self, line):
self.line = line
 records = list()
 file = open(sys.argv[1])
 while True:
line = file.readline()
if len(line) == 0: break # EOF
rec = FileRecord(line)
records.append(rec)
 file.close()
 print data read; sleeping 20 seconds...
 time.sleep(20) # gives time to check top
 # end readobjects.py

After all that, you still need to split the lines into the more-than-one 
fieldS (plural) that one would expect in a record.

A possibly faster alternative to (fastest_line_reader_so_far, 
(line.split('|')) is to use the csv module, as in the following example, 
which also shows one way of making an object out of a row of data.

C:\junktype readpipe.py
import sys, csv

class Contacts(object):
 __slots__ = ['first', 'family', 'email']
 def __init__(self, row):
 for attrname, value in zip(self.__slots__, row):
 setattr(self, attrname, value)

def readpipe(fname):
 if hasattr(fname, 'read'):
 f = fname
 else:
 f = open(fname, 'rb')
 # 'b' is in case you'd like your script to be portable
 reader = csv.reader(
 f,
 delimiter='|',
 quoting=csv.QUOTE_NONE,
 # Set quotechar to a char that you don't expect in your data
 # e.g. the ASCII control char BEL (0x07). This is necessary
 # for Python 2.3, whose csv module used the quoting arg only when
 # writing, otherwise your  characters may get stripped off.
 quotechar='\x07',
 skipinitialspace=True,
 )
 for row in reader:
 if row == ['']: # blank line
 continue
 c = Contacts(row)
 # do something useful with c, e.g.
 print [(x, getattr(c, x)) for x in dir(c)
 if not x.startswith('_')]

if __name__ == '__main__':
 if sys.argv[1:2]:
 readpipe(sys.argv[1])
 else:
 print '*** Testing ***'
 import cStringIO
 readpipe(cStringIO.StringIO('''\
 Biff|Bloggs|[EMAIL PROTECTED]
 Joseph (Joe)|Blow|[EMAIL PROTECTED]
 Joe|Blow|[EMAIL PROTECTED]

 Santa|Claus|[EMAIL PROTECTED]
 '''))

C:\junk\python23\python readpipe.py
*** Testing ***
[('email', '[EMAIL PROTECTED]'), ('family', 'Bloggs'), ('first', 'Biff')]
[('email', '[EMAIL PROTECTED]'), ('family', 'Blow'), ('first', 'Joseph 
(Joe)')]
[('email', '[EMAIL PROTECTED]'), ('family', 'Blow'), ('first', 'Joe')]
[('email', '[EMAIL PROTECTED]'), ('family', 'Claus'), ('first', 'Santa')]

C:\junk\python25\python readpipe.py
*** Testing ***
[('email', '[EMAIL PROTECTED]'), ('family', 'Bloggs'), ('first', 'Biff')]
[('email', '[EMAIL PROTECTED]'), ('family', 'Blow'), ('first', 'Joseph 
(Joe)')]
[('email', '[EMAIL PROTECTED]'), ('family', 'Blow'), ('first', 'Joe')]
[('email', '[EMAIL PROTECTED]'), ('family', 'Claus'), ('first', 'Santa')]

C:\junk

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


Re: Making a non-root daemon process

2007-03-24 Thread Ben Finney
Ben Finney [EMAIL PROTECTED] writes:

 Hmm. I typed the example program in as a simplified version of what
 I'm doing; but didn't actually *run* it. When I do run it, I get no
 exception, as you say.

 Now I'll have to find out what significant difference there is
 between my failing code and this example, and report back in this
 thread.

It turns out that, in re-typing the algorithm in the newsgroup
message, I got all the branches correct; but in the code that wasn't
working, I had reversed one of them :-)

All fine now. We return you to your regularly scheduled programming.

-- 
 \   My aunt gave me a walkie-talkie for my birthday. She says if |
  `\ I'm good, she'll give me the other one next year.  -- Steven |
_o__)   Wright |
Ben Finney

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


execution speed increase after compile py code into exe?

2007-03-24 Thread Kelie
hello,

would there be any speed increase in code execution after python code being
compiled into exe file with py2exe?

thanks,

kelie

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


Re: execution speed increase after compile py code into exe?

2007-03-24 Thread Michael Bentley

 would there be any speed increase in code execution after python  
 code being
 compiled into exe file with py2exe?


No.  I would expect slower startup followed by the same code  
execution time you'd get from running normally (not that I've  
actually tested it, mind you).

regards,
Michael

---
Our network was brought down by a biscuit??? --Steven D'Aprano



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


Re: execution speed increase after compile py code into exe?

2007-03-24 Thread Paul Rudin
Kelie [EMAIL PROTECTED] writes:

 hello,

 would there be any speed increase in code execution after python code being
 compiled into exe file with py2exe?

AIUI that's not what p2yexe is about - it's essentially about
packaging up your python program for ease of distribution and
installation on windows boxes.

However, you might find that you can get significant speed-ups by
using psyco http://psyco.sourceforge.net/, on x386 type hardware at
least.


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


Re: execution speed increase after compile py code into exe?

2007-03-24 Thread Will McGugan
Michael Bentley wrote:

 would there be any speed increase in code execution after python  code 
 being
 compiled into exe file with py2exe?

 
 No.  I would expect slower startup followed by the same code  execution 
 time you'd get from running normally (not that I've  actually tested it, 
 mind you).

Actualy startup is faster for the apps that I have py2exe'd. I think 
this may be because all the modules are in one place and Python doesn't 
have to go searching for them.

Will
--
http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating jsp-like tool with python

2007-03-24 Thread Kushal Kumaran
On Mar 24, 6:18 am, jd [EMAIL PROTECTED] wrote:
 I'd like to create a program that takes files with jsp-like markup
 and processes the embedded code (which would be python) to produce the
 output file.  There would be two kinds of sections in the markup file:
 python code to be evaluated, and python code that returns a value that
 would be inserted into the output.

 This seems like it would be straightforward in python, and maybe
 there's even a library that I could use for this, but as a newbie to
 Python, I don't know the landscape very well.  I am not looking for a
 big framework, just something small and simple that will do just this
 job.  Suggestions or pointers would be greatly appreciated.


Apache's mod_python already does something like this, with its PSP
handler.  See http://webpython.codepoint.net/mod_python

Maybe that would help.

--
Kushal Kumaran

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


Re: execution speed increase after compile py code into exe?

2007-03-24 Thread Michael Bentley

 Actualy startup is faster for the apps that I have py2exe'd. I think
 this may be because all the modules are in one place and Python  
 doesn't
 have to go searching for them.

Thanks, Will!  That's good to know.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Join strings - very simple Q.

2007-03-24 Thread Dustan
On Mar 23, 1:30 pm, Paulo da Silva [EMAIL PROTECTED] wrote:
 Mike Kent escreveu:
 ...

  New way:
  l=['a','b','c']
  jl=','.join(l)

 I thank you all.

 Almost there ...
 I tried .join(l,',') but no success ... :-(

 Paulo

Perhaps you're doing it wrong, despite having an example right in
front of you?

Side by side comparison:
jl=string.join(l,',')
jl=','.join(l)

The sequence is passed as an argument to the join method, and the
delimiter is the string whose method is being called.

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


Re: Create new processes over telnet in XP

2007-03-24 Thread Thomas Heller
Irmen de Jong schrieb:
 Shane Geiger wrote:
 This reminds me of something I once wanted to do:  How can I install 
 Python in a totally non-gui way on Windows (without the use of VNC)?  I 
 think I was telnetted into a computer (or something like that) and I was 
 unable to run the usual Python installer because it uses a GUI.
 
 Python uses a MSI (microsoft installer) based installer on windows.
 This was introduced in version 2.5 I believe.
 
 For MSI installers there's the standard MSI-way to perform a silent install.
 Google for it, I don't know what the command line switch(es) are, but they're 
 there.
 
 --Irmen
 
Even the Wise installer that was used to build the 2.3 and earlier versions
had command line switches to do silent installs.

THomas

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


Re: Join strings - very simple Q.

2007-03-24 Thread Dustan
On Mar 24, 5:59 am, Dustan [EMAIL PROTECTED] wrote:
 On Mar 23, 1:30 pm, Paulo da Silva [EMAIL PROTECTED] wrote:

  Mike Kent escreveu:
  ...

   New way:
   l=['a','b','c']
   jl=','.join(l)

  I thank you all.

  Almost there ...
  I tried .join(l,',') but no success ... :-(

  Paulo

 Perhaps you're doing it wrong, despite having an example right in
 front of you?

 Side by side comparison:
 jl=string.join(l,',')
 jl=','.join(l)

 The sequence is passed as an argument to the join method, and the
 delimiter is the string whose method is being called.

To further demonstrate (because I got a weird email that seemed to
think that my code didn't work):

 import string
 l = ['a','b','c']
 string.join(l,',')
'a,b,c'
 ','.join(l)
'a,b,c'

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


Re: Join strings - very simple Q.

2007-03-24 Thread Shane Geiger

import string

def test_join(l):
   print Joining with commas: ,  string.join(l,',')
   print Joining with empty string:   ,  string.join(l,'')
   print Joining same way, using another syntax:  ,  ''.join(l)
   print Joining with the letter X:   ,  'X'.join(l)
   print Joining with - ,  '-'.join(l)

l = ['a','b','c']

test_join(l)



Example output:

Joining with commas:  a,b,c
Joining with empty string:abc
Joining same way, using another syntax:   abc
Joining with the letter X:aXbXc
Joining with -  a-b-c








Dustan wrote:

On Mar 24, 5:59 am, Dustan [EMAIL PROTECTED] wrote:
  

On Mar 23, 1:30 pm, Paulo da Silva [EMAIL PROTECTED] wrote:



Mike Kent escreveu:
...
  

New way:
l=['a','b','c']
jl=','.join(l)


I thank you all.
  
Almost there ...

I tried .join(l,',') but no success ... :-(
  
Paulo
  

Perhaps you're doing it wrong, despite having an example right in
front of you?

Side by side comparison:
jl=string.join(l,',')
jl=','.join(l)

The sequence is passed as an argument to the join method, and the
delimiter is the string whose method is being called.



To further demonstrate (because I got a weird email that seemed to
think that my code didn't work):

  

import string
l = ['a','b','c']
string.join(l,',')


'a,b,c'
  

','.join(l)


'a,b,c'

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: Create new processes over telnet in XP

2007-03-24 Thread Rob Wolfe
Godzilla [EMAIL PROTECTED] writes:

 Rob, I would be logging into another XP machine to do some software

I was afraid of that. :)

 installation... the code you provided, correct me if I'm wrong, seems
 to work under Unix/Linux. 

This part of running and killing processes, yes.

 Any idea how to do the equivalent in XP?

You could use windows services, for example:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/115875

But I don't know details, because this is not my favourite OS. :)

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


draw like windows performance Graph

2007-03-24 Thread momobear
Type the taskmgr,  Windows performance Graph give a really nice
dynamic history curve, It will be wonderful If I could use the same
kind of graph to represent the network flow in my python program.  Is
there a windows api for this  graph drawing?

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


Re: Join strings - very simple Q.

2007-03-24 Thread Duncan Booth
Dustan [EMAIL PROTECTED] wrote:
 Perhaps you're doing it wrong, despite having an example right in
 front of you?
 
 Side by side comparison:
 jl=string.join(l,',')
 jl=','.join(l)
 
 The sequence is passed as an argument to the join method, and the
 delimiter is the string whose method is being called.
 

In case you are feeling that the ','.join(l) looks a bit jarring, be aware 
that there are alternative ways to write it. You can call the method on the 
class rather than the instance:

   jl = str.join(',', l)
   jl = unicode.join(u'\u00d7', 'l')

has the advantage of looking almost the same as the string function except 
that the order of the arguments is reversed, the catch is you need to know 
the type of the separator in advance. If you have a lot of calls with the 
same separator then you can also save the method in an appropriately named 
variable:

   commaseparated = ','.join
   ...
   jl = commaseparated(l)

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


Re: creating jsp-like tool with python

2007-03-24 Thread irstas

jd wrote:
 I'd like to create a program that takes files with jsp-like markup
 and processes the embedded code (which would be python) to produce the
 output file.  There would be two kinds of sections in the markup file:
 python code to be evaluated, and python code that returns a value that
 would be inserted into the output.

 This seems like it would be straightforward in python, and maybe
 there's even a library that I could use for this, but as a newbie to
 Python, I don't know the landscape very well.  I am not looking for a
 big framework, just something small and simple that will do just this
 job.  Suggestions or pointers would be greatly appreciated.

 Thanks...

 -- jeff

Sadly, there's probably as many template languages as there are web
frameworks for Python.
Maybe even more. For example:

http://www.djangoproject.com/documentation/templates/
http://nick.borko.org/pse/index.html
http://www.turbogears.org/about/kid.html

Pick your poison.

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


Re: Join strings - very simple Q.

2007-03-24 Thread Paulo da Silva
John Machin escreveu:
..

 Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on
 win32
 Type help, copyright, credits or license for more information.
 |  help(.join)
 Help on built-in function join:
 
 join(...)
 S.join(sequence) - string
 
 Return a string which is the concatenation of the strings in the
 sequence.  The separator between elements is S.
 
 | 
 
 OK, I'll bite: This was new in late 2000 when Python 2.0 was
 released. Where have you been in the last ~6.5 years?

In a response to one of my posts I was told 'string' is
obsolet. 'string' was enough for me, but if it is obsolet
then there should be a *new* way, isn't it? The *new*
way I was told to use is str methods.
I tried that *new* way to do *old* 'string' job. Voila
the reason of my so pertinent question.

I am deeply sorry to have disturbed you in your python's heaven.

Next time I'll read all books available, all texts including
the python formal description before
posting, or perhaps it would be better and more simple if you
just ignore my posts.

Bye.
Paulo

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


Re: Join strings - very simple Q.

2007-03-24 Thread Paulo da Silva
Dustan escreveu:
 On Mar 23, 1:30 pm, Paulo da Silva [EMAIL PROTECTED] wrote:
 Mike Kent escreveu:
 ...

 New way:
 l=['a','b','c']
 jl=','.join(l)
 I thank you all.

 Almost there ...
 I tried .join(l,',') but no success ... :-(

 Paulo
 
 Perhaps you're doing it wrong, despite having an example right in
 front of you?

Some misunderstanding here ...
The post was just to thank. I was refering to what I tried
before posting the question here.

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


Re: Idiom for running compiled python scripts?

2007-03-24 Thread irstas
On Mar 23, 9:30 am, Mark [EMAIL PROTECTED] wrote:
 A small script called python_compile_and_run in pseudo code:

 #!/usr/bin/env python
 import sys

 # Following is invalid syntax unfortunately :(
 from sys.argv[1].rstrip('.py') import main

 sys.argv = sys.argv[1:]
 if __name__ == __main__:
 main()

 so I could just do a python_compile_and_run myscript.py and it would
 do what I want, i.e. run myscript.pyc if available and valid, generate
 and run it if necessary.

There's __import__ which allows you to do what you tried:

m = __import__(sys.argv[1].rstrip('.py'))

Also, rstrip doesn't work like you think it does.
'pyxyypp.py'.rstrip('.py') == 'pyx'

Answering also to your later message:

 So the general purpose invoking bash script e.g. runpy is merely something
like:

Curiously enough, Python 2.5 has a module called runpy:
http://docs.python.org/lib/module-runpy.html

which seems to almost do what you want. It doesn't compile the modules
but you could make a modification which does. The benefit over just
using __import__(module).main() would be
that your scripts wouldn't necessarily need a function called main,
but would still work with scripts that use the __name__ == '__main__'
idiom.
A simple implementation that works:


import imp, sys, os
c = sys.argv[1]
if not os.path.exists(c + 'c') or os.stat(c).st_mtime  os.stat(c +
'c').st_mtime:
import compiler
compiler.compileFile(c)
del sys.argv[0]
imp.load_compiled('__main__', c + 'c')


I timed it against running plain .py and running .pyc directly.
It seemed to be roughly on par with running .pyc directly, and about
18ms
faster than running .py. The file had 600 lines (21kb) of code.

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


Re: Join strings - very simple Q.

2007-03-24 Thread Paulo da Silva
Steven D'Aprano escreveu:
 On Fri, 23 Mar 2007 13:15:29 -0700, John Machin wrote:
 


 
 Western civilization is 6,000 years old. 

After reading that post I wouldn't talk about
civilization, western or any other :-)

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


Re: [JOB] Sr. Python Developer, Northern VA

2007-03-24 Thread John J. Lee
Chuck Rhode [EMAIL PROTECTED] writes:

 John J. Lee wrote this on Thu, 22 Mar 2007 21:16:13 +.  My reply is
 below.
 
  I sympathise but conventional wisdom (which surely has a lot of
  truth in it) is that employers are not faced with the problem of
  minimising false negatives (failing to hire when they should have
  hired).  They are faced with the problem of minimising false
  positives (hiring when they should not have hired).  That's a gross
  simplification of course, but I'm sure you appreciate the point --
  if you're hiring employees, being fairly risk-averse is probably
  quite rational.
 
 ... so what's this we hear of employers' (in the US) being so starved
 for talent that they're willing to bring in young men from overseas
 with 3.5 kids and 1.5 wives?

I honestly don't follow the connection between my statements about the
way things are and the ethical (?) position you appear to be pushing.
Please don't take offence when I ask you not to bother to elaborate,
though.


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


Re: [JOB] Sr. Python Developer, Northern VA

2007-03-24 Thread John J. Lee
Anton Vredegoor [EMAIL PROTECTED] writes:
 John J. Lee wrote:
[...]
  but I'm sure you appreciate the point -- if you're hiring employees,
  being fairly risk-averse is probably quite rational.
 
 So when we really mean business, you're back to static typing?

I'm not wedded to dynamic typing, as it happens.  Of course, if I
were, I would have to take it as a metaphor for all of life ;-)

[...]
 Well, on my next leisurely stroll along the river side, I will
 consciously enjoy the freedom of currently having no job instead of
 the usual I'm lucky I have no kids to worry about, just to humor you!

Bastard :-)


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


Problem with game

2007-03-24 Thread hollandlucas
Hello,

the following script (it's in German):

import random
print Wie oft wollen Sie spielen?
anzahl_spiele = input()
games = 0
while games  anzahl_spiele:
games += 1
print Raten sie die Zahl, die vom Computer generiert wird!
random_number = random.randint(1, 100)
user_number = 0
counter = 0
while user_number != random_number:
user_number = input (Zahl eingeben: )
counter += 1
if user_number  random_number:
print Die eingegebene Zahl ist kleiner als die generierte
Zahl.
elif user_number  random_number:
print Die eingegebene Zahl ist groesser als die generierte
Zahl.
print Sie haben gewonnen!
print counter

yields the following error when run:

 File Python-episode12-Zahlenraten.py, line 15
print Die eingegebene Zahl ist kleiner als die generierte Zahl.

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


Re: Problem with game

2007-03-24 Thread hollandlucas
  File Python-episode12-Zahlenraten.py, line 15
 print Die eingegebene Zahl ist kleiner als die generierte Zahl.
IndentationError: expected an indented block



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


Re: fine grain logging cotrol

2007-03-24 Thread Eric S. Johansson
Dennis Lee Bieber wrote:
 On Fri, 23 Mar 2007 21:15:56 -0400, Eric S. Johansson [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:
 
 Gabriel Genellina wrote:

 I don't get all the details of what's all that stuff for, but from the  
 error and traceback, I think you forgot to create the filter_test  
 instance. That is, change lgr.addFilter(filter_test) to  
 lgr.addFilter(filter_test())

 do'h . for some reason, I thought addFilter took a class instead of an 
 instance.  but on testing, I'm still missing something and getting the 
 same error
 
   Doesn't your filter_test class require a parameter itself -- the
 name?
yes.  here is the code that fails.  I don't understand why the unbound 
method.  what is really weird is that when I singlestep through the 
code, it never seems to call filter_test.  it is like the method never 
existed.

  File C:\Python24\lib\logging\__init__.py, line 539, in filter
 if not f.filter(record):
TypeError: unbound method filter() must be called with filter_test 
instance as first argument (got LogRecord instance instead)

--
import logging
import sys

class filter_test (logging.Filter):
 test_names = { Felis.alpha : True,
Catus.alpha : False,
}

 def ___init__ (self, name):
 simple filter test 
 logging.Filter.__init__(self, name)
 self.test_name = name

 def filter(self, record):
 test and forget 
 return test_names.has_key( self.test_name) and test_names[ 
self.test_name ]

class LoggedType(type):
 def __new__(mcl, name, bases, classdict):
 def get_logger(self):
 tag = %s.%s % (name,sys._getframe(1).f_code.co_name)
 lgr = logging.getLogger(tag)
 fl = filter_test(tag)
 lgr.addFilter(fl)
 return lgr

 classdict[_%s__logger % name] = property(get_logger)
 return type.__new__(mcl, name, bases, classdict)

class Logged:
 __metaclass__ = LoggedType

class Felis(Logged):
 def alpha(self):
 self.__logger.info(Felis.alpha)
 def gamma(self):
 self.__logger.info(Felis.gamma)

class Catus(Felis):
 def alpha(self):
 self.__logger.info(Catus.alpha)
 def beta(self):
 self.__logger.info(Catus.beta)

if __name__ == __main__:
 logging.basicConfig(
 format=EXPECTED %(message)s GOT %(name)s, level=logging.INFO)
 f = Felis()
 f.alpha()
 f.gamma()
 c = Catus()
 c.alpha()
 c.beta()
 c.gamma()



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


Re: Problem with game

2007-03-24 Thread irstas
On Mar 24, 5:20 pm, [EMAIL PROTECTED] wrote:
   File Python-episode12-Zahlenraten.py, line 15
  print Die eingegebene Zahl ist kleiner als die generierte Zahl.

 IndentationError: expected an indented block

You should indent stuff inside if-statement deeper than the if itself.

I.e. NOT LIKE THIS:

if x==3:
print x


But like this:

if x==3:
print x


If in your editor it looks like you have done this, the error
is probably that you are mixing tabs and spaces as indentation
and your editor doesn't display tabs as 8 spaces. This leads to
an amazing visual illusion cunnigly developed to turn people away
from Python.


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


Re: PyImport_ImportModule/embedding: surprising behaviors

2007-03-24 Thread Aahz
In article [EMAIL PROTECTED],
David Abrahams  [EMAIL PROTECTED] wrote:

I was under the impression that both the current directory *and* the
python library directory were already, automatically, in sys.path, so
I'm really surprised to see this.  Am I doing something wrong, or is
this simply the expected behavior (and if so, where is it documented)?

IIRC (without bother to test), there has been some change in the
definition of current directory -- it used to be the actual current
directory of os.getcwd(), but since changed to the startup directory.
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

Typing is cheap.  Thinking is expensive.  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Pattern for foo tool - API - shell|GUI

2007-03-24 Thread Anastasios Hatzis
I'm looking for a pattern where different client implementations can use the 
same commands of some fictive tool (foo) by accessing some kind of API. 
Actually I have the need for such pattern for my own tool 
(http://openswarm.sourceforge.net). I already started restructuring my code 
to separate the actual command implementations from the command-line scripts 
(which is optparser-based now) and have some ideas how to proceed. But 
probably there is already a good pattern used for Python-based tools.

In the case that some of you are interested into this topic and my recent 
thoughts, you may want to have a look at the description below. Any comments 
are very much appreciated. Hopefully this list is a good place for discussing 
a pattern, otherwise I would be okay to move this to another place. Thank 
you.

Here we go:
The tool package itself provides several commands, although not important for 
the pattern itself, here some examples: modifying user-specific preferences, 
creating and changing project settings files, project-related 
code-generation, or combinations of such commands ... later also commands for 
transformation between several XML formats etc. The classes which implement 
these commands are currently in multiple modules, each having a class named
CmdHandler.

I have some Python scripts (each having a ScriptHandler classes), for use via 
command-line. Each ScriptHandler class is responsible to add all related 
command-line options and process those provided by the user (based on 
optparse library from Python standard lib). The script then calls the 
corresponding command and provide the verified options as parameters.

Due to the nature of the tool under specific conditions the following results 
may come during command execution:
* successful execution, no interaction
* critical error, execution cancelled
* user interaction needed (e.g. prompt user to approve replace existing 
directory (yes/no), prompt user to provide an alternative option)

Command-line interactions work simply with raw_input().

So far this works. Nevertheless, there are some other aspects that could be 
improved, but this is another topic: The tool uses custom exceptions (e.g. 
for critical errors) and logging features (based on logging from Python 
standard lib). Currently no automated tests, but I have to add.

For the next step I plan to support not only my own command-line scripts, but 
also a GUI to access the commands, as well as 3rd-party products (themselves 
command-line scripts or GUIs, such as foo plugins for any 3rd-party-tools). As 
far as I see, these clients need to implement a handler that:
(1) Collecting all required parameters and optional parameters from a user
(2) Provide these parameters for a particular call to command API
(3) Provides some kind of hooks that are called back from the API on specific 
events, e.g. Question with user-choice; Information with user-input
(4) Provide a logging handler object from the tool logging 
class or a sub-class of that in the case that a client-specific logging object 
should be triggered on each debug, message, warning etc.

(1) is very client-specific, e.g. in a GUI via dialogs.

(2) Each command provides a signature for all required/optional parameters. 
They are all verified from the command itself, although a client could do 
some verification at the first place.

(3) Example use-case: a command needs to know if the user wants the command to 
proceed with a particular action, e.g. Do you want to delete bar.txt? 
with Yes, No and Cancel choice. So the client's handler object (which 
is provided as first parameter to each command) implements client-specific 
features to show the user this question (e.g. pop-up dialog with question and 
three buttons), receive the user input (clicking one of the buttons) and pass 
this choice back to the foo API. Alternatively some kind of text information 
could be required, as in raw_input(), so actually this probably would be two 
different interaction features to be implemented.

(4) The foo API also provides a logging class. The client needs to initialize 
such an object and provide it as member of the handler object provided to the 
API. I wonder if some clients may have own logging features and want to 
include all log messages from foo tool to the own logs. In this case a client 
could its own sub-class of the foo logging class and extending it with 
callbacks to its (client-)native logging object.

What do you think about this?

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


Re: PyImport_ImportModule/embedding: surprising behaviors

2007-03-24 Thread Alex Martelli
Aahz [EMAIL PROTECTED] wrote:

 In article [EMAIL PROTECTED],
 David Abrahams  [EMAIL PROTECTED] wrote:
 
 I was under the impression that both the current directory *and* the
 python library directory were already, automatically, in sys.path, so
 I'm really surprised to see this.  Am I doing something wrong, or is
 this simply the expected behavior (and if so, where is it documented)?
 
 IIRC (without bother to test), there has been some change in the
 definition of current directory -- it used to be the actual current
 directory of os.getcwd(), but since changed to the startup directory.

In 2.3 and later, at least (sorry, no 2.2 and earlier around to check),
site.py makes every directory along sys.path an absolute path at Python
startup.  This _should_ probably be documented at
http://docs.python.org/lib/module-site.html, but it doesn't appear to
be clearly stated there (the page only speaks of site's job of
appending site specific paths, and not of the other jobs it also
performs, such as normalizing sys.path by turning all paths into
absolute ones and removing duplicates).


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


Re: Join strings - very simple Q.

2007-03-24 Thread Dustan
On Mar 24, 7:16 am, Paulo da Silva [EMAIL PROTECTED] wrote:
 Dustan escreveu:



  On Mar 23, 1:30 pm, Paulo da Silva [EMAIL PROTECTED] wrote:
  Mike Kent escreveu:
  ...

  New way:
  l=['a','b','c']
  jl=','.join(l)
  I thank you all.

  Almost there ...
  I tried .join(l,',') but no success ... :-(

  Paulo

  Perhaps you're doing it wrong, despite having an example right in
  front of you?

 Some misunderstanding here ...
 The post was just to thank. I was refering to what I tried
 before posting the question here.

Ah. Sorry; I didn't realize that.

 Regards
 Paulo


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


Re: Mastering Python

2007-03-24 Thread cga2000
On Sun, Mar 18, 2007 at 09:38:52PM EST, Paul McGuire wrote:
 On Mar 16, 9:27 am, BartlebyScrivener [EMAIL PROTECTED] wrote:
  On Mar 16, 8:39 am, Paul McGuire [EMAIL PROTECTED] wrote:
 
 
 
   Wow, are you still reading?  Quit wasting time and go download a
   Python dist and get started already!
 
  I think you should extract that and spend twenty minutes tidying it up
  and then publish it to the Python for Programmers page or make it a
  downloadable .pdf.
 
  http://wiki.python.org/moin/BeginnersGuide/Programmers
 
  rd
 
   The chief contribution of Protestantism to human thought is its
massive proof that God is a bore.
 
--H.L. Mencken
 
 I've added it to this page, see the last entry.  Hope some find it
 entertaining, if not informative.

Nice job.

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


Re: Need help to learn Python

2007-03-24 Thread wesley chun
 From: [EMAIL PROTECTED]
 Date: 23 Mar 2007 06:20:15 -0700

 Core Python Programming is mostly theory and very little code. It's
 good for reference and digging deeper into the language...


let me clarify here that mike's statement refers to the total number
of large applications in the book.  Core Python *does* have a lot of
code in it, but they are mostly snippets and bits using the
interactive interpreter.  i chose this model instead of many large
applications because:

1) i feel that small snippets that people can follow along with in the
interpreter is more valuable... in fact, many readers *don't* have the
interpreter in front of them, but they can see what it does so that
once they *are* in front of it, it does what they expect

2) providing smallish to medium-sized applications allows for maximum
absorption by the reader

3) i didn't have time to develop lots of large applications... if you
learn with lots of large applications with lots of code, then this
book is not for you.

with that said, i would still like to state that the book's target
audience is for people who know how to program but need to pick up
Python as quickly as possible.  the theory that's in the book is
really more explanation of how the Python interpreter works,
especially the relationship between objects and memory management.
the goal is to give you enough of an understanding of how Python works
under the covers that you will write very effective code, even as a
beginner to the language.

you can read more of my manifesto on Amazon's page for the book as
well as at the book's website below.

cheers!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Core Python Programming, Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Removing Python 2.4.4 on OSX

2007-03-24 Thread Robert Hicks
I want to upgrade to 2.5 but I don't see any unistall instructions
anywhere.

Robert

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


Re: Join strings - very simple Q.

2007-03-24 Thread 7stud
On Mar 24, 8:30 am, Duncan Booth [EMAIL PROTECTED] wrote:
 In case you are feeling that the ','.join(l) looks a bit jarring, be aware
 that there are alternative ways to write it. You can call the method on the
 class rather than the instance:

jl = str.join(',', l)
jl = unicode.join(u'\u00d7', 'l')

... the catch is you need to know
 the type of the separator in advance.

When I try the latter example, I get an error:

lst = [hello, world]
print unicode.join(u\u00d7, lst)

Traceback (most recent call last):
  File test1.py, line 2, in ?
print unicode.join(u\u00d7, lst)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd7' in
position 5: ordinal not in range(128)

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread kyosohma
On Mar 24, 11:30 am, Robert Hicks [EMAIL PROTECTED] wrote:
 I want to upgrade to 2.5 but I don't see any unistall instructions
 anywhere.

 Robert

Windows allows us to uninstall it. I think the only thing it really
installs is the files, and then it sets the system path, so just
delete the files and change your path. Unfortunately, I do not have a
Mac to test with.

Mike

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


Re: Pattern for foo tool - API - shell|GUI

2007-03-24 Thread kyosohma
On Mar 24, 10:31 am, Anastasios Hatzis [EMAIL PROTECTED] wrote:
 I'm looking for a pattern where different client implementations can use the
 same commands of some fictive tool (foo) by accessing some kind of API.
 Actually I have the need for such pattern for my own tool
 (http://openswarm.sourceforge.net). I already started restructuring my code
 to separate the actual command implementations from the command-line scripts
 (which is optparser-based now) and have some ideas how to proceed. But
 probably there is already a good pattern used for Python-based tools.

 In the case that some of you are interested into this topic and my recent
 thoughts, you may want to have a look at the description below. Any comments
 are very much appreciated. Hopefully this list is a good place for discussing
 a pattern, otherwise I would be okay to move this to another place. Thank
 you.

 Here we go:
 The tool package itself provides several commands, although not important for
 the pattern itself, here some examples: modifying user-specific preferences,
 creating and changing project settings files, project-related
 code-generation, or combinations of such commands ... later also commands for
 transformation between several XML formats etc. The classes which implement
 these commands are currently in multiple modules, each having a class named
 CmdHandler.

 I have some Python scripts (each having a ScriptHandler classes), for use via
 command-line. Each ScriptHandler class is responsible to add all related
 command-line options and process those provided by the user (based on
 optparse library from Python standard lib). The script then calls the
 corresponding command and provide the verified options as parameters.

 Due to the nature of the tool under specific conditions the following results
 may come during command execution:
 * successful execution, no interaction
 * critical error, execution cancelled
 * user interaction needed (e.g. prompt user to approve replace existing
 directory (yes/no), prompt user to provide an alternative option)

 Command-line interactions work simply with raw_input().

 So far this works. Nevertheless, there are some other aspects that could be
 improved, but this is another topic: The tool uses custom exceptions (e.g.
 for critical errors) and logging features (based on logging from Python
 standard lib). Currently no automated tests, but I have to add.

 For the next step I plan to support not only my own command-line scripts, but
 also a GUI to access the commands, as well as 3rd-party products (themselves
 command-line scripts or GUIs, such as foo plugins for any 3rd-party-tools). As
 far as I see, these clients need to implement a handler that:
 (1) Collecting all required parameters and optional parameters from a user
 (2) Provide these parameters for a particular call to command API
 (3) Provides some kind of hooks that are called back from the API on specific
 events, e.g. Question with user-choice; Information with user-input
 (4) Provide a logging handler object from the tool logging
 class or a sub-class of that in the case that a client-specific logging object
 should be triggered on each debug, message, warning etc.

 (1) is very client-specific, e.g. in a GUI via dialogs.

 (2) Each command provides a signature for all required/optional parameters.
 They are all verified from the command itself, although a client could do
 some verification at the first place.

 (3) Example use-case: a command needs to know if the user wants the command to
 proceed with a particular action, e.g. Do you want to delete bar.txt?
 with Yes, No and Cancel choice. So the client's handler object (which
 is provided as first parameter to each command) implements client-specific
 features to show the user this question (e.g. pop-up dialog with question and
 three buttons), receive the user input (clicking one of the buttons) and pass
 this choice back to the foo API. Alternatively some kind of text information
 could be required, as in raw_input(), so actually this probably would be two
 different interaction features to be implemented.

 (4) The foo API also provides a logging class. The client needs to initialize
 such an object and provide it as member of the handler object provided to the
 API. I wonder if some clients may have own logging features and want to
 include all log messages from foo tool to the own logs. In this case a client
 could its own sub-class of the foo logging class and extending it with
 callbacks to its (client-)native logging object.

 What do you think about this?

 Best regards,
 Anastasios

I think if you want to use a GUI, wxpython or Tkinter would work well
for you. wxPython has more widgets from the start, but is also more
complex. Tkinter is good for quick and dirty GUIs, but gets
increasingly more complicated to deal with the more complex the GUI
has to be, in general. At least, that's what I am told.

I started out using Tkinter. It's great for prototyping, 

Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread 7stud
Hi,

Robert Hicks wrote:
 I want to upgrade to 2.5 but I don't see any unistall instructions
 anywhere.

 Robert

I don't know if this is pertinent to your situation, but yesterday I
read something that said you need a framework install in order to do
GUI programming with wxPython.   I believe a framework install is what
originally comes with Macs and it is integrated into the OS.  I don't
know if there is a framework install for 2.5.

In addition, the download notes for the stand alone MacPython 2.5
install say that there aren't as many modules for 2.5 as there are for
the 2.4, which is something you may want to consider.

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread 7stud
Robert Hicks wrote:
... but I don't see any unistall instructions
 anywhere.


Did 2.4.4 come pre-installed?

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Greg Donald
On 24 Mar 2007 10:30:28 -0700, Robert Hicks [EMAIL PROTECTED] wrote:
 I want to upgrade to 2.5 but I don't see any unistall instructions
 anywhere.


You're not required to remove the old version before installing the new version.

Just install the new version somewhere like /usr/local and put
/usr/local/bin ahead of your other paths.



-- 
Greg Donald
http://destiney.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Diez B. Roggisch
Robert Hicks schrieb:
 I want to upgrade to 2.5 but I don't see any unistall instructions
 anywhere.

Don't do it. OSX uses the shipped version for its own purposes, and 
you'll break things if you uninstall it.

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


Re: Join strings - very simple Q.

2007-03-24 Thread Diez B. Roggisch
7stud schrieb:
 On Mar 24, 8:30 am, Duncan Booth [EMAIL PROTECTED] wrote:
 In case you are feeling that the ','.join(l) looks a bit jarring, be aware
 that there are alternative ways to write it. You can call the method on the
 class rather than the instance:

jl = str.join(',', l)
jl = unicode.join(u'\u00d7', 'l')

 ... the catch is you need to know
 the type of the separator in advance.
 
 When I try the latter example, I get an error:
 
 lst = [hello, world]
 print unicode.join(u\u00d7, lst)
 
 Traceback (most recent call last):
   File test1.py, line 2, in ?
 print unicode.join(u\u00d7, lst)
 UnicodeEncodeError: 'ascii' codec can't encode character u'\xd7' in
 position 5: ordinal not in range(128)

You are mixing unicode with bytestrings here. make hello uhello, 
same for world.

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


Re: Join strings - very simple Q.

2007-03-24 Thread Duncan Booth
Diez B. Roggisch [EMAIL PROTECTED] wrote:

 7stud schrieb:
 When I try the latter example, I get an error:
 
 lst = [hello, world]
 print unicode.join(u\u00d7, lst)
 
 Traceback (most recent call last):
   File test1.py, line 2, in ?
 print unicode.join(u\u00d7, lst)
 UnicodeEncodeError: 'ascii' codec can't encode character u'\xd7' in
 position 5: ordinal not in range(128)
 
 You are mixing unicode with bytestrings here. make hello uhello, 
 same for world.
 
Sorry Diez, wrong answer. A unicode separator will cause all the strings 
being joined to be decoded using the default encoding (which could cause 
problems with non-ascii characters in the decoded strings), but the problem 
here is with encoding, not decoding.

7stud: the problem isn't the join, it is printing the string on your 
terminal which is the problem. Try just:

   print u\u00d7

and you'll get the same problem. Or:

 lst = [hello, world]
 joined = unicode.join(u\u00d7, lst)

will work, but you'll still have problems printing the result.

If you try it using a Python interpreter with an appropriate output 
encoding it will work (idle can handle it on my system, but the DOS prompt 
with its default codepage cannot).
-- 
http://mail.python.org/mailman/listinfo/python-list


A better webpage filter

2007-03-24 Thread Anton Vredegoor
Since a few days I've been experimenting with a construct that enables 
me to send the sourcecode of the web page I'm reading through a Python 
script and then into a new tab in Mozilla. The new tab is automatically 
opened so the process feels very natural, although there's a lot of 
reading, filtering and writing behind the scene.

I want to do three things with this post:

A) Explain the process so that people can try it for themselves and say 
Hey stupid, I've been doing the same thing with greasemonkey for ages, 
or maybe You're great, this is easy to see, since the crux of the 
biscuit is the apostrophe.  Both kind of comments are very welcome.

B) Explain why I want such a thing.

C) If this approach is still valid after all the before, ask help for 
writing a better Python htmlfilter.py

So here we go:

A) Explain the process

We need :

- mozilla firefox http://en-us.www.mozilla.com/en-US/
- add-on viewsourcewith https://addons.mozilla.org/firefox/394/
- batch file (on windows):
(htmfilter.bat)
d:\python25\python.exe D:\Python25\Scripts\htmlfilter.py %1  out.html
start out.html
- a python script:
#htmfilter.py

import sys

def htmlfilter(fname, skip = []):
 f = file(fname)
 data = f.read()
 L = []
 for i,x in enumerate(data):
 if x == '':
 j = i
 elif x =='':
 L.append((j,i))
 R = list(data)
 for i,j in reversed(L):
 s = data[i:j+1]
 for x in skip:
 if x in s:
 R[i:j+1] = ' '
 break
 return ''.join(R)

def test():
 if len(sys.argv) == 2:
 skip = ['div','table']
 fname = sys.argv[1].strip()
 print htmlfilter(fname,skip)

if __name__=='__main__':
 test()

Now install the htmlfilter.py file in your Python scripts dir and adapt 
the batchfile to point to it.

To use the viewsourcewith add-on to open the batchfile: Go to some 
webpage, left click and view the source with the batchfile.

B) Explain why I want such a thing.

OK maybe this should have been the thing to start with, but hey it's 
such an interesting technique it's almost a waste no to give it a chance 
before my idea is dissed :-)

Most web pages I visit lately are taking so much room for ads (even with 
adblocker installed) that the mere 20 columns of text that are available 
for reading are slowing me down unacceptably. I have tried clicking 
'print this' or 'printer friendly' or using 'no style' from the mozilla 
menu and switching back again for other pages but it was tedious to say 
the least. Every webpage has different conventions. In the end I just 
started editing web pages' source code by hand, cutting out the beef and 
saving it as a html file with only text, no scripts or formatting. But 
that was also not very satisfying because raw web pages are *big*.

Then I found out I often could just replace all 'table' or 'div' 
elements with a space and the page -although not very html compliant any 
more- still loads and often the text looks a lot better. This worked for 
at least 50 percent of the pages and restored my autonomy and 
independence in reading web pages! (Which I do a lot by the way, maybe 
for most people the problem is not very irritating, because they don't 
read as much? Tell me that too, I want to know :-)

C) Ask help writing a better Python htmlfilter.py

Please. You see the code for yourself, this must be done better :-)

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


Re: Join strings - very simple Q.

2007-03-24 Thread Max Erickson
7stud [EMAIL PROTECTED] wrote:

 On Mar 24, 8:30 am, Duncan Booth [EMAIL PROTECTED]
 wrote: 
 In case you are feeling that the ','.join(l) looks a bit
 jarring, be aware that there are alternative ways to write it.
 You can call the method on the class rather than the instance:

jl = str.join(',', l)
jl = unicode.join(u'\u00d7', 'l')

... the catch is you need to know
 the type of the separator in advance.
 
 When I try the latter example, I get an error:
 
 lst = [hello, world]
 print unicode.join(u\u00d7, lst)
 
 Traceback (most recent call last):
   File test1.py, line 2, in ?
 print unicode.join(u\u00d7, lst)
 UnicodeEncodeError: 'ascii' codec can't encode character u'\xd7'
 in position 5: ordinal not in range(128)
 

Your terminal is likely the problem. Get rid of the print:

q=unicode.join(u'\u00d7',['hello','world'])

and you will probably get rid of the exception.

(so I guess the issue is the display, not the logic)


max

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Robert Hicks
On Mar 24, 2:09 pm, Greg Donald [EMAIL PROTECTED] wrote:
 On 24 Mar 2007 10:30:28 -0700, Robert Hicks [EMAIL PROTECTED] wrote:

  I want to upgrade to 2.5 but I don't see any unistall instructions
  anywhere.

 You're not required to remove the old version before installing the new 
 version.

 Just install the new version somewhere like /usr/local and put
 /usr/local/bin ahead of your other paths.

 --
 Greg Donaldhttp://destiney.com/

That is exactly what I did. I don't touch the Apple supplied version.
Now I want to put that latest Python on.

Robert


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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Robert Hicks
On Mar 24, 2:06 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Robert Hicks schrieb:

  I want to upgrade to 2.5 but I don't see any unistall instructions
  anywhere.

 Don't do it. OSX uses the shipped version for its own purposes, and
 you'll break things if you uninstall it.

 Diez

No, the OSX version is like 2.3 something. I installed the 2.4.4
version in /usr/local bypassing the Apple stuff.

Robert

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


Anyone know of a MICR parser algorithm written in Python?

2007-03-24 Thread mkppk
MICR = The line of digits printed using magnetic ink at the bottom of
a check.

Does anyone know of a Python function that has been written to parse a
line of MICR data?
Or, some financial package that may contain such a thing?
Or, in general, where I should be looking when looking for a piece of
Python code that may have already been written by someone?

I'm working on a project that involves a check scanner the produces
the raw MICR line as text.

Now, that raw MICR needs to be parsed for the various pieces of info.
The problem with MICR is that there is no standard layout. There are
some general rules for item placement, but beyond that it is up to the
individual banks to define how they choose to position the
information.

I did find an old C program written by someone at IBM... But I've read
it and it is Not code that would nicely convert to Python (maybe its
all the Python I'm used to, be it seems very poorly written).

Here is the link to that C code: 
ftp://ftp.software.ibm.com/software/retail/poseng/4610/4610micr.zip

I've even tried using boost to generate a Python module, but that
didn't go well, and in the end is not going to be a solution for me
anyway.. really need access to the Python source.

Any help at all would be appreciated,

-mkp

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread 7stud
On Mar 24, 12:09 pm, Greg Donald [EMAIL PROTECTED] wrote:
 On 24 Mar 2007 10:30:28 -0700, Robert Hicks [EMAIL PROTECTED] wrote:

  I want to upgrade to 2.5 but I don't see any unistall instructions
  anywhere.

 You're not required to remove the old version before installing the new 
 version.

 Just install the new version somewhere like /usr/local and put
 /usr/local/bin ahead of your other paths.

 --
 Greg Donaldhttp://destiney.com/

Can you explain how that works?  If you install python in /usr/local,
doesn't that leave you with something like /usr/local/python?  So what
does putting usr/local/bin ahead of your other paths do?

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Greg Donald
On 24 Mar 2007 12:10:12 -0700, 7stud [EMAIL PROTECTED] wrote:
 Can you explain how that works?  If you install python in /usr/local,
 doesn't that leave you with something like /usr/local/python?  So what
 does putting usr/local/bin ahead of your other paths do?

./configure --prefix=/usr/local

Then python would be /usr/local/bin/python.

For bash put this somewhere near the end of your .bashrc or /etc/bashrc:

export PATH=/usr/local/bin:$PATH

Then when you attempt to run the python binary it will be found in the
place you installed it first, not where the system version was
installed.

http://en.wikipedia.org/wiki/Path_%28computing%29


-- 
Greg Donald
http://destiney.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread skip

bbxx789 Can you explain how that works?  If you install python in
bbxx789 /usr/local, doesn't that leave you with something like
bbxx789 /usr/local/python?  So what does putting usr/local/bin ahead of
bbxx789 your other paths do?

When you install with --prefix==/usr/local you will wind up with
/usr/local/bin/python.  There will also be a /usr/local/lib/pythonX.Y (with
structure underneath it) containing all the Python and extension modules.

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Shane Geiger
You don't have to uninstall 2.4.4 to use 2.5.  Just change where the 
symlink points:


[EMAIL PROTECTED]:~\ 14:45:35$ ls -la /usr/bin/python
lrwxr-xr-x   1 root  wheel  24 Mar  1 12:48 /usr/bin/python - 
/usr/local/bin/python2.5

[EMAIL PROTECTED]:~\ 14:45:40$

In general, I am a little wary of uninstalling programs like Python 
which are used by many applications.  You don't want to find out after 
you have uninstalled it that something actually needed it.  It is much 
safer to keep it around.



[EMAIL PROTECTED] wrote:

On Mar 24, 11:30 am, Robert Hicks [EMAIL PROTECTED] wrote:
  

I want to upgrade to 2.5 but I don't see any unistall instructions
anywhere.

Robert



Windows allows us to uninstall it. I think the only thing it really
installs is the files, and then it sets the system path, so just
delete the files and change your path. Unfortunately, I do not have a
Mac to test with.

Mike

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: Python object overhead?

2007-03-24 Thread 7stud
On Mar 23, 4:04 pm, Jack Diederich [EMAIL PROTECTED] wrote:

 If you make the record a new style class (inherit from object) you can
 specify the __slots__ attribute on the class.  This eliminates the per
 instance dictionary overhead in exchange for less flexibility.


How is efficiency improved with __slots__?  Don't you create a list
object that replaces the dictionary object, e.g.:

class Test(object):
__slots__ = [m, n]


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


Re: Python object overhead?

2007-03-24 Thread Jean-Paul Calderone
On 24 Mar 2007 13:08:02 -0700, 7stud [EMAIL PROTECTED] wrote:
On Mar 23, 4:04 pm, Jack Diederich [EMAIL PROTECTED] wrote:

 If you make the record a new style class (inherit from object) you can
 specify the __slots__ attribute on the class.  This eliminates the per
 instance dictionary overhead in exchange for less flexibility.


How is efficiency improved with __slots__?  Don't you create a list
object that replaces the dictionary object, e.g.:

class Test(object):
__slots__ = [m, n]


Only one list is created.  It is used to define a C array where attributes
will be stored.  Each instance still has that C array, but it has much less
overhead than a Python list or dictionary.

Whether this reduction in overhead actually results in a useful or measurable
performance improvement is a separate question, of course.

Jean-Paul

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


Re: PyImport_ImportModule/embedding: surprising behaviors

2007-03-24 Thread Ziga Seilnacht
David Abrahams wrote:
 I'm seeing highly surprising (and different!) behaviors of
 PyImport_ImportModule on Linux and Windows when used in a program with
 python embedding.

 On Linux, when attempting to import a module xxx that's in the current
 directory, I get

   ImportError: No module named xxx

 I can work around the problem by setting

   PYTHONPATH=.

Python puts the current directory in sys.path only if it can't
determine the directory of the main script. There was a bug on
Windows that always added current directory to sys.path, but it
was fixed in Python 2.5. This is documented in the library
reference:

http://docs.python.org/lib/module-sys.html#l2h-5149

 On Windows, I get:

   'import site' failed; use -v for traceback

 I can work around the problem by setting PYTHONPATH to point to the
 python library directory:

   set PYTHONPATH=c:\Python25\Lib

This happens because Python calculates the initial import path by
looking for an executable file named python along PATH. You can
change this by calling Py_SetProgramName(filename) before calling
Py_Initialize(). This is documented in API reference manual:

http://docs.python.org/api/embedding.html

That page also describes a few hooks that you can overwrite to
modify the initial search path. They are described in more detail
on this page:

http://docs.python.org/api/initialization.html

HTH,
Ziga


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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread James Stroud
Shane Geiger wrote:
 You don't have to uninstall 2.4.4 to use 2.5.  Just change where the 
 symlink points:
 
 [EMAIL PROTECTED]:~\ 14:45:35$ ls -la /usr/bin/python
 lrwxr-xr-x   1 root  wheel  24 Mar  1 12:48 /usr/bin/python - 
 /usr/local/bin/python2.5
 [EMAIL PROTECTED]:~\ 14:45:40$
 

I have been chastised on this list for a similar suggestion (notably 
re-linking /usr/bin/python) as it may break the system because the 
particular version installed may be required for some scripts in the system.

Probably better is to create a link in ~/bin and make sure ~/bin is 
first in the path. Bash experts--please say how to do this because bash 
is default for OSX and is undoubtedly what the OP is using. I use csh.

Better, even than this is to install ipython under 2.5 and put the 
following script in your ~/bin (name it python):

#! /bin/csh -f
#second line of script (include above)

if ($#argv == 0) then
   /usr/local/bin/ipython # ==or wherever ipython is
else
   /usr/local/bin/python2.5 $argv
endif

#end of script

It doesn't matter if you use bash, the above script, though csh, will 
run fine.

Now type this in a terminal: chmod a+x ~/bin/python.

Now you can use ipython or python depending on whether you supply 
arguments. ipython will launch if you supply none (which means you want 
an interactive interpreter) and regular python2.5 will launch if you 
give it a script name--avoiding jumping into the ipython interpreter 
after the script finishes.

If you don't know what ipython is, you are missing out.

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread James Stroud
7stud wrote:
 On Mar 24, 12:09 pm, Greg Donald [EMAIL PROTECTED] wrote:
 On 24 Mar 2007 10:30:28 -0700, Robert Hicks [EMAIL PROTECTED] wrote:

 I want to upgrade to 2.5 but I don't see any unistall instructions
 anywhere.
 You're not required to remove the old version before installing the new 
 version.

 Just install the new version somewhere like /usr/local and put
 /usr/local/bin ahead of your other paths.

 --
 Greg Donaldhttp://destiney.com/
 
 Can you explain how that works?  If you install python in /usr/local,
 doesn't that leave you with something like /usr/local/python?  So what
 does putting usr/local/bin ahead of your other paths do?
 

Don't build python for OS X unless you know you need to or want a 
learning experience. Rolling your own python is somewhat a can of worms 
for the uninitiated and it will be pretty tough beyond that to make it 
run as cleanly as the stock builds. (E.g. you will be asking about why 
readline doesn't work, etc.) This stuff is especially the case for OS X, 
which does things a little differently than linux.

Just download the 2.5 installer from python.org. Double click it and be 
done. A link to the new python will be created for you in 
/usr/local/bin. If you already had an earlier installed and the link 
didn't get updated, just replace the old one substituting 2.4 (or 2.3) 
with 2.5.

Then make sure /usr/local/bin comes before /usr/bin in your path and you 
will be set. See also my previous post about integrating ipython.

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


Re: fine grain logging cotrol

2007-03-24 Thread Eric S. Johansson
Dennis Lee Bieber wrote:
 On Sat, 24 Mar 2007 11:29:34 -0400, Eric S. Johansson [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:
 
 
 yes.  here is the code that fails.  I don't understand why the unbound 
 method.  what is really weird is that when I singlestep through the 
 code, it never seems to call filter_test.  it is like the method never 
 existed.

   Among other things -- the init is never called... You have too many
 _ on it. Second, I suspect you needed to overload getLogger -- there is
 no code, that I could see that would /invoke/ a get_logger method.

get_logger does get called as part of the metaclass magic.  I don't 
understand it well enough to explain but a debugger reveals some.  for 
example, stepping through get_logger, I hit the first two statements but 
after executing getLogger, I end up at logger.info.  this leads me to 
believe that __new__ runs at the start of every method invocation (not 
just at object creation).  I obviously need to read more on the topic. 
I am really puzzled that get_logger never makes past getLogger but 
hopefully insight will arrive.


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


Re: Python object overhead?

2007-03-24 Thread 7stud
On Mar 24, 2:19 pm, Jean-Paul Calderone [EMAIL PROTECTED] wrote:
 Only one list is created.  It is used to define a C array where attributes
 will be stored.  Each instance still has that C array, but it has much less
 overhead than a Python list or dictionary.


It's all C underneath, right?  So a dictionary is what?  Two parallel
C arrays: one array with the names and one with the values?

When you do this:

__slots__ = [m, n]

there still has to be a mapping between the names m and n and
their values.  So aren't two parallel C arrays required again?

 Whether this reduction in overhead actually results in a useful or measurable
 performance improvement is a separate question, of course.


I suppose a dictionary will be required to grow in size, so at
periodic intervals new, bigger arrays will need to be created, the
contents copied over, and the old arrays destroyed(similar to a
vector in C++).  And of course, the C code that accomplishes all
that creating, copying and destroying will take up some memory.

Is that what you are talking about when you say overhead?



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


Re: Python object overhead?

2007-03-24 Thread Jean-Paul Calderone
On 24 Mar 2007 13:52:46 -0700, 7stud [EMAIL PROTECTED] wrote:
On Mar 24, 2:19 pm, Jean-Paul Calderone [EMAIL PROTECTED] wrote:
 Only one list is created.  It is used to define a C array where attributes
 will be stored.  Each instance still has that C array, but it has much less
 overhead than a Python list or dictionary.


It's all C underneath, right?  So a dictionary is what?  Two parallel
C arrays: one array with the names and one with the values?

When you do this:

__slots__ = [m, n]

there still has to be a mapping between the names m and n and
their values.  So aren't two parallel C arrays required again?


Not two *per instance* though.  The per-class overhead is roughly irrelevant
since the number of classes is generally small compared to the number of
instances.  If you have a circumstance where this isn't true, then it may
be worth considering per-class overhead rather than focusong on per-instance
overhead as I think most people in this thread have done.

 Whether this reduction in overhead actually results in a useful or measurable
 performance improvement is a separate question, of course.


I suppose a dictionary will be required to grow in size, so at
periodic intervals new, bigger arrays will need to be created, the
contents copied over, and the old arrays destroyed(similar to a
vector in C++).  And of course, the C code that accomplishes all
that creating, copying and destroying will take up some memory.

Is that what you are talking about when you say overhead?


I mostly had the Python object overhead and the overallocation overhead
in mind.  The code for resizing dicts is around whether you are using it
or not, after all.  You might want to take a look at the how dicts and
lists and __slots__ are implemented if you're interested in the details.

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


Re: Python object overhead?

2007-03-24 Thread Felipe Almeida Lessa
On 3/23/07, Bjoern Schliessmann
[EMAIL PROTECTED] wrote:
 (Note that almost everything in Python is an object!)

Could you tell me what in Python isn't an object? Are you counting
old-style classes and instances as not objects?

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


Re: A better webpage filter

2007-03-24 Thread Gabriel Genellina
En Sat, 24 Mar 2007 15:45:41 -0300, Anton Vredegoor  
[EMAIL PROTECTED] escribió:

 Since a few days I've been experimenting with a construct that enables
 me to send the sourcecode of the web page I'm reading through a Python
 script and then into a new tab in Mozilla. The new tab is automatically
 opened so the process feels very natural, although there's a lot of
 reading, filtering and writing behind the scene.

 I want to do three things with this post:

 A) Explain the process so that people can try it for themselves and say
 Hey stupid, I've been doing the same thing with greasemonkey for ages,
 or maybe You're great, this is easy to see, since the crux of the
 biscuit is the apostrophe.  Both kind of comments are very welcome.

I use the Opera browser: http://www.opera.com
Among other things (like having tabs for ages!):
- enable/disable tables and divs (like you do)
- enable/disable images with a keystroke, or only show cached images.
- enable/disable CSS
- banner supressing (aggressive)
- enable/disable scripting
- fit to page width (for those annoying sites that insist on using a  
fixed width of about 400 pixels, less than 1/3 of my actual screen size)
- apply your custom CSS or javascript on any page
- edit the page source and *refresh* the original page to reflect your  
changes

All of this makes a very smooth web navigation - specially on a slow  
computer or slow connection.

-- 
Gabriel Genellina

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


Re: Join strings - very simple Q.

2007-03-24 Thread John Machin
On Mar 25, 12:32 am, Paulo da Silva [EMAIL PROTECTED] wrote:
 John Machin escreveu:
 ..



  Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on
  win32
  Type help, copyright, credits or license for more information.
  |  help(.join)
  Help on built-in function join:

  join(...)
  S.join(sequence) - string

  Return a string which is the concatenation of the strings in the
  sequence.  The separator between elements is S.

  | 

  OK, I'll bite: This was new in late 2000 when Python 2.0 was
  released. Where have you been in the last ~6.5 years?

 In a response to one of my posts I was told 'string' is
 obsolet. 'string' was enough for me, but if it is obsolet
 then there should be a *new* way, isn't it? The *new*
 way I was told to use is str methods.
 I tried that *new* way to do *old* 'string' job.

So much was obvious from your post.

 Voila
 the reason of my so pertinent question.

What was not obvious was (1) if you have been using Python for a
while, how you managed to be unaware of str methods (2) if you are a
newbie, how you managed to find out about the string module but not
find out about str methods [e.g. it's easy to miss the one line in the
official Python tutorial that refers to them] (3) why you were not
using obvious(?) methods to find out for yourself -- much faster than
posing a question on the newsgroup, and you don't have to face the
possibility of an impertinent response :-)

 I am deeply sorry to have disturbed you in your python's heaven.

I wasn't disturbed at all (you would have to try much harder), only
mildly curious.


 Next time I'll read all books available, all texts including
 the python formal description before
 posting,

A rather strange way of finding an answer to a simple question. A
focussed search (or an index!) is more appropriate. Why would you
expect the python formal description to have details on the syntax of
individual class methods? Do you always do a serial scan of all tables
for any database query? In addition to approaches I mentioned earlier,
you could try:

(1) going to the docs page on the Python website (http://
www.python.org/doc/), click on the Search link about one-third down
the page, and search for join. You would get 6 results, one of which
is join() (string method)

(2) If you are using Windows, use the index tab in the Python-supplied
docs gadget: type in join and get the same 6 results. I believe this
facility is available (through a 3rd party) on Linux. [Having the docs
on your PC or USB storage device is very useful if you are working in
an environment where access to the Internet is restricted].

(3) Use Google groups, go to comp.lang.python, type join string into
the search box, and click on Search this group. First result is the
current thread; most (or maybe all) of the next six or so will give
you the syntax your were looking for.

(4) Using Google or any other reasonable web searcher, search for the
3 words: Python join string. Any one of the first few hits gives the
answer you were seeking.

HTH,
John

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


Re: Python object overhead?

2007-03-24 Thread Gabriel Genellina
En Sat, 24 Mar 2007 18:07:57 -0300, Felipe Almeida Lessa  
[EMAIL PROTECTED] escribió:

 On 3/23/07, Bjoern Schliessmann
 [EMAIL PROTECTED] wrote:
 (Note that almost everything in Python is an object!)

 Could you tell me what in Python isn't an object? Are you counting
 old-style classes and instances as not objects?

The syntax, by example; an if statement is not an object.

-- 
Gabriel Genellina

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


qt ver. 3, linux, windows, and modal forms

2007-03-24 Thread Mike
Hi,

I'm having a problem with modal forms on windows. I've written a very 
short test program, with a main window and a form called from the main 
window. The form is set to modal with form.setModal(1) before calling 
form.show().

All works as expected on Linux. The form is modal, not allowing the main 
window to received the focus. If I call the form from within itself, the 
topmost form is modal, and not of the previous forms will receive the 
focus until the topmost form is closed; then the next topmost is modal, 
and so on.

However, on Windows XP Pro (at work - don't use windows at home), the 
form is not modal. The main window will receive the focus with a mouse 
click even though the modal form is still on top.

The source code is identical on both OS's.

Has anyone run into this before? Is there a fix? I haven't been able to 
find anything with google searches, and Trolltech's forums don't seem to 
have any entries addressing the problem, either.

I have a progam that I'm writing for work using Qt and Python, which was 
like pulling teeth with our Microsoft oriented IT department, and I very 
much do not want to tell them that it's not going to work (modal forms 
are essential).

Thanks for your help,
Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


bugs.python.org has been compromised (urgent)

2007-03-24 Thread John Bokma
Just got comment spam in:

http:// bugs.py thon.org/file7722/order-cialis.html
http:// bugs.py thon.org/file7722/order-cialis.html order cialis 
http:// bugs.py thon.org/file7723/order-tramadol.html order tramadol 


Seems someone found a nice hole in python.org and someone should be 
severely spanked for allowing for JavaScript injection:

script language=javascriptdocument.write(unescape('%3C%73%63%72%69%70 
...

PS: I probably won't read this group much after this initial post, but my 
email address in the header works.

PPS: comment spam has been reported the normal way as well.

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anyone know of a MICR parser algorithm written in Python?

2007-03-24 Thread Paul McGuire
On Mar 24, 2:05 pm, mkppk [EMAIL PROTECTED] wrote:
 MICR = The line of digits printed using magnetic ink at the bottom of
 a check.

 Does anyone know of a Python function that has been written to parse a
 line of MICR data?
 Or, some financial package that may contain such a thing?
 Or, in general, where I should be looking when looking for a piece of
 Python code that may have already been written by someone?

 I'm working on a project that involves a check scanner the produces
 the raw MICR line as text.

 Now, that raw MICR needs to be parsed for the various pieces of info.
 The problem with MICR is that there is no standard layout. There are
 some general rules for item placement, but beyond that it is up to the
 individual banks to define how they choose to position the
 information.

 I did find an old C program written by someone at IBM... But I've read
 it and it is Not code that would nicely convert to Python (maybe its
 all the Python I'm used to, be it seems very poorly written).

 Here is the link to that C 
 code:ftp://ftp.software.ibm.com/software/retail/poseng/4610/4610micr.zip

 I've even tried using boost to generate a Python module, but that
 didn't go well, and in the end is not going to be a solution for me
 anyway.. really need access to the Python source.

 Any help at all would be appreciated,

 -mkp

Is there a spec somewhere for this data?  Googling for MICR data
format specification and similar gives links to specifications for
the MICR character *fonts*, but not for the data content.

And you are right, reverse-engineering this code is more than a 10-
minute exercise.  (However, the zip file *does* include a nice set of
test cases, which might be better than the C code as a starting point
for new code.)

-- Paul

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


Re: Idiom for running compiled python scripts?

2007-03-24 Thread Mark
On Sat, 24 Mar 2007 07:21:21 -0700, irstas wrote:
 Also, rstrip doesn't work like you think it does.
 'pyxyypp.py'.rstrip('.py') == 'pyx'

Well there is embarrassing confirmation that I am a python newbie :(

 I timed it against running plain .py and running .pyc directly. It
 seemed to be roughly on par with running .pyc directly, and about 18ms
 faster than running .py. The file had 600 lines (21kb) of code.

So see my point at least? I'm still not sure why this approach is
ill-favoured?

Thanks very much for all the detailed responses here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A better webpage filter

2007-03-24 Thread Anton Vredegoor
Gabriel Genellina wrote:

 I use the Opera browser: http://www.opera.com
 Among other things (like having tabs for ages!):
 - enable/disable tables and divs (like you do)
 - enable/disable images with a keystroke, or only show cached images.
 - enable/disable CSS
 - banner supressing (aggressive)
 - enable/disable scripting
 - fit to page width (for those annoying sites that insist on using a  
 fixed width of about 400 pixels, less than 1/3 of my actual screen size)
 - apply your custom CSS or javascript on any page
 - edit the page source and *refresh* the original page to reflect your  
 changes
 
 All of this makes a very smooth web navigation - specially on a slow  
 computer or slow connection.

Thanks! I forgot about that one. It does what I want natively so I will 
go that route for now. Still I think there must be some use for my 
method of filtering. It's just too good to not have some use :-) Maybe 
in the future -when web pages will add new advertisement tactics faster 
than web browser builders can change their toolbox or instruct their 
users. After all, I was editing the filter script on one screen and 
another screen was using the new filter as soon as I had saved it.

Maybe someday someone will write a GUI where one can click some radio 
buttons that would define what goes through and what not. Possibly such 
a filter could be collectively maintained on a live webpage with an 
update frequency of a few seconds or something. Just to make sure we're 
prepared for the worst :-)

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


Re: fine grain logging cotrol

2007-03-24 Thread Eric S. Johansson
Dennis Lee Bieber wrote:

   I've never resorted to the debugger -- it's always been faster for
 me to just wolf-fence* code with print statements...

depends on the situation for me.  normally I use log statements that 
turn on or off based on predicates (now I need to figure out how to 
handle a SIGUSR1 to reload the who-logs info)  hence this quest.  when 
done it's going into my rcsoc (random cross section of code) collection 
which I'll publish one of these days.  Also, I need to see if I can make 
this lower overhead by pre computing as much of the predicate term as 
possible and perform the test before calling a log statement.   I put in 
*lots* of log statements but leave most of them off until needed. 
different form of wolf fence.

   Could you possibly be confusing the execution of the def
 statement... Remember, in Python class and def are executable
 statements themselves. That is, what you are seeing during __new__ is
 the execution of the statement that defines the get_logger method, NOT a
 call of get_logger itself.

I know def executes.  forth plays similar games and I spent a *lot* of 
time in the guts of forth.   With python, I'm just not familiar enough 
with what goes on beneath the sheets.

 
   Ah.. Okay... the wolf howled... Looking deeper at the code, it is
 not a direct call to get_logger, but an indirect one via the dictionary
 entry.

right.  still not comfortable the property call.  if I'm reading the 
right docs, the first arg is a get method and I'm not sure how a logger 
fills that need.

 
   classdict[_Felis.alpha__logger]
 
   None the less, your posted code did have too many _ on the init,
 meaning the initialization never took place, AND the references to
 test_names needs to be prefixed with self.

my most common brain fades.  I also miss tt/ttt, ss/sss, 1l and 
probably a few others.  I sometimes think IDE's should have a did you 
mean function to alert you to stuff that's almost right.  kind of 
like the lisp programmer's assistant.

--- eric

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


Re: qt ver. 3, linux, windows, and modal forms

2007-03-24 Thread David Boddie
On Saturday 24 March 2007 23:08, Mike wrote:

 I'm having a problem with modal forms on windows. I've written a very
 short test program, with a main window and a form called from the main
 window. The form is set to modal with form.setModal(1) before calling
 form.show().

Is form an instance of a QWidget subclass or a QDialog subclass?

Have you tried calling form.exec_loop() instead of form.show()?

 All works as expected on Linux. The form is modal, not allowing the main
 window to received the focus. If I call the form from within itself, the
 topmost form is modal, and not of the previous forms will receive the
 focus until the topmost form is closed; then the next topmost is modal,
 and so on.

This sounds like the desired behaviour.

 However, on Windows XP Pro (at work - don't use windows at home), the
 form is not modal. The main window will receive the focus with a mouse
 click even though the modal form is still on top.

But this should show the same behaviour. I suspect that the use of show()
rather than exec_loop() leads to the platform-specific behaviour you are
seeing.

 The source code is identical on both OS's.
 
 Has anyone run into this before? Is there a fix? I haven't been able to
 find anything with google searches, and Trolltech's forums don't seem to
 have any entries addressing the problem, either.
 
 I have a progam that I'm writing for work using Qt and Python, which was
 like pulling teeth with our Microsoft oriented IT department, and I very
 much do not want to tell them that it's not going to work (modal forms
 are essential).

Modal forms are quite commonplace, so they should work as you expect. If you
above advice doesn't help, you'll need to supply some more information about
the versions of Qt, PyQt, SIP and Python you are using.

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


Re: Pattern for foo tool - API - shell|GUI

2007-03-24 Thread Anastasios Hatzis
On Saturday 24 March 2007 18:55, [EMAIL PROTECTED] wrote:
 On Mar 24, 10:31 am, Anastasios Hatzis [EMAIL PROTECTED] wrote:
  I'm looking for a pattern where different client implementations can use
  the same commands of some fictive tool (foo) by accessing some kind of
  API. Actually I have the need for such pattern for my own tool
  (http://openswarm.sourceforge.net). I already started restructuring my
  code to separate the actual command implementations from the command-line
  scripts (which is optparser-based now) and have some ideas how to
  proceed. But probably there is already a good pattern used for
  Python-based tools.
 
  In the case that some of you are interested into this topic and my recent
  thoughts, you may want to have a look at the description below. Any
  comments are very much appreciated. Hopefully this list is a good place
  for discussing a pattern, otherwise I would be okay to move this to
  another place. Thank you.
 
  Here we go:
  The tool package itself provides several commands, although not important
  for the pattern itself, here some examples: modifying user-specific
  preferences, creating and changing project settings files,
  project-related
  code-generation, or combinations of such commands ... later also commands
  for transformation between several XML formats etc. The classes which
  implement these commands are currently in multiple modules, each having a
  class named CmdHandler.
 
  I have some Python scripts (each having a ScriptHandler classes), for use
  via command-line. Each ScriptHandler class is responsible to add all
  related command-line options and process those provided by the user
  (based on optparse library from Python standard lib). The script then
  calls the corresponding command and provide the verified options as
  parameters.
 
  Due to the nature of the tool under specific conditions the following
  results may come during command execution:
  * successful execution, no interaction
  * critical error, execution cancelled
  * user interaction needed (e.g. prompt user to approve replace existing
  directory (yes/no), prompt user to provide an alternative option)
 
  Command-line interactions work simply with raw_input().
 
  So far this works. Nevertheless, there are some other aspects that could
  be improved, but this is another topic: The tool uses custom exceptions
  (e.g. for critical errors) and logging features (based on logging from
  Python standard lib). Currently no automated tests, but I have to add.
 
  For the next step I plan to support not only my own command-line scripts,
  but also a GUI to access the commands, as well as 3rd-party products
  (themselves command-line scripts or GUIs, such as foo plugins for any
  3rd-party-tools). As far as I see, these clients need to implement a
  handler that:
  (1) Collecting all required parameters and optional parameters from a
  user (2) Provide these parameters for a particular call to command API
  (3) Provides some kind of hooks that are called back from the API on
  specific events, e.g. Question with user-choice; Information with
  user-input (4) Provide a logging handler object from the tool logging
  class or a sub-class of that in the case that a client-specific logging
  object should be triggered on each debug, message, warning etc.
 
  (1) is very client-specific, e.g. in a GUI via dialogs.
 
  (2) Each command provides a signature for all required/optional
  parameters. They are all verified from the command itself, although a
  client could do some verification at the first place.
 
  (3) Example use-case: a command needs to know if the user wants the
  command to proceed with a particular action, e.g. Do you want to delete
  bar.txt? with Yes, No and Cancel choice. So the client's handler
  object (which is provided as first parameter to each command) implements
  client-specific features to show the user this question (e.g. pop-up
  dialog with question and three buttons), receive the user input (clicking
  one of the buttons) and pass this choice back to the foo API.
  Alternatively some kind of text information could be required, as in
  raw_input(), so actually this probably would be two different interaction
  features to be implemented.
 
  (4) The foo API also provides a logging class. The client needs to
  initialize such an object and provide it as member of the handler object
  provided to the API. I wonder if some clients may have own logging
  features and want to include all log messages from foo tool to the own
  logs. In this case a client could its own sub-class of the foo logging
  class and extending it with callbacks to its (client-)native logging
  object.
 
  What do you think about this?
 
  Best regards,
  Anastasios

 I think if you want to use a GUI, wxpython or Tkinter would work well
 for you. wxPython has more widgets from the start, but is also more
 complex. Tkinter is good for quick and dirty GUIs, but gets
 increasingly more 

Re: bugs.python.org has been compromised (urgent)

2007-03-24 Thread skip

John Just got comment spam in:
John http:// bugs.py thon.org/file7722/order-cialis.html
John http:// bugs.py thon.org/file7722/order-cialis.html order cialis 
John http:// bugs.py thon.org/file7723/order-tramadol.html order tramadol 

Yes, we know about it and are working on solving the problem.

Thanks,

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


persistent plot windows

2007-03-24 Thread Rodrigo Lopez-Negrete
Hi all,

I'm trying to write a python script using plotting form pylab.
Unfortunatelly I've encountered a problem. When I run the script via
'python myscript.py' the plot windows open and close very quickly, or
when I added the show() command the shell window was locked until I
closed the figures.

My question is: is there a way to open those windows in the background
without blocking the shell and without running it interactively??
something like gnuplot -persist?

Thanks all,
  Rodrigo Lopez-Negrete

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


Re: Idiom for running compiled python scripts?

2007-03-24 Thread Mark
On Sat, 24 Mar 2007 07:21:21 -0700, irstas wrote:
 A simple implementation that works:

Not quite irstas BTW ..

 import imp, sys, os
 c = sys.argv[1]
 if not os.path.exists(c + 'c') or os.stat(c).st_mtime  os.stat(c +
 'c').st_mtime:
 import compiler
 compiler.compileFile(c)
 del sys.argv[0]
 imp.load_compiled('__main__', c + 'c')

The above doesn't actually work for my test script. I have an atexit
call in the script which is deleting some temp files and I get the
following traceback on termination when run with the above:

Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File atexit.py, line 24, in _run_exitfuncs
func(*targs, **kargs)
  File /home/mark/bin/myscript.py, line 523, in delete
if files.tempdir:
AttributeError: 'NoneType' object has no attribute 'tempdir'
Error in sys.exitfunc:
Traceback (most recent call last):
  File /usr/lib/python2.4/atexit.py, line 24, in _run_exitfuncs
func(*targs, **kargs)
  File /home/mark/bin/myscript.py, line 523, in delete
if files.tempdir:
AttributeError: 'NoneType' object has no attribute 'tempdir'

The appropriate source code is:

At the start of main() ..

# Ensure all temp files deleted on exit
import atexit
atexit.register(files.delete)

and then from my class files:

@staticmethod
def delete():
'''Called to delete all temp files'''

if files.tempdir:
shutil.rmtree(files.tempdir)

Something about the environment is not quite the same. Any ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


Step value and function

2007-03-24 Thread [EMAIL PROTECTED]
Hi there. So I have a challenge in the Python book I am using (python
programming for the absolute beginner) that tells me to improve a
function, so that it can be called with a step value, and I havn't
been able to find out yet what's meant by a step value, but i'll keep
looking of course. I'd just be grateful if someone could illimunate
this for me.

Thanks in advance.

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


question about C extensions

2007-03-24 Thread Ralph Butler

Hi:
I have a question about extending python with C.  I have read the docs 
and done some googling, but come up short on this particular (small) 
problem.  I want to write a c extension to int.  In particular, I want 
to grab the memory for the int from an alternative heap.  I am confused 
about 2 things:  (1) Do I need to call the __init__ function for int 
itself, and if so, how do I do that?  (2)  Do I supply my own tp_alloc 
function to retrieve the memory for my new elements, and if so, what 
should it look like?  (Assume for the moment that I simply plan to do a 
malloc.)


I have attached code that does most of the work and has my initials 
(RMB) at a couple of the pieces of code I think I may need.


Any pointers to fairly specific examples would be appreciated.  I have 
found non-specific examples a bit confusing.


Thanks.
--ralph

from distutils.core import setup, Extension

setup (name = intext,
   version = 1.0,
   maintainer = rbutler,
   maintainer_email = [EMAIL PROTECTED],
   description = shared memory objects,
   ext_modules = [Extension('intext',sources=['intext.c'])]
)
#!/usr/bin/env python

# inherit from int

import intext

x = intext.INTEXT(44)
print type(x)
print x
print int(x) + 33
#include Python.h

static PyTypeObject *INTEXT_type_p;

#define PyINTEXT_Check(obj) ((obj)-ob_type == INTEXT_type_p)

typedef struct newtypeobjectstruct
{
PyObject_HEAD 
int *intextp;
} pyintext;

static PyObject *pyintext_tp_alloc(PyTypeObject *type, int nitems)
{
printf(tpalloc: nitems=%d\n,nitems);
// RMB: grab memory for the object
return (PyObject *) NULL;
}

static int pyintext_init(pyintext *self, PyObject *args)
{
int iv;

if ( ! PyArg_ParseTuple(args,i,iv))
return -1;
printf(init iv=%d\n,iv);
// RMB: invoke the super class __init__ ??
return 0;
}

static char INTEXT_type_doc[] = intext type doc;
PyTypeObject INTEXTType = {
PyObject_HEAD_INIT(PyType_Type) 0,  /* ob_size */
intext.INTEXT, /* tp_name */
sizeof(pyintext),/* tp_basicsize */
0,   /* tp_itemsize */
0,   /* tp_dealloc */
(printfunc) NULL,/* tp_print */
0,   /* tp_getattr*/
0,   /* tp_setattr */
0,   /* tp_compare */
0,   /* tp_repr */
0,   /* tp_as_number */
0,   /* tp_as_sequence */
0,   /* tp_as_mapping */
0,   /* tp_hash */
0,  /* tp_call */
0,  /* tp_str */
0,  /* tp_getattro */
0,  /* tp_setattro */
0,  /* tp_as_buffer */
Py_TPFLAGS_HAVE_CLASS,  /* tp_flags */
INTEXT_type_doc,/* tp_doc */
0,  /* tp_traverse */
0,  /* tp_clear */
0,  /* tp_richcompare */
0,  /* tp_weaklistoffset */
0,  /* tp_iter */
0,  /* tp_iternext */
0,  /* tp_methods */
0,  /* tp_members */
0,  /* tp_getset */
PyInt_Type,/* tp_base */
0,  /* tp_dict */
0,  /* tp_descr_get */
0,  /* tp_descr_set */
0,  /* tp_dictoffset */
(initproc) pyintext_init,   /* tp_init */
pyintext_tp_alloc,  /* tp_alloc */
PyType_GenericNew,  /* tp_new */
0,  /* tp_free */
0,  /* tp_is_gc */
};

static char intext_module_doc[] = intext module doc;
static struct PyMethodDef intext_module_methods[] = {
{NULL, NULL, 0, NULL}
};

void initintext(void)
{
PyObject *m;
/* Create the module and add the functions */
INTEXT_type_p = INTEXTType;
INTEXTType.ob_type = PyType_Type;
  
if (PyType_Ready(INTEXT_type_p)  0)
  return;
  
m = Py_InitModule3(intext,intext_module_methods,intext_module_doc);
if (!m)
{
printf(Py_InitModule3 failed\n);
return;
}
  
Py_INCREF(INTEXT_type_p);
PyModule_AddObject(m, INTEXT, (PyObject *)  INTEXTType);
}
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Anyone know of a MICR parser algorithm written in Python?

2007-03-24 Thread mkppk
On Mar 24, 4:55 pm, Paul McGuire [EMAIL PROTECTED] wrote:
 On Mar 24, 2:05 pm, mkppk [EMAIL PROTECTED] wrote:



  MICR = The line of digits printed using magnetic ink at the bottom of
  a check.

  Does anyone know of a Python function that has been written to parse a
  line of MICR data?
  Or, some financial package that may contain such a thing?
  Or, in general, where I should be looking when looking for a piece of
  Python code that may have already been written by someone?

  I'm working on a project that involves a check scanner the produces
  the raw MICR line as text.

  Now, that raw MICR needs to be parsed for the various pieces of info.
  The problem with MICR is that there is no standard layout. There are
  some general rules for item placement, but beyond that it is up to the
  individual banks to define how they choose to position the
  information.

  I did find an old C program written by someone at IBM... But I've read
  it and it is Not code that would nicely convert to Python (maybe its
  all the Python I'm used to, be it seems very poorly written).

  Here is the link to that C 
  code:ftp://ftp.software.ibm.com/software/retail/poseng/4610/4610micr.zip

  I've even tried using boost to generate a Python module, but that
  didn't go well, and in the end is not going to be a solution for me
  anyway.. really need access to the Python source.

  Any help at all would be appreciated,

  -mkp

 Is there a spec somewhere for this data?  Googling for MICR data
 format specification and similar gives links to specifications for
 the MICR character *fonts*, but not for the data content.

 And you are right, reverse-engineering this code is more than a 10-
 minute exercise.  (However, the zip file *does* include a nice set of
 test cases, which might be better than the C code as a starting point
 for new code.)

 -- Paul


Well, the problem is that the specification is that there is no
specification, thats just the way the MICR data line has evolved in
the banking industry unfortunately for us developers.. That being
said, there are obviusly enough banking companies out that with enough
example data to have intelligent parsers that handle all the
variations. And the C program appears to have all that built into it.

Its just that I would rather not reinvent the wheel (or read old C
code)..

So, the search continues..

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


Re: qt ver. 3, linux, windows, and modal forms

2007-03-24 Thread Mike
Answers interspersed.

David Boddie wrote:
 On Saturday 24 March 2007 23:08, Mike wrote:
 
 I'm having a problem with modal forms on windows. I've written a very
 short test program, with a main window and a form called from the main
 window. The form is set to modal with form.setModal(1) before calling
 form.show().
 
 Is form an instance of a QWidget subclass or a QDialog subclass?
QDialog
 
 Have you tried calling form.exec_loop() instead of form.show()?
Yes
 
 All works as expected on Linux. The form is modal, not allowing the main
 window to received the focus. If I call the form from within itself, the
 topmost form is modal, and not of the previous forms will receive the
 focus until the topmost form is closed; then the next topmost is modal,
 and so on.
 
 This sounds like the desired behaviour.
 
 However, on Windows XP Pro (at work - don't use windows at home), the
 form is not modal. The main window will receive the focus with a mouse
 click even though the modal form is still on top.
 
 But this should show the same behaviour. I suspect that the use of show()
 rather than exec_loop() leads to the platform-specific behaviour you are
 seeing.
Tried both - didn't make any difference.
 
 The source code is identical on both OS's.

 Has anyone run into this before? Is there a fix? I haven't been able to
 find anything with google searches, and Trolltech's forums don't seem to
 have any entries addressing the problem, either.

 I have a progam that I'm writing for work using Qt and Python, which was
 like pulling teeth with our Microsoft oriented IT department, and I very
 much do not want to tell them that it's not going to work (modal forms
 are essential).
 
 Modal forms are quite commonplace, so they should work as you expect. If you
 above advice doesn't help, you'll need to supply some more information about
 the versions of Qt, PyQt, SIP and Python you are using.

I'll have to get back to you on that one. I'm at home now (weekend). 
Will get versions from work and let you know.
 
 David

Thanks so much,
Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Game Programming Challenge #4 -- theme voting has started!

2007-03-24 Thread Richard Jones
The next PyWeek game programming challenge starts next Sunday at 00:00UTC.
If you're interested, there's definitely still time to sign up to the
challenge.

   http://www.pyweek.org/

Theme voting has started. You may now log into (or sign up to ;) the PyWeek
website to lodge your vote for theme. The themes to choose from are:

  The only way is up 
  Underneath the radar 
  One way or another 
  Don't stop till you get enough 
  The final countdown 

Come along and join in the fun :)


   Richard

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


Re: Step value and function

2007-03-24 Thread James Stroud
[EMAIL PROTECTED] wrote:
 Hi there. So I have a challenge in the Python book I am using (python
 programming for the absolute beginner) that tells me to improve a
 function, so that it can be called with a step value, and I havn't
 been able to find out yet what's meant by a step value, but i'll keep
 looking of course. I'd just be grateful if someone could illimunate
 this for me.
 
 Thanks in advance.
 

Trivial and redundant examples, but you get the point:

def doit(start, stop):
   for i in range(start, stop):
 print i

def doit_step(start, stop, step):
   for i in range(start, stop, step):
 print i

At work:

py doit(2, 11)
2
3
4
5
6
7
8
9
10
py doit_step(2, 11, 2)
2
4
6
8
10
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: persistent plot windows

2007-03-24 Thread James Stroud
Rodrigo Lopez-Negrete wrote:
 Hi all,
 
 I'm trying to write a python script using plotting form pylab.
 Unfortunatelly I've encountered a problem. When I run the script via
 'python myscript.py' the plot windows open and close very quickly, or
 when I added the show() command the shell window was locked until I
 closed the figures.
 
 My question is: is there a way to open those windows in the background
 without blocking the shell and without running it interactively??
 something like gnuplot -persist?
 
 Thanks all,
   Rodrigo Lopez-Negrete
 

python whatever.py 


(Don't forget the ampersand!)

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


Re: persistent plot windows

2007-03-24 Thread Rodrigo Lopez-Negrete
Hi James,

Thanks for the answer, the ampersand only works if I use the show()
command at the end of my script. I guess that helps although I haven't
tested it with plotting subroutines.

cheers,
  Rodrigo

On Mar 24, 6:50 pm, James Stroud [EMAIL PROTECTED] wrote:
 Rodrigo Lopez-Negrete wrote:
  Hi all,

  I'm trying to write a python script using plotting form pylab.
  Unfortunatelly I've encountered a problem. When I run the script via
  'python myscript.py' the plot windows open and close very quickly, or

  when I added the show() command the shell window was locked until I
  closed the figures.

  My question is: is there a way to open those windows in the background
  without blocking the shell and without running it interactively??
  something like gnuplot -persist?

  Thanks all,
Rodrigo Lopez-Negrete

 python whatever.py 

 (Don't forget the ampersand!)

 James


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


Re: Idiom for running compiled python scripts?

2007-03-24 Thread Gabriel Genellina
En Sat, 24 Mar 2007 20:46:15 -0300, Mark [EMAIL PROTECTED] escribió:

 The above doesn't actually work for my test script. I have an atexit
 call in the script which is deleting some temp files and I get the
 following traceback on termination when run with the above:

 Error in atexit._run_exitfuncs:
 Traceback (most recent call last):
   File atexit.py, line 24, in _run_exitfuncs
 func(*targs, **kargs)
   File /home/mark/bin/myscript.py, line 523, in delete
 if files.tempdir:
 AttributeError: 'NoneType' object has no attribute 'tempdir'

I don't know exactly what happened so it doesn't work anymore (and it  
worked before) but script finalization is always a bit fragile. All values  
in all modules dictionaries (holding globals) are set to None (presumably  
to help garbage collection by breaking cycles). When your delete function  
is called, globals like shutil or files are already gone. A way to avoid  
this problem is to hold a reference to all required globals, so your  
delete function would become:

  @staticmethod
  def delete(files=files,rmtree=shutil.rmtree):
'''Called to delete all temp files'''
if files.tempdir:
rmtree(files.tempdir)

But I'm not sure if this is enough because rmtree relies on the os module  
to do its work.

-- 
Gabriel Genellina

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Michael Bentley
On Mar 24, 2007, at 12:30 PM, Robert Hicks wrote:
 I want to upgrade to 2.5 but I don't see any unistall instructions
 anywhere.

Don't uninstall it.

That's why Apple put python under /Library/Frameworks/ 
Python.framework/Versions.  So you can have multiple versions installed.

Hopefully you left Apple's default install of 2.3.5 unmolested as  
well.  My best advise is to download the binaries from python.org and  
install.  This gives you a nice universal framework build, compete  
with readline support.

If you do elect to build it yourself, just make sure to read the Mac  
specific documentation (which tells how to generate a framework  
build).  Whichever route you take, /usr/local/bin/python and /Library/ 
Frameworks/Python.framework/Versions/Current/bin/python will point to  
pyhon2.5.  Since you already have 2.4x I assume your path already  
contains /usr/local/bin -- otherwise, you'll probably keep picking up  
the default 2.3.5 in /usr/bin.

It looks like Stackless has a Mac binary install as well.  Does  
anybody here know if I can install that on top of a stock 2.5 without  
breaking things?

regards,
Michael

---
Simplicity is the ultimate sophistication.
   -Leonardo da Vinci



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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Michael Bentley

On Mar 24, 2007, at 12:55 PM, 7stud wrote:

 In addition, the download notes for the stand alone MacPython 2.5
 install say that there aren't as many modules for 2.5 as there are for
 the 2.4, which is something you may want to consider.

There aren't as many pre-built modules for 2.5 at the MacPython  
site.  That's not to say you can't easily build your own, mind you --  
assuming you've got developer tools installed.

regards,
Michael

---
A clever person solves a problem.
A wise person avoids it.
 -Albert Einstein




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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Michael Bentley
 No, the OSX version is like 2.3 something. I installed the 2.4.4
 version in /usr/local bypassing the Apple stuff.

Oh!  Well then:

---[cut here]---
# danger will robinson -- use at your own risk ;-)
rm /usr/local/bin/python*
rm -rf /usr/local/lib/python
---[snip]---

Is the uninstall program :-)

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


functions, classes, bound, unbound?

2007-03-24 Thread 7stud
Here is some example code that produces an error:

class Test(object):
def greet():
print Hello

t = Test()
t.greet()
TypeError: greet() takes no arguments (1 given)

Ok.  That makes sense.  t.greet() is a bound method, so something
automatically relays the instance object to greet(), and since greet()
is defined with no parameters--Error.

Hmmm...I know from testing several examples that if I call a function
that's defined inside a class, and I use the class name preceding the
function call, then I have to send the instance manually.  So, based
on that error message, I'll just call the method using the class name
and not send the instance object:

Test.greet()

TypeError: unbound method greet() must be called with Test instance as
first argument (got nothing instead)

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


Re: functions, classes, bound, unbound?

2007-03-24 Thread Felipe Almeida Lessa
On 24 Mar 2007 20:24:36 -0700, 7stud [EMAIL PROTECTED] wrote:
 Here is some example code that produces an error:
[snip]

Why do people absolutely *love* to do weird and ugly things with
Python? Contests apart, I don't see lots of people trying this kind of
things on other (common) languages.

Say with me: Python is powerful, but I'll use that power *only* for
beautiful and straightforward code.

Further reading:
http://www.python.org/doc/Humor.html#zen

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


Re: Idiom for running compiled python scripts?

2007-03-24 Thread Steven D'Aprano
On Sat, 24 Mar 2007 22:59:06 +, Mark wrote:

 I timed it against running plain .py and running .pyc directly. It
 seemed to be roughly on par with running .pyc directly, and about 18ms
 faster than running .py. The file had 600 lines (21kb) of code.
 
 So see my point at least? I'm still not sure why this approach is
 ill-favoured?

Because this is entirely a trivial saving. Who cares? Sheesh.

That's less than the natural variation in execution speed caused by (e.g.)
network events on your PC. I've just run the same do-nothing script (a
simple pass) three times, and got times of 338ms, 67ms and 74ms. That's
a variation of 271 milliseconds between runs of the same script, and you
care about 18ms???

Saving 18ms on a script that takes 50ms to execute *might* be worthwhile,
if you're using that script in an automated system that executes it
thousands of times. If you're calling it by hand, come on now, you're not
even going to notice the difference! 50ms is close enough to instantaneous
that 32ms is not detectably faster to the human eye.

If you save 18ms one thousand times a day, you save a grand total of ...
eighteen seconds. Wow. Now you can spend more time with your family.

As of 2005, the world's fastest typist Barbara Blackburn has been clocked
at a peak of 212 words per minute for short bursts. Assuming an average of
five key strokes per word (including the space) that's about 18 key
presses per second, or 55 milliseconds per key press. A more realistic
figure for the average professional typist is about six key presses per
second, or 160 milliseconds per key press, and that's for pure
transposition (copying). If you've got to think carefully about what
you're typing, like sys admins do, the average time per key press is
significantly larger.

In other words, unless you can save AT LEAST 160 milliseconds, it isn't
worth typing even one more character. If you have to type one extra
character to save 18ms, you're actually 140ms worse off.

I can't believe the number of people who are spending this amount of time
worrying about such a trivial saving, and I can't believe that I've let
myself be suckered into this discussion. Don't you people have lives???



-- 
Steven
who has no life, which is why he is spending time complaining about people
who have no lives.

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread 7stud
On Mar 24, 8:18 pm, Michael Bentley [EMAIL PROTECTED] wrote:
 On Mar 24, 2007, at 12:30 PM, Robert Hicks wrote:

  I want to upgrade to 2.5 but I don't see any unistall instructions
  anywhere.

 Don't uninstall it.

 That's why Apple put python under /Library/Frameworks/
 Python.framework/Versions.  So you can have multiple versions installed.


/Libary/Frameworks/ is an empty directory(except for . and ..) on my
Mac, and I have 2.3.5 installed somewhere.

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread 7stud
On Mar 24, 9:40 pm, 7stud [EMAIL PROTECTED] wrote:
 On Mar 24, 8:18 pm, Michael Bentley [EMAIL PROTECTED] wrote:

  On Mar 24, 2007, at 12:30 PM, Robert Hicks wrote:

   I want to upgrade to 2.5 but I don't see any unistall instructions
   anywhere.

  Don't uninstall it.

  That's why Apple put python under /Library/Frameworks/
  Python.framework/Versions.  So you can have multiple versions installed.

 /Libary/Frameworks/ is an empty directory(except for . and ..) on my
 Mac, and I have 2.3.5 installed somewhere.

I mean /Library/Frameworks

Misspelled it in the post, but not when I searched it.  I did an ls -
al on it and got this:

$ ls -al /Library/Frameworks
total 0
drwxrwxr-x2 root  admin68 Jul  1  2006 .
drwxrwxr-t   43 root  admin  1462 Feb 20 14:31 ..

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread js
The only way you can do is rermove python2.4.4's files manually.

I suggest you to use MacPorts or Fink.

With MacPort, you can uninstall python2.4 by doing
$ port uninstall python24

And Installation is
$ port install python25



On 24 Mar 2007 10:30:28 -0700, Robert Hicks [EMAIL PROTECTED] wrote:
 I want to upgrade to 2.5 but I don't see any unistall instructions
 anywhere.

 Robert

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

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


Re: functions, classes, bound, unbound?

2007-03-24 Thread Steven D'Aprano
On Sat, 24 Mar 2007 20:24:36 -0700, 7stud wrote:

 Here is some example code that produces an error:
 
 class Test(object):
 def greet():
 print Hello
 
 t = Test()
 t.greet()
 TypeError: greet() takes no arguments (1 given)
 
 Ok.  That makes sense.  t.greet() is a bound method, so something
 automatically relays the instance object to greet(), and since greet()
 is defined with no parameters--Error.
 
 Hmmm...I know from testing several examples that if I call a function
 that's defined inside a class, and I use the class name preceding the
 function call, then I have to send the instance manually.  So, based
 on that error message, I'll just call the method using the class name
 and not send the instance object:
 
 Test.greet()
 
 TypeError: unbound method greet() must be called with Test instance as
 first argument (got nothing instead)


Is there a question hidden there somewhere, or are you just reporting on a
fact you have learned and are excited about?


Instance methods always need a self parameter, even if you call them from
the class. That's why you have to provide the instance by hand if you call
them from the class.

If you are trying to create a method that doesn't take a self argument,
have a look at the staticmethod function. There's also a classmethod
function as well.



-- 
Steven.

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


Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Alex Martelli
7stud [EMAIL PROTECTED] wrote:

 On Mar 24, 9:40 pm, 7stud [EMAIL PROTECTED] wrote:
  On Mar 24, 8:18 pm, Michael Bentley [EMAIL PROTECTED] wrote:
 
   On Mar 24, 2007, at 12:30 PM, Robert Hicks wrote:
 
I want to upgrade to 2.5 but I don't see any unistall instructions
anywhere.
 
   Don't uninstall it.
 
   That's why Apple put python under /Library/Frameworks/
   Python.framework/Versions.  So you can have multiple versions installed.
 
  /Libary/Frameworks/ is an empty directory(except for . and ..) on my
  Mac, and I have 2.3.5 installed somewhere.
 
 I mean /Library/Frameworks
 
 Misspelled it in the post, but not when I searched it.  I did an ls -
 al on it and got this:
 
 $ ls -al /Library/Frameworks
 total 0
 drwxrwxr-x2 root  admin68 Jul  1  2006 .
 drwxrwxr-t   43 root  admin  1462 Feb 20 14:31 ..

Try /System/Library/Frameworks ...


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


Using remote source code

2007-03-24 Thread pyapplico
Is there any possible way that I can place a .py file on the internet,
and use that source code in an .py file on my computer?

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


Re: functions, classes, bound, unbound?

2007-03-24 Thread Steven Bethard
7stud wrote:
 Here is some example code that produces an error:
 
 class Test(object):
 def greet():
 print Hello
 
 t = Test()
 t.greet()
 TypeError: greet() takes no arguments (1 given)
[snip]
 Test.greet()
 
 TypeError: unbound method greet() must be called with Test instance as
 first argument (got nothing instead)

Methods in a class are generally expected to take an instance as their 
first argument, but your greet() method takes no arguments.  This is 
because classes don't invoke the function directly, they convert it to 
an 'unbound method' object::

  class Test(object):
 ... def greet():
 ... print 'Hello'
 ...
  Test.greet
 unbound method Test.greet
  Test.greet()
 Traceback (most recent call last):
   File interactive input, line 1, in module
 TypeError: unbound method greet() must be called with Test instance
 as first argument (got nothing instead)

If you really want to get to the original function, there are a couple 
of options.  You can go through the class's __dict__, or you can wrap 
your method with a @staticmethod decorator (which tells the class not to 
wrap the function when you try to use it)::

  Test.__dict__['greet']
 function greet at 0x00E708B0
  Test.__dict__['greet']()
 Hello
  class Test(object):
 ... @staticmethod
 ... def greet():
 ... print 'Hello'
 ...
  Test.greet
 function greet at 0x00E7D2F0
  Test.greet()
 Hello

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


Re: question about C extensions

2007-03-24 Thread Ralph Butler
I think I may have figured all this out by looking at examples in the 
python source, e.g. xxsubtype.c etc.  Nonetheless, I would appreciate 
any extra info others might provide.
Thanks again.
--ralph

Ralph Butler wrote:
 Hi:
 I have a question about extending python with C.  I have read the docs 
 and done some googling, but come up short on this particular (small) 
 problem.  I want to write a c extension to int.  In particular, I want 
 to grab the memory for the int from an alternative heap.  I am confused 
 about 2 things:  (1) Do I need to call the __init__ function for int 
 itself, and if so, how do I do that?  (2)  Do I supply my own tp_alloc 
 function to retrieve the memory for my new elements, and if so, what 
 should it look like?  (Assume for the moment that I simply plan to do a 
 malloc.)
 
 I have attached code that does most of the work and has my initials 
 (RMB) at a couple of the pieces of code I think I may need.
 
 Any pointers to fairly specific examples would be appreciated.  I have 
 found non-specific examples a bit confusing.
 
 Thanks.
 --ralph
 
 
 
 
 from distutils.core import setup, Extension
 
 setup (name = intext,
version = 1.0,
maintainer = rbutler,
maintainer_email = [EMAIL PROTECTED],
description = shared memory objects,
ext_modules = [Extension('intext',sources=['intext.c'])]
 )
 
 
 
 
 #!/usr/bin/env python
 
 # inherit from int
 
 import intext
 
 x = intext.INTEXT(44)
 print type(x)
 print x
 print int(x) + 33
 
 
 
 
 #include Python.h
 
 static PyTypeObject *INTEXT_type_p;
 
 #define PyINTEXT_Check(obj) ((obj)-ob_type == INTEXT_type_p)
 
 typedef struct newtypeobjectstruct
 {
 PyObject_HEAD 
 int *intextp;
 } pyintext;
 
 static PyObject *pyintext_tp_alloc(PyTypeObject *type, int nitems)
 {
 printf(tpalloc: nitems=%d\n,nitems);
 // RMB: grab memory for the object
 return (PyObject *) NULL;
 }
 
 static int pyintext_init(pyintext *self, PyObject *args)
 {
 int iv;
 
 if ( ! PyArg_ParseTuple(args,i,iv))
   return -1;
 printf(init iv=%d\n,iv);
 // RMB: invoke the super class __init__ ??
 return 0;
 }
 
 static char INTEXT_type_doc[] = intext type doc;
 PyTypeObject INTEXTType = {
 PyObject_HEAD_INIT(PyType_Type) 0,  /* ob_size */
 intext.INTEXT, /* tp_name */
 sizeof(pyintext),/* tp_basicsize */
 0,   /* tp_itemsize */
 0,   /* tp_dealloc */
 (printfunc) NULL,/* tp_print */
 0,   /* tp_getattr*/
 0,   /* tp_setattr */
 0,   /* tp_compare */
 0,   /* tp_repr */
 0,   /* tp_as_number */
 0,   /* tp_as_sequence */
 0,   /* tp_as_mapping */
 0,   /* tp_hash */
 0,  /* tp_call */
 0,  /* tp_str */
 0,  /* tp_getattro */
 0,  /* tp_setattro */
 0,  /* tp_as_buffer */
 Py_TPFLAGS_HAVE_CLASS,  /* tp_flags */
 INTEXT_type_doc,/* tp_doc */
 0,  /* tp_traverse */
 0,  /* tp_clear */
 0,  /* tp_richcompare */
 0,  /* tp_weaklistoffset */
 0,  /* tp_iter */
 0,  /* tp_iternext */
 0,  /* tp_methods */
 0,  /* tp_members */
 0,  /* tp_getset */
 PyInt_Type,/* tp_base */
 0,  /* tp_dict */
 0,  /* tp_descr_get */
 0,  /* tp_descr_set */
 0,  /* tp_dictoffset */
 (initproc) pyintext_init,   /* tp_init */
 pyintext_tp_alloc,  /* tp_alloc */
 PyType_GenericNew,  /* tp_new */
 0,  /* tp_free */
 0,  /* tp_is_gc */
 };
 
 static char intext_module_doc[] = intext module doc;
 static struct PyMethodDef intext_module_methods[] = {
 {NULL, NULL, 0, NULL}
 };
 
 void initintext(void)
 {
 PyObject *m;
 /* Create the module and add the functions */
 INTEXT_type_p = INTEXTType;
 INTEXTType.ob_type = PyType_Type;
   
 if (PyType_Ready(INTEXT_type_p)  0)
   return;
   
 m = 

  1   2   >