Re: Exec Statement Question

2007-04-08 Thread Gabriel Genellina
7stud wrote:
> On Apr 8, 11:31 pm, "Gregory Piñero" <[EMAIL PROTECTED]> wrote:
> > Is there a way to call exec such that it won't have access to any more
> > objects than I explicitly give it?
>
> I think the way it works is that when the def is parsed, a function
> object is created and assigned to the name func1.  When the function
> object is created, d is "bound" to the global value 3, while a,b,c lie
> in wait for arguments to land in their gullets like venus fly traps.
> Your dictionary has a key whose value is a reference to the function
> object, which already has the value 3 bound to d.

Not exactly. As Georg Brandl said, the function has a reference to the
*globals* currently in use when it was defined, not directly to the
name "d".

To the OP: If you want a function with almost "empty" globals, compile
it the same way you used to execute it:

>>> text = """def func1(a):
...   print a
...   print b
...
... func1(3)
... print func1.func_globals.keys()
... """
>>>
>>> exec text in {}
3
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 5, in ?
  File "", line 3, in func1
NameError: global name 'b' is not defined
>>> exec text in {"b": 123}
3
123
['__builtins__', 'func1', 'b']
>>>

I said *almost* empty because Python may insert other keys into the
globals, like __builtins__ above (see http://docs.python.org/ref/exec.html)

--
Gabriel Genellina

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


Re: Exec Statement Question

2007-04-08 Thread Alex Martelli
Gregory Piñero <[EMAIL PROTECTED]> wrote:

> I'm curious why this code isn't working how I expect it to:
> 
> import sys
> d=3
> 
> def func1(a,b,c):
> print a,b,c,d
> print sys.path
> 
> exec "func1(1,2,3)" in {'func1':func1}
> 
> 
> returns:
> 1 2 3 3
> [ sys.path stuff ]
> 
> Since I'm telling exec to operate only within the context of the
> dictionary I give it, why does it still see sys.path and d?  I figured
> it would throw a NameError.
> 
> Is there a way to call exec such that it won't have access to any more
> objects than I explicitly give it?

func1 accesses its globals through func1.func_globals (which you can't
reassign -- it's a read-only attribute).

You may make a new function object w/ a different globals dict...:

>>> g = type(func1)(func1.func_code, {})

and that will fail (even when called directly, but similarly if exec'd)
as it's missing key 'd' in its globals:

>>> g(1, 2, 3)
1 2 3
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in func1
NameError: global name 'd' is not defined


The globals dict you pass to exec is the globals at the time of CALL,
not the globals seen from INSIDE func1; that's always going to be the
func_globals attribute of the function object, so you need to control
that (by suitably building a new function object as you require).


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


Re: Exec Statement Question

2007-04-08 Thread 7stud
On Apr 8, 11:31 pm, "Gregory Piñero" <[EMAIL PROTECTED]> wrote:
> I'm curious why this code isn't working how I expect it to:
>
> import sys
> d=3
>
> def func1(a,b,c):
> print a,b,c,d
> print sys.path
>
> exec "func1(1,2,3)" in {'func1':func1}
>
> 
> returns:
> 1 2 3 3
> [ sys.path stuff ]
>
> Since I'm telling exec to operate only within the context of the
> dictionary I give it, why does it still see sys.path and d?  I figured
> it would throw a NameError.
>
> Is there a way to call exec such that it won't have access to any more
> objects than I explicitly give it?
>
> Thanks,
>
> Greg

I think the way it works is that when the def is parsed, a function
object is created and assigned to the name func1.  When the function
object is created, d is "bound" to the global value 3, while a,b,c lie
in wait for arguments to land in their gullets like venus fly traps.
Your dictionary has a key whose value is a reference to the function
object, which already has the value 3 bound to d.


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


Re: Exec Statement Question

2007-04-08 Thread Georg Brandl
Gregory Piñero schrieb:
> I'm curious why this code isn't working how I expect it to:
> 
> import sys
> d=3
> 
> def func1(a,b,c):
> print a,b,c,d
> print sys.path
> 
> exec "func1(1,2,3)" in {'func1':func1}
> 
> 
> returns:
> 1 2 3 3
> [ sys.path stuff ]
> 
> Since I'm telling exec to operate only within the context of the
> dictionary I give it, why does it still see sys.path and d?  I figured
> it would throw a NameError.
> 
> Is there a way to call exec such that it won't have access to any more
> objects than I explicitly give it?

The function f has a func_globals attribute which points to the globals it
will use for execution. This is of course set at definition time so that
functions from, e.g., another module, have the globals of that module available.

Georg

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


Re: Crypto Suggestion/Help

2007-04-08 Thread Thomas Krüger
Jimmy E Touma schrieb:
> I need some advise on doing the following. I have a Linux application
> that allows users to access it via a code (password). At the end of the
> day, I gather a log of activities of the users and zip the file and
> would like to encrypt it so that the users can not access it or tamper
> with it. Only manager should. If I use a private/public key for doing so
> I have to store the private key on my computer. What is a good way to
> encrypt a file and have the key well hidden on the same computer? If you
> have any other way to do, like MD5 or similar, please let me know.

You don't need encryption, cryptographic hashes or Python. What you need
are just the basic UNIX/Linux permissions.

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


Weekly Python Patch/Bug Summary

2007-04-08 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  349 open ( +7) /  3737 closed (+25) /  4086 total (+32)
Bugs:  939 open (-12) /  6648 closed (+60) /  7587 total (+48)
RFE :  249 open ( -8) /   278 closed (+12) /   527 total ( +4)

New / Reopened Patches
__

Python 2.5 "What's New" document contains socket errors  (2007-03-17)
CLOSED http://python.org/sf/1682878  opened by  Jp Calderone

ConfigParser support for alt delimiters  (2007-03-18)
   http://python.org/sf/1682942  opened by  Stephen Hansen

Demo/parser/unparse.py fixes and cleanups  (2007-03-19)
CLOSED http://python.org/sf/1683328  opened by  Piet Delport

Refactor test_minidom.py to use unittest.  (2007-03-18)
CLOSED http://python.org/sf/1683397  opened by  Jerry Seutter

PEP 361 Warnings  (2007-03-19)
   http://python.org/sf/1683908  opened by  Adam Olsen

add os.chflags() and os.lchflags() where available  (2006-05-17)
   http://python.org/sf/1490190  reopened by  nnorwitz

Documentation for C-API string functions  (2007-03-21)
CLOSED http://python.org/sf/1684834  opened by  Björn Lindqvist

cgi.py invalid REQUEST_METHOD set  (2005-03-08)
CLOSED http://python.org/sf/1159139  reopened by  joesalmeri

new function: os.path.relpath  (2005-10-27)
CLOSED http://python.org/sf/1339796  reopened by  loewis

MSVCCompiler creates redundant and long PATH strings  (2007-03-21)
CLOSED http://python.org/sf/1685563  opened by  Scott Dial

Add IllegalStateError  (2007-03-22)
   http://python.org/sf/1685642  opened by  Björn Lindqvist

Method cache  (2007-03-22)
   http://python.org/sf/1685986  opened by  Armin Rigo

More PEP 3116 classes  (2007-03-22)
CLOSED http://python.org/sf/1686273  opened by  Mark Russell

int to Py_ssize_t changes  (2007-03-22)
CLOSED http://python.org/sf/1686451  opened by  Alexander Belopolsky

Allow any mapping after ** in calls  (2007-03-22)
   http://python.org/sf/1686487  opened by  Alexander Belopolsky

extending os.walk to support following symlinks  (2005-08-26)
CLOSED http://python.org/sf/1273829  reopened by  loewis

Replace time_t by Py_time_t  (2007-03-27)
   http://python.org/sf/1689402  opened by  Christian Heimes

Refactor test_sax.py to use unittest.  (2007-03-28)
CLOSED http://python.org/sf/1690164  opened by  Jerry Seutter

Refactor test_pyexpat.py to use unittest.  (2007-03-28)
CLOSED http://python.org/sf/1690169  opened by  Jerry Seutter

Added support for custom readline functions  (2007-03-28)
   http://python.org/sf/1690201  opened by  Ben Timby

Don't block on Queue get/put when time is moved back  (2007-03-29)
   http://python.org/sf/1690578  opened by  xiaowen

Migrate test_minidom.py to unittest  (2007-03-30)
   http://python.org/sf/1691032  opened by  Jason Orendorff

Fix for bug #1283289  (2007-03-30)
   http://python.org/sf/1691070  opened by  Roger Upole

Move initial args assignment to BaseException.__new__  (2007-04-01)
   http://python.org/sf/1692335  opened by  ?iga Seilnacht

warnings.py gets filename wrong for eval/exec  (2007-04-01)
   http://python.org/sf/1692664  opened by  Adam Olsen

trace.py --ignore-module should accept module name list.  (2007-04-02)
   http://python.org/sf/1693149  opened by  Raghuram Devarakonda

Fix for duplicate "preferences" menu-OS X  (2007-04-02)
   http://python.org/sf/1693258  opened by  Kevin Walzer

tarfile bug when opening a file directly  (2007-04-05)
   http://python.org/sf/1695229  opened by  Arve Knudsen

Fix test_urllib on Windows buildbots  (2007-04-07)
   http://python.org/sf/1695862  opened by  Ziga Seilnacht

Remove redundant code in ntpath.walk()  (2007-04-08)
   http://python.org/sf/1696393  opened by  Michael Haggerty

Adding an index method to tuples  (2007-04-08)
   http://python.org/sf/1696444  opened by  Paul Boddie

Patches Closed
__

TypeError swallowing in UNPACK_SEQUENCE opcode  (2007-03-16)
   http://python.org/sf/1682205  closed by  gbrandl

Make PyComplex_AsCComplex use __complex__  (2007-03-07)
   http://python.org/sf/1675423  closed by  gbrandl

remove sys.exitfunc, rewrite atexit in C  (2007-03-14)
   http://python.org/sf/1680961  closed by  collinwinter

telnetlib option subnegotiation fix  (2003-01-07)
   http://python.org/sf/664020  closed by  gbrandl

telnetlib.py change to ease option handling.  (2006-07-10)
   http://python.org/sf/1520081  closed by  gbrandl

Python 2.5 "What's New" document contains socket errors  (2007-03-17)
   http://python.org/sf/1682878  closed by  gbrandl

PEP 3115 patch  (2007-03-14)
   http://python.org/sf/1681101  closed by  gvanrossum

Adding a testcase for the bug in find_longest_match  (2007-03-11)
   http://python.org/sf/1678339  closed by  gbrandl

Patch to add tempfile.SpooledTemporaryFile (for #415692)  (2007-01-07)
   http://python.org/sf/1630118  closed by  collinwinter

Demo/parser/unparse.py fixes and cleanups  (2007-03-19)
   http://pyth

Exec Statement Question

2007-04-08 Thread Gregory Piñero
I'm curious why this code isn't working how I expect it to:

import sys
d=3

def func1(a,b,c):
print a,b,c,d
print sys.path

exec "func1(1,2,3)" in {'func1':func1}


returns:
1 2 3 3
[ sys.path stuff ]

Since I'm telling exec to operate only within the context of the
dictionary I give it, why does it still see sys.path and d?  I figured
it would throw a NameError.

Is there a way to call exec such that it won't have access to any more
objects than I explicitly give it?

Thanks,

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


Re: tuples are useless???

2007-04-08 Thread James Stroud
Steven D'Aprano wrote:
> On Mon, 09 Apr 2007 02:26:37 +, James Stroud wrote:
> 
>> Bart Willems wrote:
>>> James Stroud wrote:
 ... It boils down to the fact that tuples are useless as a result 
 unless you know you really need them--and you never really NEED them.
>>> Could you clarify that for me? I use tuples *a lot* and I really *NEED* 
>>> them - I'm building a lot of multi-tier reports where detail-level data 
>>> is pulled out of a dictionary based on a composed key. It is impossible 
>>> to build those dictionaries *without* using tuples.
>>
>> "Impossible" is a strong word, as is "need" (especially when in all caps).
>>
>> py> import md5
>> py> class HashedList(list):
>> ...   def __hash__(self):
>> ... h = md5.new()
>> ... for item in self:
>> ...   h.update(str(hash(item)))
>> ... return int(h.hexdigest(), 16)
>> ...
>> py> hl = HashedList('bob', 'carol', 'ted')
>> py> {hl:3}
>> {['bob', 'carol', 'ted']: 3}
>>
>> Impossible? I wouldn't even say that this was all that difficult.
> 
> Possible, if by possible you mean "broken".
> 
> 
 D = {hl: 3}
 D
> {['bob', 'carol', 'ted']: 3}
 hl[0] = 'Bob'
 D
> {['Bob', 'carol', 'ted']: 3}
 D.keys()[0] is hl
> True
 D[hl]
> Traceback (most recent call last):
>   File "", line 1, in 
> KeyError: ['Bob', 'carol', 'ted']
> 
> 

   def __setitem__(self, *args):
 raise TypeError, '%s doesn't support item assignment.' % 
self.__class__.__name__


Problem fixed. Next?

By the way, this would be analagous to the tedious

class Something(object):
   def __init__(self, value):
 self._value = value
   value = property(lambda: self._value)

just to make sure users don't change the value of value so they don't 
"break" the instance.

I don't think Bart is changing the items in his keys anyway--so the 
problem which was stated as impossible is still possible. The solution 
was not to code to your personal expectations but to show how tuples are 
never essential. Any number of solutions could fix the problem you have 
invented.

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


Re: shelve error

2007-04-08 Thread Alex Martelli
7stud <[EMAIL PROTECTED]> wrote:
   ...
> In my opinion, the most valuable thing you could do for a next
> printing would be to expand the index to 3 times its current length.

Suggest that to O'Reilly: they're the one who prepare the index, not me;
I only get to point out errors I may notice on it during the roughly 4-5
days I get to review it in the late phases of production.

I don't believe any major change in the index can be contemplated
between one printing and another, but your complaint, if directed to the
appropriate ears, might possibly infuence some future edition.


> Also, the book is brand new, yet the cover has completely separated
> from the spine of the book, and now the cover is only attached to the
> first and last pages with a bit of glue.

Similarly, I have no control on any aspect of the physical production of
the book: again, telling me about your complaints is absolutely useless,
if you want any chance to have an effect, tell O'Reilly.


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


Re: shelve error

2007-04-08 Thread 7stud
> Discussion subject changed to "Python universal build, OSX 10.3.9 and 
> undefined symbols when
> linking" by David Pratt

What gives?  How come you can change the title of my thread?


On Apr 8, 8:14 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> But if you open an errata for the missing explanation for the different
> default value of the flag argument (use URL
> ), I'll be glad to
> fix it for the next printing...

In my opinion, the most valuable thing you could do for a next
printing would be to expand the index to 3 times its current length.
As it is now, I think the index is woefully inadequate, which I find
surprising for a reference book.  I haven't been able to find 3/4 of
the things I have looked up in the index.  For instance __get__(),
__set__(), and sorted() are nowhere to be found in the index.

Also, the book is brand new, yet the cover has completely separated
from the spine of the book, and now the cover is only attached to the
first and last pages with a bit of glue.

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


Re: python, wxpython and Mac OS X

2007-04-08 Thread 7stud
On Apr 8, 8:46 pm, Robert Kern <[EMAIL PROTECTED]> wrote:
> 7stud wrote:
>
> Why 2.4.4 instead of the official 2.5 binary fromwww.python.org?
>
>  http://www.python.org/download/
>

1) On some download page that listed both python 2.5 and 2.4, it said
that python 2.4 had more packages/modules available for Macs than 2.5.

2) The wxPython website says that to use wxPython on a Mac, you need a
special "framework" build of python--like the one that comes
preinstalled.  It says framework builds are available for python 2.4.

Should I remove 2.4.4 and install 2.5 instead?

>
> > Also, what wxPython download should I install?
>
> For 
> 2.4:http://prdownloads.sourceforge.net/wxpython/wxPython2.8-osx-unicode-2...
>
> For 
> 2.5:http://prdownloads.sourceforge.net/wxpython/wxPython2.8-osx-unicode-2...
>

Thanks.

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


Re: Crypto Suggestion/Help

2007-04-08 Thread Paul Rubin
Jimmy E Touma <[EMAIL PROTECTED]> writes:
> I need some advise on doing the following. I have a Linux application
> that allows users to access it via a code (password). At the end of the
> day, I gather a log of activities of the users and zip the file and
> would like to encrypt it so that the users can not access it or tamper
> with it. Only manager should. If I use a private/public key for doing so
> I have to store the private key on my computer. What is a good way to
> encrypt a file and have the key well hidden on the same computer? If you
> have any other way to do, like MD5 or similar, please let me know.

Are you saying you have a desktop app that's running on the user's own
machine and you're trying to prevent the user from getting at the log
data?  That is impossible if the user has control over the machine and
is willing and able to hack the software.  If you just want to make an
encrypted file that the user can't decrypt, use a public key on the
user's machine, and only have the secret key on the manager's machine.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples are useless???

2007-04-08 Thread Steven D'Aprano
On Mon, 09 Apr 2007 02:26:37 +, James Stroud wrote:

> Bart Willems wrote:
>> James Stroud wrote:
>>> ... It boils down to the fact that tuples are useless as a result 
>>> unless you know you really need them--and you never really NEED them.
>> 
>> Could you clarify that for me? I use tuples *a lot* and I really *NEED* 
>> them - I'm building a lot of multi-tier reports where detail-level data 
>> is pulled out of a dictionary based on a composed key. It is impossible 
>> to build those dictionaries *without* using tuples.
> 
> 
> "Impossible" is a strong word, as is "need" (especially when in all caps).
> 
> py> import md5
> py> class HashedList(list):
> ...   def __hash__(self):
> ... h = md5.new()
> ... for item in self:
> ...   h.update(str(hash(item)))
> ... return int(h.hexdigest(), 16)
> ...
> py> hl = HashedList('bob', 'carol', 'ted')
> py> {hl:3}
> {['bob', 'carol', 'ted']: 3}
> 
> Impossible? I wouldn't even say that this was all that difficult.

Possible, if by possible you mean "broken".


>>> D = {hl: 3}
>>> D
{['bob', 'carol', 'ted']: 3}
>>> hl[0] = 'Bob'
>>> D
{['Bob', 'carol', 'ted']: 3}
>>> D.keys()[0] is hl
True
>>> D[hl]
Traceback (most recent call last):
  File "", line 1, in 
KeyError: ['Bob', 'carol', 'ted']


-- 
Steven.

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


Re: Unicode problem

2007-04-08 Thread Martin v. Löwis
> Thanks! That's a nice little stumbling block for a newbie like me ;) Is 
> there a way to make utf-8 the default encoding for every string, so that 
> I do not have to encode each string explicitly?

You can make sys.stdout encode each string with UTF-8, with

sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

Make sure that you then that *all* strings that you print
are Unicode strings.

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


Crypto Suggestion/Help

2007-04-08 Thread Jimmy E Touma
Hi all,

I need some advise on doing the following. I have a Linux application
that allows users to access it via a code (password). At the end of the
day, I gather a log of activities of the users and zip the file and
would like to encrypt it so that the users can not access it or tamper
with it. Only manager should. If I use a private/public key for doing so
I have to store the private key on my computer. What is a good way to
encrypt a file and have the key well hidden on the same computer? If you
have any other way to do, like MD5 or similar, please let me know.


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


Python universal build, OSX 10.3.9 and undefined symbols when linking

2007-04-08 Thread David Pratt
Hi. I am on a PPC and have been getting the same undefined symbols 
traceback when linking applications after compiling. A few weeks back I 
posted on a problem to pythonmac-sig@python.org after attempting to 
build mod_python, today its pylucene - same problem. I initially 
shrugged off the problem with mod_python as likely an issue with the mac 
port.

Crazy thing is that I built the same version of pylucene successfully 
just before upgrading to universal build of 2.4.4 python for mac without 
problems. So I recompiled the same version of pylucene I had previously 
built with a PPC only build of python to evaluate whether my thoughts 
were right. I had a hunch universal python was causing my trouble with 
mod_python and a newer build of pylucene and it appears I was right. I 
am currently using Mac OSX 10.3.9 on a PPC with universal build of 
2.4.4. I should say that other than linking problem I am experiencing, 
the python functions as it should.

 From mod_python build:

ld: Undefined symbols:
_fstatvfs referenced from Python expected to be defined in libSystem
_lchown referenced from Python expected to be defined in libSystem
_statvfs referenced from Python expected to be defined in libSystem
apxs:Error: Command failed with rc=65536
.
make[1]: *** [mod_python.so] Error 1
make: *** [do_dso] Error 2

 From pylucene build:

ld: Undefined symbols:
_fstatvfs referenced from Python expected to be defined in libSystem
_lchown referenced from Python expected to be defined in libSystem
_statvfs referenced from Python expected to be defined in libSystem
gmake: *** [release/_PyLucene.so] Error 1

I have googled to see there have been others with this issue however 
they have tended to communicate about the problem on software lists or 
forums specific to the software they were attempting to build. I did not 
see this resolved in any case that I have read.

I am hoping someone may be able to advise a possible solution. I am 
planning on upgrading to OSX 10.4 within a week since mac is not making 
the JDK 1.5.0 available for OSX 10.3 users - so pretty much being forced 
into upgrading in any case.

If you had the same linking issue with the universal build of python it 
would be good to hear from you - better yet would be some way of solving 
this or at least understanding what may be going on. I have posted to 
pythonmac-sig@python.org in the interim but there is very little traffic 
on this list. In the meantime I thought there may other OSX 10.3.9 users 
out there who may have run into the same fate. Many thanks.

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


Re: python, wxpython and Mac OS X

2007-04-08 Thread Robert Kern
7stud wrote:
> Hi,
> 
> I'm using an intel imac which came with python 2.3.5 pre-intstalled on
> OS 10.4.7.  I was able run a hello world wxPython script in Terminal
> by typing:
> 
> $pythonw wxPythonTest.py
> 
> Yesterday, I installed python 2.4.4 which I downloaded from the
> MacPython website, and it seems to have installed correctly:

Why 2.4.4 instead of the official 2.5 binary from www.python.org?

  http://www.python.org/download/

> $python
> Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> 
> However, now when I try to run my hello world wxPython script in
> Terminal, I get the error message:
> 
> Traceback (most recent call last):
>   File "wxPythonTest.py", line 1, in ?
> import wx
> ImportError: No module named wx
> 
> Does that mean I need to install a newer version of wxPython? 

The packages that are installed (or you might install) for Python 2.3 are
entirely separate from those that you would install for Python 2.4. It's not
that you need a newer version of wxPython; it's that you need to install one for
Python 2.4 period.

> Also, what wxPython download should I install?

For 2.4:
http://prdownloads.sourceforge.net/wxpython/wxPython2.8-osx-unicode-2.8.3.0-universal10.4-py2.4.dmg

For 2.5:
http://prdownloads.sourceforge.net/wxpython/wxPython2.8-osx-unicode-2.8.3.0-universal10.4-py2.5.dmg

-- 
Robert Kern

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

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


Re: Why NOT only one class per file?

2007-04-08 Thread Chris Lasher
On Apr 4, 5:23 pm, "Chris Lasher" <[EMAIL PROTECTED]> wrote:
> A friend of mine with a programming background in Java and Perl places
> each class in its own separate file in . I informed him that keeping
> all related classes together in a single file is more in the Python
> idiom than one file per class. He asked why, and frankly, his valid
> question has me flummoxed.
>
> [snip]
>
> Thoughts, comments, and insight much appreciated,
> Chris

Thanks to all who replied and made this a very interesting and
informative discussion! It gave my friend, and myself, plenty to think
about.

Much appreciated,
Chris

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


python, wxpython and Mac OS X

2007-04-08 Thread 7stud
Hi,

I'm using an intel imac which came with python 2.3.5 pre-intstalled on
OS 10.4.7.  I was able run a hello world wxPython script in Terminal
by typing:

$pythonw wxPythonTest.py

Yesterday, I installed python 2.4.4 which I downloaded from the
MacPython website, and it seems to have installed correctly:

$python
Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

However, now when I try to run my hello world wxPython script in
Terminal, I get the error message:

Traceback (most recent call last):
  File "wxPythonTest.py", line 1, in ?
import wx
ImportError: No module named wx

Does that mean I need to install a newer version of wxPython?  If so,
I'm not sure how to proceed.  The wxPython download page says:
-
The Max OSX version of wxPython is distributed as a set of mountable
disk images. The runtime verisons contain Installer packages, as well
as a script that can perform an uninstall of previous installs of
wxPython. (NOTE: If you have versions prior to 2.5.3.1 installed
please do run the uninstaller to remove the older version.)
--
I looked around in Finder, but I can't tell what version of wxPython
that came pre-installed on my imac, so I am not sure whether I need to
uninstall it.

Also, what wxPython download should I install?

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


Re: tuples are useless???

2007-04-08 Thread James Stroud
Bart Willems wrote:
> James Stroud wrote:
>> ... It boils down to the fact that tuples are useless as a result 
>> unless you know you really need them--and you never really NEED them.
> 
> Could you clarify that for me? I use tuples *a lot* and I really *NEED* 
> them - I'm building a lot of multi-tier reports where detail-level data 
> is pulled out of a dictionary based on a composed key. It is impossible 
> to build those dictionaries *without* using tuples.


"Impossible" is a strong word, as is "need" (especially when in all caps).

py> import md5
py> class HashedList(list):
...   def __hash__(self):
... h = md5.new()
... for item in self:
...   h.update(str(hash(item)))
... return int(h.hexdigest(), 16)
...
py> hl = HashedList('bob', 'carol', 'ted')
py> {hl:3}
{['bob', 'carol', 'ted']: 3}

Impossible? I wouldn't even say that this was all that difficult.

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


Re: shelve error

2007-04-08 Thread Alex Martelli
7stud <[EMAIL PROTECTED]> wrote:

> On Apr 4, 10:22 pm, [EMAIL PROTECTED] wrote:
> > how did you generate aaa.txt?
> 
> Ok, I got it to work by supplying a filename that didn't previously
> exist.  Neither the book I am reading, "Beginning Python: From Novice
> to Professional" nor the book I am using as a reference, "Python in
> Nutshell", happens to mention that important fact.

I notice that the Nutshell (2nd ed) has a small errata that may be
what's confusing you. On p. 284, under "The shelve module", I say:

shelve supplies a function open that is polymorphic to anydbm.open .

On p. 286, you find the whole page explaining anydbm.open (which is why
I didn't want to duplicate all that info), including the detail that the
default value for argument flag is 'r' (meaning read-only operation, and
on a file that must already exist).  However, shelve.open is not
_entirely_ polymorphic to anydbm.open, in this small but crucial detail:
the defaulf value for argument flag is 'c' (meaning, as p. 286 correctly
says, that it creates a new file if it doesn't exist, but also accepts
and opens an existing file, and operation is read-write).

Of course, if the existing file was not created by the shelve module,
there may well be errors -- shelve uses DBM-like archive files, as
clearly explained on p. 284, not arbitrary text files (nor for that
matter arbitrary binary files).  As the documentation for anydbm.open
explicitly says, it's all about DBM files; adding "will not work right
if you try to open just any random textfile or other file you may happen
to have laying around on your favourite storage device" would be
insulting to the reader and a waste of space, so I don't consider it a
valid errata.

But if you open an errata for the missing explanation for the different
default value of the flag argument (use URL
), I'll be glad to
fix it for the next printing, changing the previously quoted sentence
to:

shelve supplies a function open that is polymorphic to anydbm.open
(except that the default value of argument flag is 'c' rather than 'n').


BTW, if you DO want to call shelve.open on a path f that may correspond
to an arbitrary existing file (and want to toss away the previous
contents of that file, if any) the correct way to call is then:

  s = shelve.open(whatever_path, 'n')

since 'n' truncates an existing file, or creates a new one, as needed.

That is also shown in the code example for module shelve in the Nutshell
(the 'n' occurs just at the top of p. 285).


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


Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread Alex Martelli
Lorenzo <[EMAIL PROTECTED]> wrote:
   ...
> > >  elapsedTime = mydata[1]
> > >  index = elapsedTime.find("real")
> > >  # the index will have a value 0f 110
> > >  totaltime = elapsedTime[index:]
   ...
> Oops! I sent the wrong piece of code. The above is actually the work 
> around which actually works. The bad code is this:
> index  = mydata[0].find("real")
> elapsedTime = mydata[0][index:]

The only difference is that in the "workaround that works" you're
mungling mydata[1], in the "bad code" mydata[0].  If you print or
otherwise emit the value of index in each case, I think the cause of
your problem will become clear (and it will probably be a value of index
that's -1 for the "failing" case, and >= 0 for the "working" case, as
other posts on this thread have already suggested).

No connection can exist between your problem, and the string being "held
in a tuple" or held in any other fashion.


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


Re: tuples, index method, Python's design

2007-04-08 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> I think the problem is that Python developers are split between those who
> see tuples as immutable lists, and those who see them as records/structs.

I think the construction

   def f(*a): ...

shows that the "immutable list" interpretation is firmly ensconced in
the language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2007-04-08 Thread Steven D'Aprano
On Sun, 08 Apr 2007 20:10:21 -0400, Carsten Haese wrote:

> On Sun, 2007-04-08 at 13:10 -0700, Paul Rubin wrote:
>> Carsten Haese <[EMAIL PROTECTED]> writes:
>> > > Do you not see the gratuituous inconsistency between tuples and lists
>> > > as a useless feature?  What is the use case for keeping it?
>> > 
>> > When a new feature is requested, the burden of proof is on the requester
>> > to show that it has uses. The use case for not having tuple.index is
>> > that there are no use cases for having it. If that answer sounds absurd,
>> > it is because your question is absurd.
>> 
>> The use case has already been discussed.  Removing the pointless
>> inconsistency between lists and tuples means you can stop having to
>> remember it, so you can free up brain cells for implementing useful
>> things.  That increases your programming productivity.
> 
> Will tuples also get a sort method? What about append and extend? pop?
> __iadd__? __delslice__?

Since tuples are immutable, no.

And before you ask, since they aren't strings, they won't get upper,
lower, split or strip either.

 
> How many brain cells are actually freed up by not having to remember
> that *one* method that you'd never use doesn't exist?

74,972,561.


I think the problem is that Python developers are split between those who
see tuples as immutable lists, and those who see them as records/structs.
Neither of them is wrong -- tuples are multi-use. Guido may or may not
have designed them to be used as structs (short and heterogeneous, as
opposed to long and homogeneous) but designers are often surprised by the
uses people find for their creations, and the designer doesn't get the
final say as to what is the "right" usage.

If you see tuples as an immutable list, having an index method is quite
useful. If you see them as structs, an index method is useless.



-- 
Steven.

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


Re: Why does not my wx.html.HtmlWindow work?

2007-04-08 Thread [EMAIL PROTECTED]
On Apr 9, 1:01 am, Rob Williscroft <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote innews:[EMAIL PROTECTED]
> comp.lang.python:
>
>
>
> > Below are my source code:
>
> > import wx
> > import wx.html
>
> > class MyHtmlFrame(wx.Frame):
>
> > def __init__(self, parent, title):
> > wx.Frame.__init__(self, parent, -1, title, size=(600,400))
> > html = wx.html.HtmlWindow (self)
> > if "gtk2" in wx.PlatformInfo:
> > html.SetStandardFonts()
> > html.LoadPage("
> >http://www.pythonthreads.com/articles/python/incorporating-into
> > -wxpython-part-1.html")
>
> > app = wx.PySimpleApp()
> > frm = MyHtmlFrame(None, "Simple HTML Browser")
> > frm.Show()
> > app.MainLoop()
>
> > It is just an example in the book "wxPython in action". But every time
> > when I try to get it run, my CPU is fully occupied, and there is no
> > frame that comes into existence. Why?
>
> I think your problem is that you call LoadPage before app.MainLoop() is
> called, IOW you need to call LoadPage in an event handler:
>
> import wx
> import wx.html
>
> class MyHtmlFrame(wx.Frame):
>
> HOME = "http://www.google.co.uk";
>
> def __init__(self, parent, title):
> wx.Frame.__init__(self, parent, -1, title, size=(600,400))
> self.html = wx.html.HtmlWindow (self)
> if "gtk2" in wx.PlatformInfo:
> self.html.SetStandardFonts()
> self.done_show = False
> wx.EVT_IDLE( self, self.OnShow )
> self.html.SetPage(
> "Loading ..." % self.HOME
>   )
>
> def OnShow( self, event ):
> if self.done_show:
>   return
> self.done_show = True
> self.html.LoadPage( self.HOME )
>
> app = wx.PySimpleApp()
> frm = MyHtmlFrame(None, "Simple HTML Browser")
> frm.Show()
> app.MainLoop()
>
> Note: the URL you loading takes ages to show, which is why I
> use:http://www.google.co.ukabove.
>
> Rob.
> --http://www.victim-prime.dsl.pipex.com/


To Rob Williscroft,

It works when I call LoadPage() in any event handler, though I don't
know the reason. I'll try to learn it.
Thank you.
And the example in the book "wxPython In Action" is wrong?

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


Re: tuples, index method, Python's design

2007-04-08 Thread Paul Rubin
Carsten Haese <[EMAIL PROTECTED]> writes:
> Will tuples also get a sort method? What about append and extend? pop?
> __iadd__? __delslice__?

They are immutable so they won't get .sort() etc.  sorted(...) already
works on them.

> How many brain cells are actually freed up by not having to remember
> that *one* method that you'd never use doesn't exist?

I dunno but I do know that Ruby is attracting a lot of potential Python
users because it apparently has fewer of these inconsistencies.  A big
web site I hang out on decided to do a software rewrite (currently using
a huge perl script) and evaluated a bunch of possible approaches.  In
the final decision, Ruby/Rails won out over Python/Django.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2007-04-08 Thread Carsten Haese
On Sun, 2007-04-08 at 13:10 -0700, Paul Rubin wrote:
> Carsten Haese <[EMAIL PROTECTED]> writes:
> > > Do you not see the gratuituous inconsistency between tuples and lists
> > > as a useless feature?  What is the use case for keeping it?
> > 
> > When a new feature is requested, the burden of proof is on the requester
> > to show that it has uses. The use case for not having tuple.index is
> > that there are no use cases for having it. If that answer sounds absurd,
> > it is because your question is absurd.
> 
> The use case has already been discussed.  Removing the pointless
> inconsistency between lists and tuples means you can stop having to
> remember it, so you can free up brain cells for implementing useful
> things.  That increases your programming productivity.

Will tuples also get a sort method? What about append and extend? pop?
__iadd__? __delslice__?

How many brain cells are actually freed up by not having to remember
that *one* method that you'd never use doesn't exist?

-Carsten


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


Re: how to remove multiple occurrences of a string within a list?

2007-04-08 Thread Paul McGuire
On Apr 3, 3:47 pm, [EMAIL PROTECTED] wrote:
> Beware that converting a list to set and then back to list won't
> preserve the order of the items, because the set-type loses the order.

Also beware that this conversion will remove duplicates, so that if
'haha' is in the original list multiple times, there will only be one
after converting to a set and then back to a list.  Only you can tell
us whether this behavior is desirable or not.

-- Paul

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


Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread Lorenzo
In article <[EMAIL PROTECTED]>,
 Georg Brandl <[EMAIL PROTECTED]> wrote:

> Lorenzo schrieb:
> 
> >> > How do I go about it?
> >> 
> >> Do it correctly. Post your actual example that fails
> >> and the related error message. Possibnly your indexes
> >> were out of range.
> >> 
> >> > I googled this and found a couple
> >> > of references, but no solution.
> >> 
> >> Well, there wouldn't be  a solution to a non-existent
> >> problem, would there?
> >> 
> >> > TIA
> > 
> > Here's the code:
> > 
> >  elapsedTime = mydata[1]
> >  index = elapsedTime.find("real")
> >  # the index will have a value 0f 110 
> >  totaltime = elapsedTime[index:]
> >  # instead of this returning a shortened html string, i only 
> >  # get the left angle bracket '<'
> 
> May it be that mydata[1] doesn't contain "real" at all? In that case,
> find() returns -1, and the slice elapsedTime[-1:] always contains
> at most one character.
> 
> If you replace "find" by "index", you get a ValueError exception if
> "real" was not found, if that helps you.
> 
> Whenever one calls str.find(), one has to check the return value for -1.
> 
> Georg

Oops! I sent the wrong piece of code. The above is actually the work 
around which actually works. The bad code is this:
index  = mydata[0].find("real")
elapsedTime = mydata[0][index:]

My apologies, but this is what fails.

-- 
"My Break-Dancing days are over, but there's always the Funky Chicken"
--The Full Monty
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread Lorenzo
In article <[EMAIL PROTECTED]>,
 "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> On Apr 8, 12:29�pm, Lorenzo <[EMAIL PROTECTED]> wrote:
> > In article <[EMAIL PROTECTED]>,
> >
> >
> >
> >
> >
> >  "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> > > On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]>
> > > wrote:
> > > > I have tuple which hold a string in tup[0]. I want to get a slice of
> > > > that string. I thought I would do something like:
> > > > tup[0][start:end]
> > > > But this fails.
> >
> > > No, it doesn't.
> >
> > > >>> a = ('abcdefg','hijkl')
> > > >>> a[0]
> > > 'abcdefg'
> > > >>> a[0][1:2]
> > > 'b'
> >
> > > > How do I go about it?
> >
> > > Do it correctly. Post your actual example that fails
> > > and the related error message. Possibnly your indexes
> > > were out of range.
> >
> > > > I googled this and found a couple
> > > > of references, but no solution.
> >
> > > Well, there wouldn't be  a solution to a non-existent
> > > problem, would there?
> >
> > > > TIA
> >
> > Here's the code:
> >
> >  elapsedTime = mydata[1]
> >  index = elapsedTime.find("real")
> >  # the index will have a value 0f 110
> >  totaltime = elapsedTime[index:]
> >  # instead of this returning a shortened html string, i only
> >  # get the left angle bracket '<'
> 
> This implies that '<' is the 111th character (counting
> from 0) and that it is the last character since you used
> [index:].
> 
> Print out the entire string elapsedTime, count from
> 0 to the characters you want and see if you have the
> correct index numbers (verify them).
> 
> 
> >
> > --
> > "My Break-Dancing days are over, but there's always the Funky Chicken"
> > --The Full Monty

Oops! I sent the wrong piece of code. The above is actually the work 
around which actually works. The bad code is this:
index  = mydata[0].find("real")
elapsedTime = mydata[0][index:]

My apologies, but this is what fails.

-- 
"My Break-Dancing days are over, but there's always the Funky Chicken"
--The Full Monty
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: tuples are useless???

2007-04-08 Thread Bart Willems
James Stroud wrote:
> ... It boils down to the fact that tuples are useless as a 
> result unless you know you really need them--and you never really NEED 
> them.

Could you clarify that for me? I use tuples *a lot* and I really *NEED* 
them - I'm building a lot of multi-tier reports where detail-level data 
is pulled out of a dictionary based on a composed key. It is impossible 
to build those dictionaries *without* using tuples.

So, I *need* those tuples, and they're far from useless to me.

For the rare, rare, rare cases where I *would* need an index function on 
a tuple (I've never needed it):

class IndexTuple(tuple):
   def index(n):
 # your code goes here

would be sufficient, wouldn't it?

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


Debugging doctest failures

2007-04-08 Thread Eric Mahurin
Noob here.  Just got into python a little over a week ago...

One of the (unique?) things I really like about python is the concept
of doctesting.  But, now I want more!  Here's what I'd like to see:

* easy debugging.  As soon as there is a failure (unexpected exception
or mismatch), drop down into the debugger in a way to isolates the bug
down to the nearest test/example as much as possible.

* integrated with code coverage.  I'd like to be targetting 100% code
coverage with doctests.  With full (or a target) coverage, no
additional coverage data would be needed and otherwise something that
tells which lines don't have coverage would be good.  A way to mark
code that you don't care about covering (typically error conditions -
at least initially) would also be good.

* whether stdout and/or sterr should be checked.


If anybody has any pointers to what I should be doing with doctest or
another framework I should be using (zope.testing?), I'd appreciate
it.

I made a crack at the first one above (easy debugging).  Here is a
little script I came up with.  You just give modules you want to
doctest as arguments.  When a normal failure occurs, it will restart
the test (with verbose) and set traces before each example.  When an
unexpected exception occurs, it pulls up the debugger with the
backtrace and continuing will restart the test just like a normal
failure.  I've used this a bit and it allows me to find bugs very fast
without changing the code a bit for debug purposes.  The
implementation below is quite hacky and tied to the implementation
within the doctest module.


#!/usr/bin/env python

import doctest
import sys

def trace_runner(reporter,arg3) :
import sys
tb = sys.exc_info()[2]
while tb.tb_next : tb = tb.tb_next
l = tb.tb_frame.f_locals
out, test, example, arg3 = l['out'], l['test'], l['example'],
l[arg3]
runner = doctest.DocTestRunner(verbose=True,
optionflags=doctest.NORMALIZE_WHITESPACE)
getattr(runner,reporter)(out, test, example, arg3)
for e in test.examples :
e.source = 'pdb.set_trace();' + e.source
exec 'import pdb' in test.globs
return runner

mod_names = []
for mod_name in sys.argv[1:] :
__import__(mod_name,globals(),locals())
mod_names.append(mod_name)
finder = doctest.DocTestFinder()
runner = doctest.DebugRunner(optionflags=doctest.NORMALIZE_WHITESPACE)

try :

for mod_name in mod_names :
mod = sys.modules.get(mod_name)
for test in finder.find(mod, mod_name) :
runner.run(test)

except doctest.DocTestFailure :

runner = trace_runner('report_failure','got')
runner.run(test)

except doctest.UnexpectedException, err :

runner = trace_runner('report_unexpected_exception','exc_info')
import pdb
pdb.post_mortem(err.exc_info[2])
runner.run(test)

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


Re: Python Web Servers and Page Retrievers

2007-04-08 Thread Max Erickson
Subscriber123 <[EMAIL PROTECTED]> wrote:
> urllib, or urllib2 for advanced users. For example, you can
> easily set your own headers when retrieving and serving pages,
> such as the User-Agent header which you cannot set in either
> urllib or urllib2. 

Sure you can. See:

http://www.diveintopython.org/http_web_services/user_agent.html

(though the behavior was changed for python 2.3 to make setting the 
user agent work better)


max


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


Re: how to remove multiple occurrences of a string within a list?

2007-04-08 Thread Alex Martelli
Ayaz Ahmed Khan <[EMAIL PROTECTED]> wrote:
   ...
> I am getting varying results on my system on repeated runs.  What about
> itertools.ifilter()?

Calling itertools.ifilter returns an iterator; if you never iterate on
that iterator, that, of course, is going to be very fast (O(1), since it
does not matter how long the list you _don't_ iterate on is), but why
would you care how long it takes to do no useful work at all?

> $ python -m timeit -s "L = ['0024', 'haha', '0024']; import itertools"
"itertools.ifilter(lambda i: i != '1024', L)" 
> 10 loops, best of 3: 5.37 usec per loop
> 
> $ python -m timeit -s "L = ['0024', 'haha', '0024']" 
> "[i for i in L if i != '0024']" 
> 10 loops, best of 3: 5.41 usec per loop

Here are the numbers I see:

brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', '0024'];
> import itertools" "itertools.ifilter(lambda i: i != '1024', L)"
100 loops, best of 3: 0.749 usec per loop

This is the "we're not doing any work" timing.

brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', 
'0024']" "[i for i in L if i != '1024']"
100 loops, best of 3: 1.37 usec per loop

This is "make a list in the obvious way, excluding an item that's never
there" (like in your code's first case, I'm comparing with 1024, which
ain't there, rather than with 0024, which is).

brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', 
'0024']; import itertools" "list(itertools.ifilter(lambda i: i !=
'1024', L))"
10 loops, best of 3: 6.18 usec per loop

This is the "make it the hard way" (excluding a non-present item).
About 5/6 of the overhead comes from the list constructor.

When we exclude the item that IS there twice:

brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', 
'0024']" "[i for i in L if i != '0024']"
100 loops, best of 3: 0.918 usec per loop

this is the "obvious way to do it",

brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', 
'0024']; import itertools" "list(itertools.ifilter(lambda i: i !=
'0024', L))"
10 loops, best of 3: 6.16 usec per loop

and this is the "hard and contorted way".


If you only want to loop, not to build a list, itertools.ifilter (or a
genexp) may be convenient (if the original list is long); but for making
lists, list comprehensions win hand-down.

Here are a few cases of "just looping" on lists of middling size:

brain:~ alex$ python -m timeit -s "L = 123*['0024', 'haha', 
'0024']" "for j in [i for i in L if i != '0024']: pass"
1 loops, best of 3: 70 usec per loop

brain:~ alex$ python -m timeit -s "L = 123*['0024', 'haha', 
'0024']" "for j in (i for i in L if i != '0024'): pass"
1 loops, best of 3: 70.9 usec per loop

brain:~ alex$ python -m timeit -s "L = 123*['0024', 'haha', 
'0024']; import itertools" "for j in itertools.ifilter(lambda i: i !=
'0024', L
): pass"
1 loops, best of 3: 151 usec per loop

Here, the overhead of itertools.ifilter is only about twice that of a
genexp (or list comprehension; but the LC should cost relatively more as
L's length keeps growing, due to memory-allocation issues).

BTW, sometimes simplest is still best:

brain:~ alex$ python -m timeit -s "L = 123*['0024', 'haha', 
'0024']" "for i in L:  
>   if i != '0024':
> pass"
1 loops, best of 3: 52.5 usec per loop

I.e., when you're just looping... just loop!-)


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


Python Web Servers and Page Retrievers

2007-04-08 Thread Subscriber123

I wrote most of the following script, useful for retrieving pages from the
web and serving web pages. Since it is so low level, it is much more
customizable than simpleHTTPserver, cgiHTTPserver, urllib, or urllib2 for
advanced users. For example, you can easily set your own headers when
retrieving and serving pages, such as the User-Agent header which you cannot
set in either urllib or urllib2.

(sorry for not putting in any comments!)

By the way, I just threw this together quickly, and haven't really had time
to test retrieve() very much. Please let me know if it is buggy.
I guess I should also write a dictToQuery() function. Oh well.


import socket


host,port='',80

sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind((host,port))
sock.listen(1)

def serve(function=lambda *args:(args[2],200,'OK',{},'')):
"""\
def serve(function(method,filename,httpversion,headers,get,post))

Serves one request, calling function() with the above
parameters. function() must return (httpversion,code,
accepted,headers,content) in that order. If you don't
pass a function, then
function=lambda *args:(args[2],200,'OK',{},'')
"""

csock,caddr=sock.accept()
rfile=csock.makefile('r',0)
wfile=csock.makefile('w',0)

# Protocol exchange - read request
headers={}
line=rfile.readline().strip()
split1=line.find(' ')
method,remainder=line[:split1].strip(),line[split1+1:].strip()
split2=remainder.find(' ')

filename,httpversion=remainder[:split2].strip(),remainder[split2+1:].strip()
while 1:
line=rfile.readline().strip()
print line
if line=='':
break
else:
split=line.find(':')
key,value=line[:split],line[split+1:]
headers[key.strip()]=value.strip()

try:
post=rfile.read(int(headers['Content-Length']))
except:
post=''
get=queryToDict(filename)
post=queryToDict(post)
loc=filename.find("?")
if loc>-1:
filename=filename[:loc]
print "get:",`get`
print "post:",`post`

httpversion,code,accepted,headers,content=function(method,filename,httpversion,headers,get,post)
wfile.write("%s %s %s\n"%(httpversion,code,accepted))
for header in list(headers):
wfile.write("%s: %s\n"%(header,headers[header]))
wfile.write("\n%s\n"%content)
wfile.close()
csock.close()

def
retrieve(host,port=80,method='GET',filename='/',httpversion='HTTP/1.0',headers={},post=''):
"""\
Retrieves one web page from:
http://host:port/filename
with the headers
"""
sock.connect((host,port))
rfile=sock.makefile('r',0)
wfile=sock.makefile('w',0)
wfile.write("%s %s %s\n"%(method,filename,httpversion))
for header in list(headers):
wfile.write("%s: %s\n"%(header,headers[header]))
wfile.write('\n')
wfile.write("%s\n"%post)

headers={}
line=rfile.readline().strip()
split1=line.find(' ')
httpversion,remainder=line[:split1].strip(),line[split1+1:].strip()
split2=remainder.find(' ')
code,accepted=remainder[:split2].strip(),remainder[split2+1:].strip()
while 1:
line=rfile.readline().strip()
if line=='':
break
else:
split=line.find(':')
key,value=line[:split],line[split+1:]
headers[key.strip()]=value.strip()
return httpversion,code,accepted,headers,rfile

def queryToDict(query):
if '?' in query:
query=query[query.index('?')+1:]
kvpairs=query.split("&")
ret={}
for kvpair in kvpairs:
if '=' in kvpair:
loc=kvpair.index('=')
key,value=kvpair[:loc],kvpair[loc+1:]
ret[key]=value
return ret

if __name__=='__main__':
i=0
while True:
i+=1
print "\nserve #%d:"%i
serve(lambda
*args:(args[2],200,'OK',{'Content-Type':'text/html'},'Go Away!'))

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

Re: Unicode problem

2007-04-08 Thread Rehceb Rotkiv
On Sat, 07 Apr 2007 12:46:49 -0700, Gabriel Genellina wrote:

> You have to encode the Unicode object explicitely: print
> fileString.encode("utf-8")
> (or any other suitable one; I said utf-8 just because you read the input
> file using that)

Thanks! That's a nice little stumbling block for a newbie like me ;) Is 
there a way to make utf-8 the default encoding for every string, so that 
I do not have to encode each string explicitly?
-- 
http://mail.python.org/mailman/listinfo/python-list


getting button's coordinations

2007-04-08 Thread gslm
Hi,
I want to use a button's coordinations for my application.It's
necessary for determinig an area for ImageGrab function.Because all
widgets are on a button.And I want to have this screenshot and save it
as image file.

Or is there any command which print all of the view of button(all the
components on the button)?
regards...

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


Re: RFC: Assignment as expression (pre-PEP)

2007-04-08 Thread Dustan
On Apr 8, 10:56 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Dustan <[EMAIL PROTECTED]> wrote:
> > >>> class Wrapper(object):
> >   def __init__(self, obj):
> >   self.obj = obj
> >   def getit(self):
> >   return self.obj
> >   def setit(self, obj):
> >   self.obj = obj
> >   return obj
>
> Yeah, that's substantialy the same approach I posted as a Python
> Cookbook recipe almost six years ago, see
>  .

Indeed, I did discover that in my copy of the Python Cookbook some
time ago. Perhaps I should have noted that.

> My specific use case for that recipe was when using Python to code a
> "reference algorithm" found in a book, so that deep restructuring was
> unwanted -- a similar but opposite case is using Python to explore
> prototype algorithms that would later be recoded e.g. in C (here, too,
> you don't really want to refactor the Python code to use dictionaries
> "properly", so assign-and-test is handy).
>
> Alex


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


Re: What happened to http://www.pythonware.com/daily and http://mechanicalcat.net/pyblagg.html?

2007-04-08 Thread Fuzzyman
On Apr 7, 3:44 pm, "asker" <[EMAIL PROTECTED]> wrote:
> These sites are not updated since almost one month.
> Does anybody knows why?

I assume the pythonware folk are busy. I notice that Fredrik Lundh
hasn't blogged for some time either.

Fuzzyman
http://www.voidspace.org.uk/ironpython/index.shtml

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


Re: tuples, index method, Python's design

2007-04-08 Thread Paul Rubin
Carsten Haese <[EMAIL PROTECTED]> writes:
> > Do you not see the gratuituous inconsistency between tuples and lists
> > as a useless feature?  What is the use case for keeping it?
> 
> When a new feature is requested, the burden of proof is on the requester
> to show that it has uses. The use case for not having tuple.index is
> that there are no use cases for having it. If that answer sounds absurd,
> it is because your question is absurd.

The use case has already been discussed.  Removing the pointless
inconsistency between lists and tuples means you can stop having to
remember it, so you can free up brain cells for implementing useful
things.  That increases your programming productivity.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2007-04-08 Thread Carsten Haese
On Sun, 2007-04-08 at 07:51 -0700, Paul Rubin wrote:
> Carsten Haese <[EMAIL PROTECTED]> writes:
> > > Maybe we can add such methods to the PyPy tuples for some time, to
> > > experimentally see if they make the language worse :-)
> > 
> > Adding useless features always makes a product worse. What's your use
> > case for tuple.index?
> 
> Do you not see the gratuituous inconsistency between tuples and lists
> as a useless feature?  What is the use case for keeping it?

When a new feature is requested, the burden of proof is on the requester
to show that it has uses. The use case for not having tuple.index is
that there are no use cases for having it. If that answer sounds absurd,
it is because your question is absurd.

-Carsten


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


Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread [EMAIL PROTECTED]
On Apr 8, 12:29�pm, Lorenzo <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>
>
>
>
>
> �"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> > On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]>
> > wrote:
> > > I have tuple which hold a string in tup[0]. I want to get a slice of
> > > that string. I thought I would do something like:
> > > tup[0][start:end]
> > > But this fails.
>
> > No, it doesn't.
>
> > >>> a = ('abcdefg','hijkl')
> > >>> a[0]
> > 'abcdefg'
> > >>> a[0][1:2]
> > 'b'
>
> > > How do I go about it?
>
> > Do it correctly. Post your actual example that fails
> > and the related error message. Possibnly your indexes
> > were out of range.
>
> > > I googled this and found a couple
> > > of references, but no solution.
>
> > Well, there wouldn't be �a solution to a non-existent
> > problem, would there?
>
> > > TIA
>
> Here's the code:
>
> �elapsedTime = mydata[1]
> �index = elapsedTime.find("real")
> �# the index will have a value 0f 110
> �totaltime = elapsedTime[index:]
> �# instead of this returning a shortened html string, i only
> �# get the left angle bracket '<'

This implies that '<' is the 111th character (counting
from 0) and that it is the last character since you used
[index:].

Print out the entire string elapsedTime, count from
0 to the characters you want and see if you have the
correct index numbers (verify them).


>
> --
> "My Break-Dancing days are over, but there's always the Funky Chicken"
> --The Full Monty

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

Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread [EMAIL PROTECTED]
On Apr 8, 12:29�pm, Lorenzo <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>
>
>
>
>
> �"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> > On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]>
> > wrote:
> > > I have tuple which hold a string in tup[0]. I want to get a slice of
> > > that string. I thought I would do something like:
> > > tup[0][start:end]
> > > But this fails.
>
> > No, it doesn't.
>
> > >>> a = ('abcdefg','hijkl')
> > >>> a[0]
> > 'abcdefg'
> > >>> a[0][1:2]
> > 'b'
>
> > > How do I go about it?
>
> > Do it correctly. Post your actual example that fails
> > and the related error message. Possibnly your indexes
> > were out of range.
>
> > > I googled this and found a couple
> > > of references, but no solution.
>
> > Well, there wouldn't be �a solution to a non-existent
> > problem, would there?
>
> > > TIA
>
> How would you get a slice of a[0] from your example? 'cde' for example?

'b' _was_ a slice of a[0]. but for your specific example

>>> a[0][2:5]
'cde'

Keep in mind the "end" value is not returned and indexing
starts with 0, so "cde" represents the 3rd, 4th & 5th
characters making the slice 2:5.

>
> --
> "My Break-Dancing days are over, but there's always the Funky Chicken"
> --The Full Monty

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

Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread Georg Brandl
Lorenzo schrieb:

>> > How do I go about it?
>> 
>> Do it correctly. Post your actual example that fails
>> and the related error message. Possibnly your indexes
>> were out of range.
>> 
>> > I googled this and found a couple
>> > of references, but no solution.
>> 
>> Well, there wouldn't be  a solution to a non-existent
>> problem, would there?
>> 
>> > TIA
> 
> Here's the code:
> 
>  elapsedTime = mydata[1]
>  index = elapsedTime.find("real")
>  # the index will have a value 0f 110 
>  totaltime = elapsedTime[index:]
>  # instead of this returning a shortened html string, i only 
>  # get the left angle bracket '<'

May it be that mydata[1] doesn't contain "real" at all? In that case,
find() returns -1, and the slice elapsedTime[-1:] always contains
at most one character.

If you replace "find" by "index", you get a ValueError exception if
"real" was not found, if that helps you.

Whenever one calls str.find(), one has to check the return value for -1.

Georg

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


Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread Lorenzo
In article <[EMAIL PROTECTED]>,
 "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]>
> wrote:
> > I have tuple which hold a string in tup[0]. I want to get a slice of
> > that string. I thought I would do something like:
> > tup[0][start:end]
> > But this fails.
> 
> No, it doesn't.
> 
> >>> a = ('abcdefg','hijkl')
> >>> a[0]
> 'abcdefg'
> >>> a[0][1:2]
> 'b'
> 
> 
> > How do I go about it?
> 
> Do it correctly. Post your actual example that fails
> and the related error message. Possibnly your indexes
> were out of range.
> 
> > I googled this and found a couple
> > of references, but no solution.
> 
> Well, there wouldn't be  a solution to a non-existent
> problem, would there?
> 
> > TIA

How would you get a slice of a[0] from your example? 'cde' for example?

-- 
"My Break-Dancing days are over, but there's always the Funky Chicken"
--The Full Monty
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread Lorenzo
In article <[EMAIL PROTECTED]>,
 "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]>
> wrote:
> > I have tuple which hold a string in tup[0]. I want to get a slice of
> > that string. I thought I would do something like:
> > tup[0][start:end]
> > But this fails.
> 
> No, it doesn't.
> 
> >>> a = ('abcdefg','hijkl')
> >>> a[0]
> 'abcdefg'
> >>> a[0][1:2]
> 'b'
> 
> 
> > How do I go about it?
> 
> Do it correctly. Post your actual example that fails
> and the related error message. Possibnly your indexes
> were out of range.
> 
> > I googled this and found a couple
> > of references, but no solution.
> 
> Well, there wouldn't be  a solution to a non-existent
> problem, would there?
> 
> > TIA

Here's the code:

 elapsedTime = mydata[1]
 index = elapsedTime.find("real")
 # the index will have a value 0f 110 
 totaltime = elapsedTime[index:]
 # instead of this returning a shortened html string, i only 
 # get the left angle bracket '<'

-- 
"My Break-Dancing days are over, but there's always the Funky Chicken"
--The Full Monty
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: block scope?

2007-04-08 Thread Georg Brandl
Alex Martelli schrieb:
> Paul Rubin  wrote:
> 
>> [EMAIL PROTECTED] (Alex Martelli) writes:
>> > > exec?
>> > option 1: that just runs the compiler a bit later ...
>> 
>> Besides exec, there's also locals(), i.e.
>>locals['x'] = 5
>> can shadow a variable.  Any bad results are probably deserved ;)
> 
 locals['x']=5
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'builtin_function_or_method' object does not support item
> assignment
> 
> I suspect you want to index the results of calling locals(), rather than
> the builtin function itself.  However:
> 
 def f():
> ...   locals()['x'] = 5
> ...   return x
> ... 
 f()
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in f
> NameError: global name 'x' is not defined
> 
> No "shadowing", as you see: the compiler knows that x is NOT local,
> because it's not assigned to (the indexing of locals() does not count:
> the compiler's not expected to detect that), so it's going to look it up
> as a global variable (and not find it in this case).

Even assignments to real local variable names in the locals() result do
normally not result in the variable having a new value.

> I think that ideally there should be a runtime error when assigning an
> item of locals() with a key that's not a local variable name (possibly
> excepting functions containing exec, which are kind of screwy anyway).

I would make the locals() result completely independent from the frame,
and document that it is read only.

(though, this needs some other way for trace functions to interact with
the frame's local variables.)

Georg

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


Re: Why does not my wx.html.HtmlWindow work?

2007-04-08 Thread Rob Williscroft
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED] in
comp.lang.python: 

> Below are my source code:
> 
> import wx
> import wx.html
> 
> class MyHtmlFrame(wx.Frame):
> 
> def __init__(self, parent, title):
> wx.Frame.__init__(self, parent, -1, title, size=(600,400))
> html = wx.html.HtmlWindow (self)
> if "gtk2" in wx.PlatformInfo:
> html.SetStandardFonts()
> html.LoadPage("
> http://www.pythonthreads.com/articles/python/incorporating-into
> -wxpython-part-1.html") 
> 
> app = wx.PySimpleApp()
> frm = MyHtmlFrame(None, "Simple HTML Browser")
> frm.Show()
> app.MainLoop()
> 
> It is just an example in the book "wxPython in action". But every time
> when I try to get it run, my CPU is fully occupied, and there is no
> frame that comes into existence. Why?
> 

I think your problem is that you call LoadPage before app.MainLoop() is
called, IOW you need to call LoadPage in an event handler:

import wx
import wx.html

class MyHtmlFrame(wx.Frame):
  
HOME = "http://www.google.co.uk";

def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, size=(600,400))
self.html = wx.html.HtmlWindow (self)
if "gtk2" in wx.PlatformInfo:
self.html.SetStandardFonts()
self.done_show = False
wx.EVT_IDLE( self, self.OnShow )
self.html.SetPage( 
"Loading ..." % self.HOME
  )
  
def OnShow( self, event ): 
if self.done_show:
  return
self.done_show = True
self.html.LoadPage( self.HOME ) 

app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Simple HTML Browser")
frm.Show()
app.MainLoop()

Note: the URL you loading takes ages to show, which is why I
use: http://www.google.co.uk above.

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


Re: How do I get a slice of a string held in a tuple?

2007-04-08 Thread [EMAIL PROTECTED]
On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]>
wrote:
> I have tuple which hold a string in tup[0]. I want to get a slice of
> that string. I thought I would do something like:
> tup[0][start:end]
> But this fails.

No, it doesn't.

>>> a = ('abcdefg','hijkl')
>>> a[0]
'abcdefg'
>>> a[0][1:2]
'b'


> How do I go about it?

Do it correctly. Post your actual example that fails
and the related error message. Possibnly your indexes
were out of range.

> I googled this and found a couple
> of references, but no solution.

Well, there wouldn't be  a solution to a non-existent
problem, would there?

> TIA


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


Re: itertools, functools, file enhancement ideas

2007-04-08 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> >for block in f.iterchars(n=1024):  ...
> for block in iter(partial(f.read, 1024), ''): ...

Hmm, nice.  I keep forgetting about that feature of iter.  It also came
up in a response to my queue example from another post.

> >   a) def flip(f): return lambda x,y: f(y,x)
> Curious resemblance to:
>itemgetter(1,0)

Not sure I understand that.  
-- 
http://mail.python.org/mailman/listinfo/python-list


How do I get a slice of a string held in a tuple?

2007-04-08 Thread Lorenzo Thurman
I have tuple which hold a string in tup[0]. I want to get a slice of 
that string. I thought I would do something like:
tup[0][start:end]
But this fails. How do I go about it? I googled this and found a couple 
of references, but no solution.
TIA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: starship.python.net is down

2007-04-08 Thread TimeHorse
On Feb 26, 4:46 pm, Tom Bryan <[EMAIL PROTECTED]> wrote:
> Yes.  Unfortunately, there may be a hardware problem.  Stefan, the admin

Any word from the ISP what the hardware problem might be, Tom?

Jeffrey.

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


Re: itertools, functools, file enhancement ideas

2007-04-08 Thread rdhettinger
[Paul Rubin]
> 1. File iterator for blocks of chars:
>
>f = open('foo')
>for block in f.iterchars(n=1024):  ...

for block in iter(partial(f.read, 1024), ''): ...



> iterates through 1024-character blocks from the file.  The default iterator
>   a) def flip(f): return lambda x,y: f(y,x)

Curious resemblance to:

   itemgetter(1,0)


Raymond



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


Re: RFC: Assignment as expression (pre-PEP)

2007-04-08 Thread Alex Martelli
Dustan <[EMAIL PROTECTED]> wrote:

> >>> class Wrapper(object):
>   def __init__(self, obj):
>   self.obj = obj
>   def getit(self):
>   return self.obj
>   def setit(self, obj):
>   self.obj = obj
>   return obj

Yeah, that's substantialy the same approach I posted as a Python
Cookbook recipe almost six years ago, see
 .

My specific use case for that recipe was when using Python to code a
"reference algorithm" found in a book, so that deep restructuring was
unwanted -- a similar but opposite case is using Python to explore
prototype algorithms that would later be recoded e.g. in C (here, too,
you don't really want to refactor the Python code to use dictionaries
"properly", so assign-and-test is handy).


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


Re: tuples, index method, Python's design

2007-04-08 Thread Mel Wilson
7stud wrote:
> On Apr 7, 8:27 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
>> Adding useless features always makes a product worse. What's your use
>> case for tuple.index?

> I'll trade you an index method for tuples for the whole complex number
> facility.

Actually, I've found the use cases for list.index to be kind of thin. 
  Long before I think "Which one of these items is a 3?", I seem to 
have thought "dictionary".

Cheers, Mel.

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


Re: tuples, index method, Python's design

2007-04-08 Thread Paul Rubin
Carsten Haese <[EMAIL PROTECTED]> writes:
> > Maybe we can add such methods to the PyPy tuples for some time, to
> > experimentally see if they make the language worse :-)
> 
> Adding useless features always makes a product worse. What's your use
> case for tuple.index?

Do you not see the gratuituous inconsistency between tuples and lists
as a useless feature?  What is the use case for keeping it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2007-04-08 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> Carsten Haese:
> > Adding useless features always makes a product worse. What's your use
> > case for tuple.index?
>
> Ruby is a bit younger than Python, it has shown that few things may be
> better done in a different way.

I think the Ruby way is just to add a ton of methods to every class
and to give them all aliases as well. Then you let the programmer
"monkey patch" those classes in their own code, too.

> An advantage of PyPy is that it allows faster and simpler ways to perform 
> language experiments. So you can
> even try things first and judge them later. You can find usercases later. 
> This may help rejuvenate Python a bit :-)

It's virtually a matter of copy and paste to do this with CPython.
Here's a patch against the SVN trunk:

http://sourceforge.net/tracker/index.php?func=detail&aid=1696444&group_id=5470&atid=305470

Paul

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


Re: Custom Python Runtime

2007-04-08 Thread gene tani
On Apr 6, 4:52 pm, "Jack" <[EMAIL PROTECTED]> wrote:
> Since the full installation of Python (from either the standard installer or
> ActiveState installer) is too big for my intended use, I'd like to build a
> custom distribution of Python for Windows platform, omitting some lib files,
> such as audio, tk, printing, testing units, etc.
>
> Is there a way to customize the Windows build? In my case, there is no need
> to build an installer. The best way is to have everything in a directory, as
> long as I know where to find Python and Python knows where to find the
> necessary libs. Any online docs describing this? Thanks!

did you look at Diet Python:

http://sourceforge.net/projects/dietpython

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


Re: Console UI

2007-04-08 Thread Grant Edwards
On 2007-04-08, Ayaz Ahmed Khan <[EMAIL PROTECTED]> wrote:
> "Clement" typed:
>
>> My project is based on console Application. Is there any
>> console UI except urwid. If so, can i come to know.
>
> There is ``curses''.

And newt (runs on top of slang).  It's not well documented, but
it is nice and lightweight.  IIRC the python module is called
"snack".

-- 
Grant Edwards   grante Yow!  Spreading peanut
  at   butter reminds me of
   visi.comopera!! I wonder why?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RFC: Assignment as expression (pre-PEP)

2007-04-08 Thread Dustan
On Apr 5, 2:51 pm, [EMAIL PROTECTED] wrote:
> I would like to gauge interest in the following proposal:
>
> Problem:
>
> Assignment statements cannot be used as expressions.
>
> Performing a list of mutually exclusive checks that require data
> processing can cause excessive tabification.  For example, consider
> the following python snipet...
>
> temp = my_re1.match(exp)
> if temp:
>   # do something with temp
> else:
>   temp = my_re2.match(exp)
>   if temp:
> # do something with temp
>   else:
> temp = my_re3.match(exp)
> if temp:
>   # do something with temp
> else:
>   temp = my_re4.match(exp)
>
> # etc.
>
> Even with 2-space tabification, after about 20 matches, the
> indentation will take up half an 80-column terminal screen.
>
> Details:
>
> Python distinguishes between an assignment statement and an equality
> expression.  This is to force disambiguation of assignment and
> comparison so that a statement like:
>
> if x = 3:
>
> Will raise an expression rather than allowing the programmer to
> accidentally overwrite x.  Likewise,
>
> x == 3
>
> Will either return True, False or raise a NameError exception, which
> can alert the author of any potential coding mistakes since if x = 3
> (assignment) was meant, assignment being a statement returns nothing
> (though it may raise an exception depending on the underlying
> assignment function called).
>
> Because this forced disambiguation is a guiding virtue of the python
> language, it would NOT be wise to change these semantics of the
> language.
>
> Proposal:
>
> Add a new assignment-expression operator to disambiguate it completely
> from existing operators.
>
> Although any number of glyph could be used for such a new operator, I
> here propose using pascal/gnu make-like assignment.  Specifically,
>
> let:
>
> x = 3
>
> Be a statement that returns nothing;
>
> let:
>
> x == 3
>
> Be an expression that, when x is a valid, in-scope name, returns True
> or False;
>
> let:
>
> x := 3
>
> Be an expression that first assigned the value (3) to x, then returns
> x.
>
> Thus...
>
> if x = 3:
>   # Rais exception
>   pass
>
> if x == 3:
>   # Execute IFF x has a value equivalent to 3
>   pass
>
> if x := 3:
>   # Executes based on value of x after assignment;
>   # since x will be 3 and non-zero and thus represents true, always
> executed
>   pass
>
> Additional:
>
> Since python allows in-place operator assignment, (e.g. +=, *=, etc.),
> allow for these forms again by prefixing each diglyph with a colon
> (:), forming a triglyph.
>
> E.g.
>
> if x :+= 3:
>   # Executes IFF, after adding 3 to x, x represents a non-zero number.
>   pass
>
> Also note, that although the colon operator is used to denote the
> beginning of a programme block, it should be easily distinguished from
> the usage of : to denote a diglyph or triglyph assignment expression
> as well as the trinary conditional expression.  This is because
> firstly, the statement(s) following a colon (:) in existing python
> should never begin with an assignment operator.  I.e.,
>
> if x: = y
>
> is currently not valid python.  Any attempt at interpreting the
> meaning of such an expression in the current implementation of python
> is likely to fail.  Secondly, the diglyph and triglyph expressions do
> not contain spaces, further disambiguating them from existing python.
>
> Alternative proposals for dyglyph and triglyph representations for
> assignment expressions are welcome.
>
> Implementation details:
>
> When the python interpreter parser encounters a diglyph or triglyph
> beginning with a colon (:) and ending with an equals sign (=), perform
> the assignment specified by glyph[1:] and then return the value of the
> variable(s) on the left-hand side of the expression.  The assignment
> function called would be based on standard python lookup rules for the
> corresponding glyph[1:] operation (the glyph without the leading
> colon).
>
> Opposition:
>
> Adding any new operator to python could be considered code bloat.
>
> Using a colon in this way could still be ambiguous.
>
> Adding the ability to read triglyph operators in the python
> interpreter parser would require too big a code revision.
>
> Usage is too obscure.
>
> Using an assignment expression would lead to multiple conceptual
> instructions for a single python statement (e.g. first an assignment,
> then an if based on the assignment would mean two operations for a
> single if statement.)
>
> Comments:
>
> [Please comment]
>
> Jeffrey.

If you really really really really really really really really really
really really really really really really really really really really
really really really really really really really really really really
really really really really really really really really really really
really really really really really really really really really really
really really really really really really really really really really
really really really really really really really really really really

Re: Test Tube Zealots: The American Chemical Society Terminates the Membership of Chemists from Iran

2007-04-08 Thread frank.logullo
Sounds like a good idea to me.  ACS is normally a left wing organization but
if true, I applaud them for this.
The only way the Iranian government problem is going to be rationally solved
is from forces within.


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


Re: Nice "bug" to loose a contest

2007-04-08 Thread aspineux
This code works like the python one,
I dont use buffered stdio f... functions,
but the more 'system call' read and write

int main()
{
char buf[120];
int len;

while (len=read(1, buf, sizeof(buf))) {
write(1, buf, len);
}
return 0;
}

I dont understand what is appening,
but you have to know their is a link between
stdin and stdout in 'terminal mode', when you make a read on stdin,
stdout is automatically flushed, this link disappears when onr is not
liked to a terminal.
This is to facilitate user input, to avoid to put a flush after each
write,
in fact before any user input.

Hope someone else will give the trick



On 8 avr, 12:52, "stdazi" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> Yesterday, I was at a programming competition. We programmed on Linux
> liveCD's and Python was one of the allowed languages (among C and
> Java). I cared just about the algorithmic approach so I used Python.
> One of the main rules is, that the code reads its standard input and
> dumps the result on the standard output. Here happened my bigger
> programming mistake ever - I used the following approach :
>
> 
> import sys
> print sys.stdout.readlines() # TYPO ! stdin != stdout
> 
>
> So the WEIRD issue is, that it worked and, executing the following
> code I get :
>
> 
> [EMAIL PROTECTED] ~ $ python la.py
> test
> test #2
> ['test \n', 'test #2\n']
> [EMAIL PROTECTED] ~ $
> 
>
> Ok, as the algorithm worked perfectly, and all the test cases we were
> given were positive, I've continued with the next problem, copy/
> pasting the above idiom... When they tested the code, they used file
> redirection like :
>
> ==
> python la.py < /somefile
> ==
>
> And, my code resulted in no output/input (=> 0 points), which can be
> proved here too :
>
> 
> [EMAIL PROTECTED] ~ $ python la.py < /etc/passwd
>
> ===
>
> Some friend of mine told me that's the Unix way, (stdout can act like
> stdin) so I tried some C code :
>
> ===
>   1 #include 
>   2
>   3 int main() {
>   4 char buf[120];
>   5 while (fgets(buf, sizeof(buf), stdout) != NULL) {
>   6 puts(buf);
>   7 }
>   8return 0;
>   9}
> ===
>
> The code returns with no delay, so I'm really wondering where is that
> nice sys.{stdin,stdout} feature inplemented as pydoc doesn't mention
> anything. I'd spot the mistake before submitting the problem solutions
> if it was written in C :)
>
> Thanks!


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


Re: iterator interface for Queue?

2007-04-08 Thread Leo Kislov
On Apr 7, 11:40 pm, Paul Rubin  wrote:
> Is there any reason Queue shouldn't have an iterator interface?
> I.e. instead of
>
> while True:
>item = work_queue.get()
>if item is quit_sentinel:
># put sentinel back so other readers can find it
>work_queue.put(quit_sentinel)  
>break
>process(item)

It's almost equal to:

for item in iter(work_queue.get, quit_sentinel):
process(item)

except that it doesn't keep the quit sentinel in the queue. But that's
a personal preference, I usually put as many quit sentinels in a queue
as many consumers.

  -- Leo

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


Nice "bug" to loose a contest

2007-04-08 Thread stdazi
Hello,

Yesterday, I was at a programming competition. We programmed on Linux
liveCD's and Python was one of the allowed languages (among C and
Java). I cared just about the algorithmic approach so I used Python.
One of the main rules is, that the code reads its standard input and
dumps the result on the standard output. Here happened my bigger
programming mistake ever - I used the following approach :


import sys
print sys.stdout.readlines() # TYPO ! stdin != stdout


So the WEIRD issue is, that it worked and, executing the following
code I get :


[EMAIL PROTECTED] ~ $ python la.py
test
test #2
['test \n', 'test #2\n']
[EMAIL PROTECTED] ~ $


Ok, as the algorithm worked perfectly, and all the test cases we were
given were positive, I've continued with the next problem, copy/
pasting the above idiom... When they tested the code, they used file
redirection like :

==
python la.py < /somefile
==

And, my code resulted in no output/input (=> 0 points), which can be
proved here too :


[EMAIL PROTECTED] ~ $ python la.py < /etc/passwd


===

Some friend of mine told me that's the Unix way, (stdout can act like
stdin) so I tried some C code :

===
  1 #include 
  2
  3 int main() {
  4 char buf[120];
  5 while (fgets(buf, sizeof(buf), stdout) != NULL) {
  6 puts(buf);
  7 }
  8return 0;
  9}
===

The code returns with no delay, so I'm really wondering where is that
nice sys.{stdin,stdout} feature inplemented as pydoc doesn't mention
anything. I'd spot the mistake before submitting the problem solutions
if it was written in C :)

Thanks!

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


How to set program name in Python : success

2007-04-08 Thread aspineux
here is the trick I found

#  ( exec  -a "pgm.py" python < pgm.py ) &
# ps ax | grep pgm.py
22334 pts/2S+ 0:00 pgm.py

this solution works on linux and probably all BSD too,
but don't let specify any arguments.

If someone know a better solution 

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


Re: block scope?

2007-04-08 Thread Paddy
On Apr 7, 4:48 am, James Stroud <[EMAIL PROTECTED]> wrote:
> Neal Becker wrote:
> > One thing I sometimes miss, which is common in some other languages (c++),
> > is idea of block scope.  It would be useful to have variables that did not
> > outlive their block, primarily to avoid name clashes.  This also leads to
> > more readable code.  I wonder if this has been discussed?
>
> Probably, with good code, block scope would be overkill, except that I
> would welcome list comprehensions to have a new scope:
>
> py> i
> 
> Traceback (most recent call last):
>File "", line 1, in 
> : name 'i' is not defined
>
> py> [i for i in xrange(4)]
> [0, 1, 2, 3]
> py> i  # hoping for NameError
> 3

Yep, i think that we need consistent scope rules for
listexps and genexps. Isn't it coming in 3.0?

If it is, then maybe it will be back-ported to
Python 2.6.

In Python 2.5 we have the following:

>>> [k for k in (j for j in range(5))]
[0, 1, 2, 3, 4]
>>> k
4
>>> j
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'j' is not defined
>>>

- Paddy.

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


Re: Newbie Question about sequence multiplication

2007-04-08 Thread lancered
On Apr 5, 12:19 am, "Scott" <[EMAIL PROTECTED]> wrote:
> Alright, so I've been trying to teach myself Python which, when compared to
> my attempt to learn C++, is going pretty well.
> But I've come across an issue that I can't figure out, so I figured I'd ask
> the pro's.
>
> Now it looks pretty weird in this format but it was copied exactly from IDLE
>
> *code follows***
>
> #What this program is suppose to do is print a sentence centered in a box
>
> sentence = raw_input('Sentence: ')
>
> screen_width = 80
> text_width = len(sentence)
> box_width = text_width + 6
> left_margin = (screen_width - box_width) // 2
>
> print
> print ' ' * left_margin + '+'   + '-' * (box_width-2)  +  '+'
> print ' ' * left_margin + '|  ' + ' ' * text_width + ' |'
> print ' ' * left_margin + '|  ' + ' '   sentence   + ' |'
> print ' ' * left_margin + '|  ' + ' ' * text_width + ' |'
> print ' ' * left_margin + '+'   + '-' * (box_width-2)  + ' |'
> print
>
> end code
>
> Now that, even though copied straight from "Beginning Python: From Novice to
> Professional", returns :
> There's an error in your program: invalid syntax
>
> with the word sentence highlighted (not the sentence when I'm defining the
> name, the one in..uhmthe body of the code)
>
> Now if i put * before sentence as it is with the rest of the variables, it
> actually gets to the point where it asks me for the sentence, but after
> inputting my sentence I receive:
> Traceback (most recent call last):
>   File "D:/Programming/Python/sequence string multiplication example", line
> 16, in 
> print ' ' * left_margin + '|  ' + ' ' * sentence   + ' |'
> TypeError: can't multiply sequence by non-int of type 'str'
>
> Why can't I get it to do what it's supposed to do? What am I
> missing/misunderstanding?
> Very simply all its supposed to do is something like this (now bear with me
> formating might distort this a bit lol)
> ++
> ||
> |  Like This|
> ||
> ++
>
> Any help would be greatly appreciated
>
> -Scott

I modified the codes a little bit to get it running, and give the
correct alignment.
Just as a reference for you. Here is it:

*
sentence = raw_input('Sentence: ')

screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) /2

print
print ' ' * left_margin + '+' + '-' * (box_width-2)  + '+'
print ' ' * left_margin + '|' + ' ' * (box_width-2)  + '|'
print ' ' * left_margin + '|' + ' '*2+sentence +' '*2+ '|'
print ' ' * left_margin + '|' + ' ' * (box_width-2)  + '|'
print ' ' * left_margin + '+' + '-' * (box_width-2)  + '+'
print


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


Re: itertools, functools, file enhancement ideas

2007-04-08 Thread Alexander Schmolck
[EMAIL PROTECTED] (Alex Martelli) writes:

> > 4. functools enhancements (Haskell-inspired):
> >Let f be a function with 2 inputs.  Then:
> >   a) def flip(f): return lambda x,y: f(y,x)
> >   b) def lsect(x,f): return partial(f,x)
> >   c) def rsect(f,x): return partial(flip(f), x)
> > 
> >lsect and rsect allow making what Haskell calls "sections".  Example:
> >   # sequence of all squares less than 100
> >   from operator import lt
> >   s100 = takewhile(rsect(lt, 100), (x*x for x in count()))
> 
> Looks like they'd be useful, but I'm not sure about limiting them to
> working with 2-argument functions only.

How's

from mysterymodule import resect
from operator import lt
takewhile(rsect(lt, 100), (x*x for x in count()))

better than 

takewhile(lambda x:x<100, (x*x for x in count()))

Apart from boiler-plate creation and code-obfuscation purposes?

'as




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


Re: block scope?

2007-04-08 Thread Alexander Schmolck
Neal Becker <[EMAIL PROTECTED]> writes:

> One thing I sometimes miss, which is common in some other languages (c++),
> is idea of block scope.  It would be useful to have variables that did not
> outlive their block, primarily to avoid name clashes.  This also leads to
> more readable code.  

I have on occassion used lambda as a poor-man's let, but only if I needed to
avoid multiple evaluation:

 res = (lambda x=blah(...), y=blahz(...):  f(x*y,x+y))()

I'm sure most people would debate it's more readable, but it's IMO superior to
cleaning up manually with ``del``. I sometimes also find it useful to avoid
cluttering up the interactive shell.

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


Re: Hide the python-script from user

2007-04-08 Thread Sherm Pendley
[EMAIL PROTECTED] (Jason F. McBrayer) writes:

> A determined and technically savvy user will surely find
> the key (not least by debugging the start-script).

... and then write a patch that disables the key, and distribute that to
a few million of his not so determined or savvy friends.

> Basically, this doesn't work for the same reason that DRM doesn't
> work.

That reason being, it only needs to be cracked once. The odds are heavily
stacked in the crackers' favor.

sherm--

-- 
Web Hosting by West Virginians, for West Virginians: http://wv-www.net
Cocoa programming in Perl: http://camelbones.sourceforge.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comments in ConfigParser module

2007-04-08 Thread Joel Granados

On 7 Apr 2007 13:19:06 -0700, Gabriel Genellina <[EMAIL PROTECTED]>
wrote:


Joel Andres Granados wrote:

> The module also allows the comments to appear in the same line as the
> "name = value" constructs.  The only difference being that this is only
> possible with ";" and not with "#" character.  I did not see this in the
> documentation but this is how it is behaving.

Yes, it's not documented. There is only a comment in the source code:

# ';' is a comment delimiter only if it
follows
# a spacing character

I think it's either a bug in the code or in the documentation.



Yep, IMO its a weirdness in the behavior that is not documented.


QUESTION...So the question is:
> Can you use "#" and ";" as comment characters? and if so why does the
> "#" not apply for the same situations as the ";"?

If you follow the documentation, comments are ONLY allowed to start a
line.
The actual implementation discards any text following a ;
sequence.



Yep.   This is just one of the situations where the documentation is
different from the actual behavior.


Just for reference:
> On the RFC 822  (a document
> referenced in the documentation) there is a mention of ";" being used as
> comment character but not necessarily at the beginning of the line.

RFC822 uses ";" to include comments in the syntax rules, not for
comments in the actual message headers (parenthesis are used there).



Yep.  Here I just wanted to stress that in the RFC it states that the
comment doesn't necessarily have to be at the beginning of the line.

--

Gabriel Genellina

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





--
Joel Andrés Granados
Medellín Colombia
--
[EMAIL PROTECTED]
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Console UI

2007-04-08 Thread Ayaz Ahmed Khan
"Clement" typed:

> My project is based on console Application. Is there any console UI
> except urwid. If so, can i come to know.

There is ``curses''.

-- 
Ayaz Ahmed Khan

Do what comes naturally now.  Seethe and fume and throw a tantrum.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: defining functions

2007-04-08 Thread rweth
Andre P.S Duarte wrote:
> How do I define a function, then import it, without having to save it
> in lib; like "C:\python25\lib". ?
> 

The best way I have found (in windows ) for permanently extending your
search path for modules is to create the file:
package.pth
and put your path/s in a line by line format:
 c:\qa\PythonLibs
 c:\qa\PythonUtils

The file needs to be in a location in your install
under the site-packages .. in windows for my system thats:
C:\Python25\Lib\site-packages\package.pth

After you do that you can put your modules in the paths you define
in the package.pth   file and sys,path will pick up your modules
automatically.

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


Re: Hide the python-script from user

2007-04-08 Thread Jason F. McBrayer
hlubenow <[EMAIL PROTECTED]> writes:

> Ok, but now I can offer a real secure solution:

Nope.

[snip]

> Then you have to program a start-script, that reads in your script and the
> decryption-key. The decryption-key must be encrypted too. Such a encrypted
> key can be generated by the modules if you don't pass a password to my
> function "doEncrypt(). The decryption-key must then be hidden somewhere
> within the encrypted program-script. That's because, if the user knows
> where to find the key, he can decrypt the program-script.
>
> If your start-script is written, everything should work automatically, one
> shouldn't nearly notice the decryption-process.

That is to say, for the user to be able to run your program, they must
have the key.  They don't have to know they have the key, but they
have to have it.  This isn't really secure, it's just obscure.  It
depends on the user not finding the key, and on no one telling them
where it is.  A determined and technically savvy user will surely find
the key (not least by debugging the start-script).

Basically, this doesn't work for the same reason that DRM doesn't
work.  

-- 
+---+
| Jason F. McBrayer[EMAIL PROTECTED]  |
| If someone conquers a thousand times a thousand others in |
| battle, and someone else conquers himself, the latter one |
| is the greatest of all conquerors.  --- The Dhammapada|
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does not my wx.html.HtmlWindow work?

2007-04-08 Thread [EMAIL PROTECTED]
On 4月8日, 下午2时29分, Thomas Krüger <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
> > 
> > html.LoadPage("http://www.pythonthreads.com/articles/python/incorporating-into-wxpyt...";)
>
> Quickshot: There's a space at the start of your URI.
>
> Thomas

It seems it's not the problem.
In my final program there is no such mistake.

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

Re: How to tell when a file is opened

2007-04-08 Thread Tim Golden
momobear wrote:
>> Will look into NTFS change journals when I get some spare time.
> How can we get NTFS change journals? Is there any API for this purpose
> or we could implement our own?
> there're an api in windows help us montior file changes.
> win32file.ReadDirectoryChangesW

Don't know what the API is but whatever it ends up being,
there's always ctypes. This article:

   http://www.codeproject.com/useritems/Eyes_on_NTFS.asp

points to DeviceIOControl and CreateFile, both in the
win32file module.

The problem with win32file.ReadDirectoryChangesW, which the
OP probably saw when he looked at my site (though he doesn't
actually say so) is that you're trying to monitor *an entire
hard disk*, maybe more. And you'll almost certainly run into
buffer shortfalls or even performance issues. But I don't
really have access to a big enough or used enough disk to
carry out a meaningful test.

TJG

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


Re: Cant access http://cheeseshop.python.org/ or wiki

2007-04-08 Thread rweth
cyb wrote:
> For some reason I can ping these two sites fine, but when I try to go to 
> them I cannot get to them. Normal python.org homepage works just fine. 
> This is preventing me from getting setuptools and using pyOpenGL =(
> 
> I'm using COmcast in savannah, GA


"It's the finest cheese shop in these parts sir"
"And what leads you to that conclusion"
"well it's so clean sir"
"well it's certainly uncontaminated by cheese!"
 http://www.youtube.com/watch?v=pDat9zdw7Gs

Prey out of curiosity .. any idea where the spiders came from?
I too noticed an issue downloading mechanize last night.
-- 
http://mail.python.org/mailman/listinfo/python-list