Re: __del__ not called?

2006-03-13 Thread Felipe Almeida Lessa
Em Seg, 2006-03-13 às 08:21 +0100, Gregor Horvath escreveu:
> Hi,
> 
> I do not understand why __del__ does not get executed in the following 
> example.

It only collects when there are no references:

>>> class A(object):
... def __init__(self):
... print "A's init"
... def __del__(self):
... print "A's del"
...
>>> a = A()
A's init
>>> del a
A's del
>>> class B(object):
... a = A()
...
A's init
>>> del B
>>> # We'll to tell him to collect the garbage here, but
... # usually it should not be necessary.
... import gc
>>> gc.collect()
A's del
20
>>>

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: Class attributes newbie question (before I join a cargocult)

2006-03-13 Thread Peter Otten
EP wrote:

> This is likely a stupid question, 

There seems to be a cult believing that calling one's own question "stupid"
magically diminishes its degree of stupidity. In reality, as a compiler
would put it, "code has no effect".

> but I am confused about what is going 
> on with class attributes as far as whether they "stick".  I ran across
> this in a program I am writing, but have reproduced the behavoir below
> - can someone point me in the right direction (thanks):
> 
> class AttStickiness(object):
> def __init__(self, myname="", mysex=""):
> self.name=myname
> self.sex=mysex
> 
> def changeSex(self, newsex=""):
> self.mysex=newsex
> return self.mysex
> 
> def changeName(self, newname=""):
> self.name=newname
> return self.name
> 
> def whoAmI(self):
> return self.name, self. sex

Are empty strings reasonable defaults for name or sex? No.
Do the changeXXX() methods /conceptionally/ anything except change an
attribute? No.
Is whoAmI() meant to inform the user/developer? Yes.

If your answers were like mine you are already deeply into "cargocult".
Instead of changeXXX() use attributes directly (you can turn them into
properties should side effects become necessary), instead of whoAmI() use
__str__() or __repr__().
 
>>> class Person(object):
... def __init__(self, name, sex):
... self.name = name
... self.sex = sex
... def __repr__(self):
... return "Person(name=%r, sex=%r)" % (self.name, self.sex)
...
>>> me = Person("Eric", "male")
>>> me
Person(name='Eric', sex='male')
>>> me.name = "Jimbo"
>>> me
Person(name='Jimbo', sex='male')
>>> me.sex = "female"
>>> me
Person(name='Jimbo', sex='female')

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


Re: python crashes in Komodo

2006-03-13 Thread Fredrik Lundh
"swisscheese" wrote:

> Using the Komodo IDE under XP I often get "python.exe has encountered a
> problem and needs to close". Running python direct on the same app
> gives a list index out of bounds error. Any ideas how to get Komodo to
> give the proper error?

is your application using any non-standard (i.e. non-bundled) C extensions ?





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


Is this possible in Python?

2006-03-13 Thread alainpoint
Hi

I wonder if Python is capable of the following: define a function which
returns its argument.
I mean:
def magic_function(arg):
.. some magic code ...

that behaves the following way:

assert magic_function(3+4)=="3+4"
assert magic_function([i for i in range(10)])=="i for i in range(10)]"

It is not trivial at all and might require some bytecode hacking that i
am unable to do myself BUT you are the experts ;-)

Alain

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


Re: Is this possible in Python?

2006-03-13 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> assert magic_function(3+4)=="3+4"
> assert magic_function([i for i in range(10)])=="i for i in range(10)]"
> 
> It is not trivial at all and might require some bytecode hacking that i
> am unable to do myself BUT you are the experts ;-)

Guhhh... you'd want to use the traceback system and reach back into
the source code to get and parse the statement that called the magic
function, sort of like a debugger does.  I don't think messing with
the bytecode would help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __del__ not called?

2006-03-13 Thread Gregor Horvath
Felipe Almeida Lessa schrieb:

 del B
 # We'll to tell him to collect the garbage here, but
 >
 > ... # usually it should not be necessary.

Thanks. If I do

del B

then the __del__ of A gets called.
That surprises me. I thought that B gets del'd by python when it goes 
out of scope?

Do I manually have to del all class objects, so that their class 
attributes get gc'd 

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


Re: generators shared among threads

2006-03-13 Thread Tim Peters
[Paul Rubin]
> It looks to me like you can't have two threads in the same generator:

You can't even have one thread in a generator-iterator get away with
activating the generator-iterator while it's already active.  That's
an example in PEP 255:

"""
  Restriction:  A generator cannot be resumed while it is actively
running:

>>> def g():
... i = me.next()
... yield i
>>> me = g()
>>> me.next()
Traceback (most recent call last):
 ...
  File "", line 2, in g
ValueError: generator already executing
"""

Same thing if more than one thread tries to do that, but perhaps
harder to see then.

To make some intuitive sense of those, note that a generator-iterator
reuses a single stack frame across resumptions.  There is only once
such frame per generator-iterator, hence only  (among other things)
one "program counter" per generator-iterator.  It should be obvious
that multiple threads can't be allowed to muck with _the_ frame's
program counter simultaneously, and the example above is actually
subtler on that count (because nothing in non-resumable functions
prepares you for that generators make it possible for a _single_
thread to _try_ to "be in two places at the same time" inside a single
invocation of a function -- although any attempt to try to do that
with a single thread is necessarily convoluted, like the example
above, the implementation still has to prevent it).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __del__ not called?

2006-03-13 Thread Duncan Booth
Gregor Horvath wrote:

> #!/usr/bin/python
> class A(object):
>def __init__(self):
>  print "init"
> 
>def __del__(self):
>  print "del"
> 
> test1.py
> 
> #!/usr/bin/python
> import test
> 
> class B(object):
>a = test.A()
> 
> Running test1.py outputs:
> 
> init
> 
> the "del" is missing.
> 
> I suppose the a object should be garbage collected!?

No, Python doesn't run the garbage collector when it is exiting. What it 
does is to delete all the globals from each module in turn. So:

C:\Python24>python
Python 2.4.2c1 (#66, Sep 21 2005, 15:16:11) [MSC v.1310 32 bit (Intel)] on 
win32

Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
...def __init__(self):
...  print "init"
...def __del__(self):
...  print "del called"
...
>>> a = A()
init
>>> ^Z

del called

C:\Python24>

In this case the del method is called as 'a' is deleted, but if you create 
a circular reference a does not get destroyed:

>>> class A(object):
...def __init__(self):
...  print "init"
...def __del__(self):
...  print "del called"
...
>>> a = A()
init
>>> a.ref = a
>>> ^Z


C:\Python24>

What is less obvious is that new style classes always include circular 
references, so a class is never detroyed until the garbage collector runs. 
A.__mro__ is a tuple which includes A, and there is probably something else 
I've forgotten (for an empty and otherwise unreferenced class 
getrefcount(oldstyleclass) returns 2, getrefcount(newstyleclass) returns 
5).

Of course, if your __del__ method actually does get invoked during program 
exit you have to be pretty careful what you do: the chances are any global 
variables you used in __del__ have already been destroyed in particular any 
modules you imported may have been deleted. In short, don't rely on 
anything much being possible from __del__ called this way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __del__ not called?

2006-03-13 Thread Gregor Horvath
Duncan Booth schrieb:

> What is less obvious is that new style classes always include circular 
> references, so a class is never detroyed until the garbage collector runs. 

Thanks. I tried the same example with old style classes and A.__del__ 
gets correctly called.

> Of course, if your __del__ method actually does get invoked during program 
> exit you have to be pretty careful what you do: the chances are any global 
> variables you used in __del__ have already been destroyed in particular any 
> modules you imported may have been deleted. In short, don't rely on 
> anything much being possible from __del__ called this way.

I wanted to close a database connection, which is opend by __init__.

But what happens to my database connection (instance attributes of A) 
when __del__ is never called?

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


Re: __del__ not called?

2006-03-13 Thread Tim Peters
[Duncan Booth]
> No, Python doesn't run the garbage collector when it is exiting.

Actually, it does.  What it doesn't do is call the garbage collector
twice when it exits, although it used to ;-)

> What it does is to delete all the globals from each module in turn. So:

Yup.  The code is in function Py_Finalize().  Here's the relevant snippet:

...
PyGC_Collect();

/* Destroy all modules */
PyImport_Cleanup();

/* Collect final garbage.  This disposes of cycles created by
 * new-style class definitions, for example.
 * XXX This is disabled because it caused too many problems.  If
 * XXX a __del__ or weakref callback triggers here, Python code has
 * XXX a hard time running, because even the sys module has been
 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
 * XXX One symptom is a sequence of information-free messages
 * XXX coming from threads (if a __del__ or callback is invoked,
 * XXX other threads can execute too, and any exception they encounter
 * XXX triggers a comedy of errors as subsystem after subsystem
 * XXX fails to find what it *expects* to find in sys to help report
 * XXX the exception and consequent unexpected failures).  I've also
 * XXX seen segfaults then, after adding print statements to the
 * XXX Python code getting called.
 */
#if 0
PyGC_Collect();
#endif

The first PyGC_Collect() runs, then what you described runs ("destroy
all modules"), and then  PyGC_Collect() _doesn't_ run again.  As the
comment says, it's the second run of PyGC_Collect() that _would_ get
rid of dead module-level new-style classes, were it to run.

Alas, as the XXX comments say, too much of the interpreter has been
destroyed by PyImport_Cleanup() for __del__ and weakref callbacks to
execute sanely, so we have to skip it.  And, of course, module-level
objects _aren't_ trash before PyImport_Cleanup() runs.  Therefore
module-level objects involved in reference cycles never trigger
__del__ or weakref callbacks as a side effect of Python exiting, and
new-style classes are (as you said) always involved in reference
cycles.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this possible in Python?

2006-03-13 Thread Azolex
Paul Rubin wrote:
> [EMAIL PROTECTED] writes:
>> assert magic_function(3+4)=="3+4"
>> assert magic_function([i for i in range(10)])=="i for i in range(10)]"
>>
>> It is not trivial at all and might require some bytecode hacking that i
>> am unable to do myself BUT you are the experts ;-)
> 
> Guhhh... you'd want to use the traceback system and reach back into
> the source code to get and parse the statement that called the magic
> function, sort of like a debugger does.

That's one way

> I don't think messing with
> the bytecode would help.

Well, the following package

http://packages.debian.org/stable/python/decompyle

might permit something like that.
-- 
http://mail.python.org/mailman/listinfo/python-list


SSL/TLS - am I doing it right?

2006-03-13 Thread Frank Millman
Hi all

I am writing a multi-user accounting/business application, which uses
sockets to communicate between client and server. I want to offer the
option of encrypting the traffic between the two. The main reason for
this is to cater for wireless communication.

I have read up on SSL, and more or less understand the concepts. I have
downloaded some additional software, read the instructions, and seem to
have got it working. However, I have no in-depth knowledge of what is
going on, and I have no idea how to check if I am doing it correctly.

The subject is too important to learn the hard way that I am doing
something wrong. Therefore I would be grateful if someone would review
the steps I have taken (listed below), and advise on whether there is
anything obviously wrong or missing.

TIA

Frank Millman


1. Install
--
  OpenSSL
  M2Crypto
  TLSLite

2. Create KeyPair + Certificate
---
  openssl genrsa -out privkey.key 1024
  openssl req -new -x509 -key privkey.key -out privkey.crt -days 1095
  cp privkey.key privkey.pem
  cat privkey.crt >> privkey.pem

3. Modify Server

  old -
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
while 1:
  conn,addr = s.accept()
  data = conn.recv(1024)

  new -
f = open('/home/frank/secrets/privkey.pem').read()
x509 = X509()
x509.parse(f)
certChain = X509CertChain([x509])
f = open('/home/frank/secrets/privkey.pem').read()
privateKey = parsePEMKey(f,private=True)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
while 1:
  conn,addr = s.accept()
  c = TLSConnection(conn)
  c.handshakeServer(certChain=certChain,privateKey=privateKey)
  data = c.recv(1024)

4.Modify Client
---
  old -
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(data)

  new -
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
c = TLSConnection(s)
c.handshakeClientCert()
c.send(data)

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


Re: Old Python Logo

2006-03-13 Thread Josef Meile
>>Can someone post a link or email me an image of the old Python logo?
>>I'd like to save a copy of it, I rather liked it - very retro.
> 
> 
> the dot matrix logo ?
> 
> you can get a copy from this page:
> 
>
That website is down. You could try the archive as well:
http://web.archive.org/web/20050401015445/http://www.python.org/

Regards
Josef

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


Re: Old Python Logo

2006-03-13 Thread Tim Parkin
Josef Meile wrote:
>>>Can someone post a link or email me an image of the old Python logo?
>>>I'd like to save a copy of it, I rather liked it - very retro.
>>
>>
>>the dot matrix logo ?
>>
>>you can get a copy from this page:
>>
>>
> 
> That website is down. You could try the archive as well:
> http://web.archive.org/web/20050401015445/http://www.python.org/

or you can look at http://archive-www.python.org which will be up for
the next month.

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


Re: __del__ not called?

2006-03-13 Thread Duncan Booth
Gregor Horvath wrote:

>> Of course, if your __del__ method actually does get invoked during
>> program exit you have to be pretty careful what you do: the chances
>> are any global variables you used in __del__ have already been
>> destroyed in particular any modules you imported may have been
>> deleted. In short, don't rely on anything much being possible from
>> __del__ called this way. 
> 
> I wanted to close a database connection, which is opend by __init__.
> 
> But what happens to my database connection (instance attributes of A) 
> when __del__ is never called?
> 

First off, never depend on __del__ to do anything critical. The only 
guarantee about the __del__ method on an object is that it will be called 
zero, one, or more times. (Admittedly you have to work a bit to get it 
called more than once.)

If you have a resource which absolutely must be tidied up, then always put 
the code which accesses that resource inside a try..finally construct. If 
it is something pretty global to your program than that try..finally might 
have to be at the outermost level of your program:

try:
   main()
finally:
   cleanup()

(In Python 2.5 you will be able to use a 'with' construct instead, but 
unfortunately we still have to wait a bit for that to become common usage).

Without knowing more about the specific database connection, I can't tell 
you what happens if you don't explicitly close it. I would hope that it 
will tidy itself up, but if your code keeps anything cached locally to be 
written out then obviously that might not get written.

If the database supports transactions (and it should), then I would expect 
anything modified in a transaction which has been commited will be written 
correctly, and everything modified in a transaction which has not been 
commited will be discarded: closing (or not) the database should be pretty 
well irrelevant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Old Python Logo

2006-03-13 Thread Fredrik Lundh
Josef Meile wrote:

> > you can get a copy from this page:
> >
> That website is down. You could try the archive as well:
> http://web.archive.org/web/20050401015445/http://www.python.org/

it's down for maintenance, but it wasn't down when I posted
that link...

you don't have to use the archive, btw.  the file is still there
on python.org:

http://www.python.org/pics/pythonHi.gif





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


Re: __del__ not called?

2006-03-13 Thread Gregor Horvath
Duncan Booth schrieb:

> First off, never depend on __del__ to do anything critical. The only 

Thanks to all of you!
Everything's clear now!

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


Re: Is this possible in Python?

2006-03-13 Thread Kay Schluehr

[EMAIL PROTECTED] wrote:
> Hi
>
> I wonder if Python is capable of the following: define a function which
> returns its argument.
> I mean:
> def magic_function(arg):
> .. some magic code ...
>
> that behaves the following way:
>
> assert magic_function(3+4)=="3+4"
> assert magic_function([i for i in range(10)])=="i for i in range(10)]"
>
> It is not trivial at all and might require some bytecode hacking that i
> am unable to do myself BUT you are the experts ;-)
>
> Alain

Storing arguments away before they are evaluated doesn't work in
Python. You have to hack the compiler in order to access the parsetree.
You might take a look at the compiler package of the standard library
that enables access to ASTs. Thus you could define lazy evaluation and
just-in-time compilation of some particular ASTs. I do not recommend
doing this for real purposes, but it is a good excercise and sooner or
later you become an expert yourself :)

Kay

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


Implement EJBs in Python/Jython

2006-03-13 Thread reinsn
Hi,

I'd like to know, if it's possible to implement EJB bean classes in
Python. I mean, Jython provides to possible to create *.class files
from python modules. How must my python module look like to create a
valid enterprise bean class from it.

Thanks in advance,

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


Re: Cheese Shop: some history for the new-comers

2006-03-13 Thread Max M
A.M. Kuchling wrote:
> On Sat, 11 Mar 2006 16:50:26 +1100, 
>   richard <[EMAIL PROTECTED]> wrote:
> 
>>So I did what people always do in this situation, I asked Barry Warsaw to
>>name. it. And he did, "Cheese Shop". I liked the name, so it was done. When
>>the new pydotorg machines went live last year, so too did the name
>>cheeseshop.python.org
> 
> 
> Given the endless whiny complaints about the name, though, I think we
> should just give up and go back to PyPI (pronounced 'Pippy').


When short obscure names are bad in programming, whay are they good in 
general communication.

"Python Packages" is too obvious perhaps?

When we start using eggs will it then be renamed to "Dairy Shop" or 
perhaps "Daisy" to make it obscure? Or the "Chickens Nest"?


Please. If it is meant to be used and understood, both Cheeseshop and 
Pypi are bad names.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie - Running Commands Interactively

2006-03-13 Thread Chris Bingham
Hi everyone,

I'm new to python, and I was wondering if anyone could help me with a
couple of problems I've hit please?

I'm trying to write a wrapper script for the passwd command, so that we
can log everytime someone uses it, which options they used with it and
if they succeeded or cancelled the command. The idea is that it'll look
to the user like they're running the original system passwd command,
but actually they're running it though this script.

At the moment my script looks like this:


#!/usr/bin/env python

import os
import coLog
import sys

result='failed'
if len(sys.argv) > 1:
  cmd="passwd"
  for arg in sys.argv[1:]:
cmd=cmd + " " + arg
else:
  cmd="passwd"

cmdRun=os.popen(cmd)

result=str(cmdRun.readlines())
print result
subResult=result.find('successfully')
print subResult

if subResult != '-1':
  coLog.add('Passwd', 'The user successfully executed the following
command: ' + cmd, 'CLI')
else:
  coLog.add('Passwd', 'The user executed the following command, but
it failed or was cancelled: ' + cmd, 'CLI')

# EOF


The 'coLog' module that get's imported at the start is 1 I wrote to do
the actual logging, so that i can easily reuse the code in other
scripts.

I've got 2 problems with it that i just haven't been able to fix;

1. Firstly, if I use os.popen to execute the command, the first & last
lines of the command's output don't get displayed, i can get them later
from the 'cmdRun' variable and print them, but then it doens't look
like the original passwd command. I've found that using os.system
instead fixes this issue, but then pressing ctrl-c during the command
causes the shell ure in to go cooco-lala on u! :) os.popen works
correctly with ctrl-c. I also tried os.popen2, but this caused the
passwd command to go nuts!

2. Secondly, if ctrl-c is pressed the script gets killed along with the
command, so it doens't log cancelled commands. I've tried using various
variations of 'try, except', including catching the KeyboardInterrupt
and catching all exceptions, but nothing seemed to work!

I've been struggling with these 2 issues for the last week, and so far
no joy. If anyone has any idea how to fix them I'd really appreciate
the help! :)

Thanks in advance for any help anybody can give,

Chris

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


Re: Cheese Shop: some history for the new-comers

2006-03-13 Thread Sybren Stuvel
A.M. Kuchling enlightened us with:
> Given the endless whiny complaints about the name, though, I think
> we should just give up and go back to PyPI (pronounced 'Pippy').

I love The Python Cheese Shop. It's original and distinctive. Besides
that, it gives you more information that PyPI since Python is written
fully.

Not every name has to fully reflect the named. I mean, Microsoft is
the largest software company on the planet, but no way that you can
guess that from the name.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Sybren Stuvel
Frank Millman enlightened us with:
> while 1:
>   conn,addr = s.accept()
>   c = TLSConnection(conn)
>   c.handshakeServer(certChain=certChain,privateKey=privateKey)
>   data = c.recv(1024)

It's nice that you set up a TLS connection, but you never check the
certificate of the other side for vality. You should make sure the
certificate chain is completely signed from top to bottom. Then check
that the bottom certificate is amongst trusted CAs. Also check all the
certificates in the chain against the CRL of the CA. I've submitted
this CRL check to the author of TLS Lite, so it should be in a release
soon.

> s.connect((HOST,PORT))
> c = TLSConnection(s)
> c.handshakeClientCert()
> c.send(data)

See above. You set up a TLS connection, but you never verify that
you're talking to the right computer.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python crashes in Komodo

2006-03-13 Thread jimlewis
> any non-standard (i.e. non-bundled) C extensions ?

No.

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


Re: Cheese Shop: some history for the new-comers

2006-03-13 Thread Michael

> Not every name has to fully reflect the named. I mean, Microsoft is
> the largest software company on the planet, but no way that you can
> guess that from the name.
>   
MICRO computer SOFTware. Seems pretty obvious to me and I'd expect the 
same from any tech person.pipi and cheese shop both sound like so-so 
names to me. Neither sounds to be especially easy for people to remember 
and find when searching using generic half remembered terms. Not really 
important though so long as they are easy to find from the Python website.

-- 
Michael McGlothlin, tech monkey
Tub Monkey
http://www.tubmonkey.com/

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


Re: Implement EJBs in Python/Jython

2006-03-13 Thread Diez B. Roggisch
reinsn wrote:

> Hi,
> 
> I'd like to know, if it's possible to implement EJB bean classes in
> Python. I mean, Jython provides to possible to create *.class files
> from python modules. How must my python module look like to create a
> valid enterprise bean class from it.

You have to compile a class that implements the EJB-Interface. Look for
examples that do that for other classes like struts actions, and perform
accordingly.

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


Environmental Variables

2006-03-13 Thread Sathyaish
In which physical file are the python environmental variables located?
I know I can access them using the:


os.environ.get('PYTHONSTARTUP')

or

os.environ.get('PYTHONPATH')


to get their values. But out of the program, if I need to look at them
and alter their values, where do I find them? Are they the OS
environmental variables as I suspect? If they are, then I'll find them
with the other OS environ variables in My
Computer->System->Properties->Advanced->Environmental Variables.

But I checked that place and did not find any default values for them.

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


Re: Cheese Shop: some history for the new-comers

2006-03-13 Thread Sybren Stuvel
Michael enlightened us with:
>> Microsoft is the largest software company on the planet, but no way
>> that you can guess that from the name.
>
> MICRO computer SOFTware. Seems pretty obvious to me

Where is the size of the company in that story? The fact that they
make software is rather obvious indeed. Just as obvious as that PYTHON
Cheese Shop has something to do with Python.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE: great headache....

2006-03-13 Thread Joel Hedlund
>> Anyone knows if this platform is a good one?

It's very good. It's comfortable, helpful and stable. Also looks good.

> Eclipse + Pydev does most, if not all, of your list - I am not sure what 
> you mean by conditional pause -  plus a whole lot more.  

Maybe he means conditional breakpoints? PyDev certainly has that.

> I like Eclipse, but lots of folks on the Python groups seem to hate it 
> with a passion.

Any ideas why?

> If you install Eclipse and try to use it without reading the Workbench 
> User Guide then you are not going to get anywhere.

Woah, easy now! I never read any "Workbench User Guide" and I'm doing just fine 
with PyDev. Fabio Zadrozny (PyDev developer) wrote an excellent startup guide 
for python programmers that includes installing and basic editing:

http://www.fabioz.com/pydev/manual_101_root.html

It's all I ever read and it was enough for me to get going with Eclipse + PyDev 
within 15 minutes on a WinXP machine. 

On a side note: with Ubuntulinux 5.10 it was more of a hassle, but that was 
just to get Eclipse running smoothly. I.e: an Eclipse/apt/Java problem. Once 
that was neatly in place, that guide above worked flawlessly.

Cheers!
/Joel Hedlund
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Environmental Variables

2006-03-13 Thread Diez B. Roggisch
Sathyaish wrote:

> In which physical file are the python environmental variables located?
> I know I can access them using the:
> 
> 
> os.environ.get('PYTHONSTARTUP')
> 
> or
> 
> os.environ.get('PYTHONPATH')
> 
> 
> to get their values. But out of the program, if I need to look at them
> and alter their values, where do I find them? Are they the OS
> environmental variables as I suspect? If they are, then I'll find them
> with the other OS environ variables in My
> Computer->System->Properties->Advanced->Environmental Variables.
> 
> But I checked that place and did not find any default values for them.

They aren't necessarily stored somewhere - except in memory. You can open a
cmd-prompt and do something like

set FOO "bar" 

(syntax may vary, I'm a UNIX-guy)

Then you will be able to access this variable from a process - like python.
But it is nowhere saved.

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


Anomalous behaviour when compiling regular expressions?

2006-03-13 Thread Harvey.Thomas
>>> import re
>>> r = re.compile('(a|b*)+')
Traceback (most recent call last):
  File "", line 1, in ?
  File "c:\python24\lib\sre.py", line 180, in compile
return _compile(pattern, flags)
  File "c:\python24\lib\sre.py", line 227, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat

but

>>> r = re.compile('(a|b*c*)+')
>>> r.match('def').group()
''

Why is there a difference in behaviour between the two cases. Surely the
two cases are equivalent to:

>>> r = re.compile('(a|b)*')
>>> r.match('def').group()
''

and 

>>> r = re.compile('(a|b|c)*')
>>> r.match('def').group()
''

Harvey


The information contained in this email message may be confidential. If you are 
not the intended recipient, any use, interference with, disclosure or copying 
of this material is unauthorised and prohibited. Although this message and any 
attachments are believed to be free of viruses, no responsibility is accepted 
by Informa for any loss or damage arising in any way from receipt or use 
thereof.  Messages to and from the company are monitored for operational 
reasons and in accordance with lawful business practices. 
If you have received this message in error, please notify us by return and 
delete the message and any attachments.  Further enquiries/returns can be sent 
to [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Environmental Variables

2006-03-13 Thread Fredrik Lundh
Sathyaish wrote:

> In which physical file are the python environmental variables located?
> I know I can access them using the:
>
>
> os.environ.get('PYTHONSTARTUP')
>
> or
>
> os.environ.get('PYTHONPATH')
>
>
> to get their values. But out of the program, if I need to look at them
> and alter their values, where do I find them? Are they the OS
> environmental variables as I suspect?

yes.

> If they are, then I'll find them with the other OS environ variables in My
> Computer->System->Properties->Advanced->Environmental Variables.

yes, provided that they've been set, and set via that dialogue (and not
by some startup script or other mechanism).

> But I checked that place and did not find any default values for them.

there are no default values for the variables you mention.

(as written, the environ.get call returns None if the variable is not set)





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


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Frank Millman

Sybren Stuvel wrote:
> Frank Millman enlightened us with:
> > while 1:
> >   conn,addr = s.accept()
> >   c = TLSConnection(conn)
> >   c.handshakeServer(certChain=certChain,privateKey=privateKey)
> >   data = c.recv(1024)
>
> It's nice that you set up a TLS connection, but you never check the
> certificate of the other side for vality. You should make sure the
> certificate chain is completely signed from top to bottom. Then check
> that the bottom certificate is amongst trusted CAs. Also check all the
> certificates in the chain against the CRL of the CA.

Thanks for the reply, Sybren.

I was hoping to avoid this step. The point of the exercise for me is
encryption. I am not too worried about authentication. The next step in
my app is for the client to enter a user id and password, and the
server will not proceed without verifying this.

However, I realise that security is not something to be trivialised, so
if your recommendation is that I do complete the validation steps, I
will try to understand that part of the documentation and apply that as
well.

Thanks

Frank

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


Re: Please, I Have A Question before I get started

2006-03-13 Thread Diez B. Roggisch
Skipper wrote:

> Hi All,
> 
> I am going to try and learn Python because I want to write at least
> one program to help my disabled son with communitation.
> 
> I am not asking for anyone to do this for me I simply want to know if
> I can do what I need to do with Python 
> 
> Basically the program will blank the screen and call up (for example)
> 6 pictures.  A flashing border with travel from picture to picture.
> When the computer senses a mouse click it will clear the screen and
> present a second set of choices ... one level deeper than the first
> ... based on the chosen picture.
> 

Are you aware of this:

http://pythonology.org/success&story=natsworld

Maybe it offers what you need - and certainly it shows that these kind of
things can be done using pygame.

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


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Paul Rubin
"Frank Millman" <[EMAIL PROTECTED]> writes:
> I was hoping to avoid this step. The point of the exercise for me is
> encryption. I am not too worried about authentication. The next step in
> my app is for the client to enter a user id and password, and the
> server will not proceed without verifying this.

That is a total disaster without authentication, since it means the
client can reveal the password to an imposter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Frank Millman

Paul Rubin wrote:
> "Frank Millman" <[EMAIL PROTECTED]> writes:
> > I was hoping to avoid this step. The point of the exercise for me is
> > encryption. I am not too worried about authentication. The next step in
> > my app is for the client to enter a user id and password, and the
> > server will not proceed without verifying this.
>
> That is a total disaster without authentication, since it means the
> client can reveal the password to an imposter.

Understood. You cannot have encryption without authentication - they go
hand in hand.

Back to the documentation.

Thanks, Paul

Frank

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


Re: Python IDE: great headache....

2006-03-13 Thread 3KWA
Vim + iPython does most of it doesn't it?

That's where I am after I became a bit frustrated with Idle (which I
still use on odd occasions).

EuGeNe

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


Re: Environmental Variables

2006-03-13 Thread Sathyaish
Thanks for the replies.

I am trying to have a startup file execute everytime I launch the
interpreter. So, for a test, I wrote a small file I called
"Sathyaish.py". The contents of the file were simply:

# ! This is my new start-up file.

print "Sathyaish is the best."


Then, in the interpreter, on its prompt, I said:

>>> os.environ['PYTHONSTARTUP'] = 'C:\\Sathyaish.py'
>>>

It didn't complain. I tested it immediately. On the same interpreter
instance, I said:

>>> import os
>>> os.environ.get('PYTHONSTARTUP')

It gave me back 'C:\Sathyaish.py'. I didn't close that interpreter. I
left it open and launched a new instance of the interpreter. In this I
queried the same:


>>> import os
>>> os.environ.get('PYTHONSTARTUP')
None

was what I got. I checked the at DOS prompt (cmd) for PYTHONSTARTUP,
and I got an 'unrecognized program/command/batch file' interrupt.

What's the deal with environmental variables? Are they specific to an
interpreter session? That shouldn't be.

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


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Sybren Stuvel
Frank Millman enlightened us with:
> The point of the exercise for me is encryption. I am not too worried
> about authentication.

Encryption can't function fully without authenication.

> The next step in my app is for the client to enter a user id and
> password, and the server will not proceed without verifying this.

But the client is willing to give that username and password to
anybody that's listening. It doesn't authenticate the server, so it
can be very easily tricked into talking to someone else. Your system
is open to Man in the Middle attacks.

> However, I realise that security is not something to be trivialised,
> so if your recommendation is that I do complete the validation
> steps, I will try to understand that part of the documentation and
> apply that as well.

That is indeed my recommendation indeed :)

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anomalous behaviour when compiling regular expressions?

2006-03-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> >>> import re
> >>> r = re.compile('(a|b*)+')
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "c:\python24\lib\sre.py", line 180, in compile
> return _compile(pattern, flags)
>   File "c:\python24\lib\sre.py", line 227, in _compile
> raise error, v # invalid expression
> sre_constants.error: nothing to repeat
>
> but
>
> >>> r = re.compile('(a|b*c*)+')
> >>> r.match('def').group()
> ''
>
> Why is there a difference in behaviour between the two cases. Surely the
> two cases are equivalent to:
>
> >>> r = re.compile('(a|b)*')
> >>> r.match('def').group()
> ''

equivalent?


>>> re.match("(a|b*c*)", "abc").groups()
('a',)

>>> re.match("(a|b)*", "abc").groups()
('b',)


I have no time to sort out why your second example doesn't give the
same error (that might be a bug in the RE compiler), but no, a repeated
group with a min-length of 1 is not, in general, the same thing as a re-
peated group with a min-length of zero.





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


Re: Anomalous behaviour when compiling regular expressions?

2006-03-13 Thread Fredrik Lundh
Fredrik Lundh wrote:

> I have no time to sort out why your second example doesn't give the
> same error

oh, it was there it went.





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


Re: Environmental Variables

2006-03-13 Thread Diez B. Roggisch
> was what I got. I checked the at DOS prompt (cmd) for PYTHONSTARTUP,
> and I got an 'unrecognized program/command/batch file' interrupt.
> 
> What's the deal with environmental variables? Are they specific to an
> interpreter session? That shouldn't be.

Yes they are - and yes, it should be that way. A process inherits the
environment of its parent. It can set its own environment, and if it forks
children, these will see that. But there is no way for a process to alter
the environment of its parent, let alone some arbitrary other process. This
is an OS-limitation (or feature) - so if you absolutely have to convince
somebody that it is bad, try Redmond :)

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


Re: Environmental Variables

2006-03-13 Thread Duncan Booth
Sathyaish wrote:

> What's the deal with environmental variables? Are they specific to an
> interpreter session? That shouldn't be.

If you think that then complain to Microsoft, or even the people who 
developed Unix since that is what Microsoft based their environment 
variables on.

Environment variables work the same way in Python as they do in any other 
process: any process can modify its own environment variables and pass 
those changes down to other processes which it starts, but no process can 
modify the environment of its parent process or any other process in the 
system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Environmental Variables

2006-03-13 Thread Fredrik Lundh
Sathyaish wrote:

> What's the deal with environmental variables? Are they specific to an
> interpreter session?

they're copied from the parent process when a new process is started,
and any changes to them are local to the process.

> That shouldn't be.

that's how environment variables work, on all platforms.





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


Re: Anomalous behaviour when compiling regular expressions?

2006-03-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> >>> import re
> >>> r = re.compile('(a|b*)+')
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "c:\python24\lib\sre.py", line 180, in compile
> return _compile(pattern, flags)
>   File "c:\python24\lib\sre.py", line 227, in _compile
> raise error, v # invalid expression
> sre_constants.error: nothing to repeat
>
> but
>
> >>> r = re.compile('(a|b*c*)+')
> >>> r.match('def').group()
> ''
>
> Why is there a difference in behaviour between the two cases. Surely the
> two cases are equivalent to:
>
> >>> r = re.compile('(a|b)*')
> >>> r.match('def').group()
> ''
>
> and
>
> >>> r = re.compile('(a|b|c)*')
> >>> r.match('def').group()
> ''

your definition of "equivalent" is a bit unusual:

>>> re.match("(a|b*c*)+", "abc").groups()
('',)
>>> re.match("(a|b)*", "abc").groups()
('b',)
>>> re.match("(a|b|c)*", "abc").groups()
('c',)

that you don't get an error for

> >>> r = re.compile('(a|b*c*)+')
> >>> r.match('def').group()

might be a compiler bug.  running it on 2.3 gives you another error,
though:

>>> re.match("(a|b*c*)+", "abc").groups()
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\python23\lib\sre.py", line 132, in match
return _compile(pattern, flags).match(string)
RuntimeError: maximum recursion limit exceeded

(a repeated group with a min-length of zero can match anything an
infinite number of times, which is, in general, not what you want)





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


Re: Please, I Have A Question before I get started

2006-03-13 Thread Skipper
Thank you all so much for your input.  The feedback was perfect.  I
did not realizethis may be difficult under any circumstances.

I am very familiar with PowerPoint and will try the open office
thing...

I can not believe that there isn't a GUI programing tool that will
allow me to build GUI apps - just like I use Dreamweaver to build a
web page ... a WYSIWYG builder that does a few simplet things and
calls other programs ...

Oh well  no silver bullet!

Thanks again
Mike







On Mon, 13 Mar 2006 13:45:05 +1100, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:

>On Mon, 13 Mar 2006 02:19:39 +, Skipper wrote:
>
>> Hi All,
>> 
>> I am going to try and learn Python because I want to write at least
>> one program to help my disabled son with communitation.
>> 
>> I am not asking for anyone to do this for me I simply want to know if
>> I can do what I need to do with Python 
>
>[snip]
>
>> Can python do this?  I realize I am responsible for the menu sets,
>> pictures  attaching sounds etc  
>
>There is no reason why Python can't do this.
>
>If you are new to programming, I suggest you have a look at Pythoncard.
>Unfortunately, most of the Graphical User Interface libraries for Python
>have a fairly steep learning curve, and in general building GUIs can be
>tedious and difficult, regardless of language. Pythoncard is an attempt to
>simplify the whole process and make simple things simple.
>
>http://pythoncard.sourceforge.net/

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


Re: Environmental Variables

2006-03-13 Thread Sathyaish
I recall now, the shells in Unix - a child inherited the variables
declared in its parent but not vice-versa. It works the same way in
DOS. So, I wasn't seeing it clearly earlier. I am seeing it clearly
now. I was imagining that the PYTHONPATH had some default value on
installation and was expecting to see it. And since it was an
*environmental* variable I was setting, I just expected it to turn up
in the entire environment, totally forgetting the scope of the
environment I was declaring it in - a process and not an OS.

Thanks.

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


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Frank Millman

Sybren Stuvel wrote:
> Frank Millman enlightened us with:
> > The point of the exercise for me is encryption. I am not too worried
> > about authentication.
>
> Encryption can't function fully without authenication.
>

Ok, I have been thinking about the replies from you and Paul, and I am
confused (nothing new).

Let's keep it simple, and assume that the client and the server are on
the same network. The server runs with restricted permissions, with
access to the database. A client can only access the server through a
client connection.

A client can be any workstation on the network. To be able to function
as a client, it needs a pointer to the client software, and it needs a
pointer to a parameter that tells it where to find the server - ip
address/port number.

If I understand correctly, a 'man-in-the-middle' attack would involve
someone setting up a 'pseudo server', which gives the correct responses
to the client's attempt to log in; and would also involve someone
manipulating the client parameter so that it points to the pseudo
server instead of the real server. This would indeed allow the pseudo
server to obtain the user id and password fraudulently.

What I have not understood is how to prevent this. How can the client
distinguish between a valid server and a fraudulent one? If it obtains
the server credentials dynamically, the fraudulent server can supply
fraudulent credentials. If somehow the client must know in advance what
the credentials are, then these can only be as secure as the parameter
that tells the client how to connect in the first place.

I more or less understand the concept of setting up a secure server,
with a signed key that can be validated via a trusted authority, but
surely it is not necessary for every user of my software to register
with such an authority before they can get protected communication
between their own clients and their own server.

I am sure I am missing the point somewhere. Any advice, or links to
literature that explain this in more detail, will be much appreciated.

Thanks

Frank

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


Re: __del__ not called?

2006-03-13 Thread bruno at modulix
Gregor Horvath wrote:
> Felipe Almeida Lessa schrieb:
> 
>del B
># We'll to tell him to collect the garbage here, but
>>
>> ... # usually it should not be necessary.
> 
> Thanks. If I do
> 
> del B
> 
> then the __del__ of A gets called.
> That surprises me.

Why ?

> I thought that B gets del'd by python when it goes
> out of scope?

It does. What you have to understand here is that in your script, B
being in the global (read : module) scope, it doesnt goes out of scope
before the script's execution's done. By that time, it's too late to do
anything with stdin/stdout/stderr.

Just add this to the script:

def foo():
  b = B()
  print "in foo"

foo()

> Do I manually have to del all class objects, so that their class
> attributes get gc'd 

Absolutely not. The only times I use del is when I want to cleanup a
namespace from temp vars no longer used (usually a module's namespace
with some hairy tricks at load time).



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


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Paul Rubin
"Frank Millman" <[EMAIL PROTECTED]> writes:
> What I have not understood is how to prevent this. How can the client
> distinguish between a valid server and a fraudulent one? If it obtains
> the server credentials dynamically, the fraudulent server can supply
> fraudulent credentials. If somehow the client must know in advance what
> the credentials are, then these can only be as secure as the parameter
> that tells the client how to connect in the first place.

The client and the server each needs to know the public key of the
"certificate authority" (or CA) that issued the root of the chain of
certificates that the other side presents.  For a public server you'd
use a commercial CA.  For a local network you could run your own CA;
for example, OpenSSL (www.openssl.org) comes with a simple Perl script
that acts as a rudimentary CA.

Note that TLSLite at the moment doesn't know how to authenticate
certificate chains all by itself without external libraries.  I didn't
look at your code sample closely enough to figure out whether you were
using OpenSSL or M2Crypto in a way that takes care of that.

> I am sure I am missing the point somewhere. Any advice, or links to
> literature that explain this in more detail, will be much appreciated.

This might help:

  http://www.modssl.org/docs/2.8/ssl_intro.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please, I Have A Question before I get started

2006-03-13 Thread Sybren Stuvel
Skipper enlightened us with:
> I can not believe that there isn't a GUI programing tool that will
> allow me to build GUI apps

There are plenty of them.

> just like I use Dreamweaver to build a web page

Which produces horrible HTML.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Sybren Stuvel
Frank Millman enlightened us with:
> If I understand correctly, a 'man-in-the-middle' attack would
> involve someone setting up a 'pseudo server', which gives the
> correct responses to the client's attempt to log in

That's right. Usually it's done by proxying the data between the
client and the real server.

> and would also involve someone manipulating the client parameter so
> that it points to the pseudo server instead of the real server.

Yup. This can be done in various ways, like ARP poisoning of the
network. Then the IP address will not change, but the network card
that the traffic is sent to will. The fraudulent server, having the
correct ARP table, can then forward the captured data to the real
server.

> What I have not understood is how to prevent this. How can the
> client distinguish between a valid server and a fraudulent one?

By checking the certificates. The CA mustn't sign server certificates
except for the real server. The fraudulent server thus has no valid
server certificate.

> If it obtains the server credentials dynamically, the fraudulent
> server can supply fraudulent credentials. If somehow the client must
> know in advance what the credentials are, then these can only be as
> secure as the parameter that tells the client how to connect in the
> first place.

True, but as you can see above, making the client talk to another
computer doesn't have to involve accessing and changing the client's
filesystem.

> I more or less understand the concept of setting up a secure server,
> with a signed key that can be validated via a trusted authority, but
> surely it is not necessary for every user of my software to register
> with such an authority before they can get protected communication
> between their own clients and their own server.

If you want to be secure, that *is* necessary. Every client should
have a valid, signed certificate, and every server should too.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


is hk_classes python interface good?

2006-03-13 Thread piotr maliński
Ive found hk_classes a C++/Python library/module for accesing
databases. It works nice for me but I wonder if someone used
hk_classes in a project, is this module good, etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


automatic from module import * expansion

2006-03-13 Thread Keith Jackson
Does anybody know of a tool that will take a module as input, look for 
any wildcard imports, and then identify what symbols in the module come 
from which wildcard import? It could then expand out the from module 
import * to from module import foo, bar. It might need to ask the user 
on this, since they might want the wildcard import for something 
special, but it would still be *much* nicer then expanding the imports 
out by hand.

Apologies ahead of time if I've missed something obvious. I did spend 
some quality time with google, and couldn't find anything.
cheers,
--keith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE: great headache....

2006-03-13 Thread Don Taylor
Joel Hedlund wrote:

>> If you install Eclipse and try to use it without reading the
>> Workbench User Guide then you are not going to get anywhere.
> 
> 
> Woah, easy now! I never read any "Workbench User Guide" and I'm doing
> just fine with PyDev. Fabio Zadrozny (PyDev developer) wrote an
> excellent startup guide for python programmers that includes
> installing and basic editing:
> 
> http://www.fabioz.com/pydev/manual_101_root.html
> 
> It's all I ever read and it was enough for me to get going with
> Eclipse + PyDev within 15 minutes on a WinXP machine.
> 

Sorry to offend, I was just extrapoloating from personal experience.

When I was looking for a Java IDE I tried IntelliJ Idea, Netbeans and
Eclipse in that order.  I found that I could use Idea and Netbeans
without reading the manuals, but I could not get going with Eclipse
until I read the Workbench User Guide and got the hang of perspectives
and views.  Even installing it the first time seemed to be a mystery.
It is not difficult at all, just different.  In retrospect, I don't know
why I found it puzzling but I have met others who have had the same 
experience.

It has improved a lot recently, but even the Eclipse web-site was hard 
to navigate.  I think that a lot of the puzzlement comes from the fact 
that the Eclipse folks present Eclipse not as an IDE, but as a framework 
  where one of the applications happens to be an IDE.

Don.

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


mydate.strftime('%x') and cgi script

2006-03-13 Thread Sibylle Koczian
Hello,

I'm writing a cgi script which only needs to run in a small LAN. I tried
to show dates in a reasonable format by using

import locale
import datetime

locale.setlocale(locale.LC_ALL, '')
...
dt = datetime.date.today()
print dt.strftime('%x')

This works well in other scripts or at the interactive prompt. It
doesn't work in a cgi script: in the browser the date is shown as
'mm/dd/' which is _not_ my 'Locale's appropriate date
representation' as the documentation for strftime calls it.

The workaround is simple: explicit description of the right format works
('%d.%m.%Y'). But why doesn't the short form work as well?

Thank you for explanations or links to them,
Koczian

-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't simultaneously read/write from ossaudio dsp device

2006-03-13 Thread Tito
I got it working!  There was another thread http://tinyurl.com/pebqc on
this group where someone had the same problem.  I changed my code to
the following:

from twisted.internet.task import LoopingCall
from twisted.internet import reactor
import os, sys, wave, audioop

"""
While playing the contents of test1.wav,  talk into the mic
and have the audio recorded into /tmp/out.wav
"""

def playnlisten_out():
audio = wavin.readframes(1024)
stereoaudio = audioop.tostereo(audio, 2, 1, 1)
dspout.write(stereoaudio)

def playnlisten_in():
audio = dspin.read(640)
wavout.write(audio)

def both():
playnlisten_out()
playnlisten_in()

dspout = ossaudiodev.open('/dev/dsp', 'w')# 2 file handles
dspin = ossaudiodev.open('/dev/dsp', 'r')

wavin = wave.open("test1.wav", "r")
wavout = wave.open("/tmp/out.wav", "w")

both_loop = LoopingCall(both)
both_loop.start(0.02)

reactor.run()

and it worked as expected.  I did not need to mess around with
/dev/mixer.

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


Re: SSL/TLS - am I doing it right?

2006-03-13 Thread Sybren Stuvel
Paul Rubin enlightened us with:
> for example, OpenSSL (www.openssl.org) comes with a simple Perl
> script that acts as a rudimentary CA.

I never understood those CA scripts. I mean, creating a new CA
certificate only has to be done once, and is:

openssl req -new -x509 -key $KEY -out $OUT -days 365 -config $CONF

Signing a certificate request is easier:

openssl ca -in some.req

Why do people feel the need to wrap that up in some Perl script?

> Note that TLSLite at the moment doesn't know how to authenticate
> certificate chains all by itself without external libraries.  I
> didn't look at your code sample closely enough to figure out whether
> you were using OpenSSL or M2Crypto in a way that takes care of that.

TLS Lite can use both, and cryptlib_py too. For proper verification,
you need the latter. My CRL checks also require cryptlib.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speed of data structures in python

2006-03-13 Thread Dave

As the OP, i thought i'd follow up with my experience, in case anyone else  
is learning pyopengl and as mystified as i was (am?).

Thank you to all the posters who responded, especially the one who  
mentioned display lists...

Initially, i had built a very simple prototype, getting 5 fps. This was  
very poorly designed though, calculating normals and positions (sqrt, sin,  
pow) on the fly.

when i posted the OP, i suspecteded that the biggest improvement would be  
achieved by storing the normals and positions in the fastest data  
structure.

after posting, i implemented numpy arrays to hold normals and positions,  
and got 18 fps.

i then increased the complexity of the protoype to the bare-min specs  
required, and got 1-2 fps.

i then implemented display lists (opengl stuff), and am now getting 190  
fps (on the larger protoype).

so, my point is, the limiting factor had nothing to do with speed of data  
structures in python, but the way data was being consumed by opengl (and  
my absolute newbieness at opengl ;-)

i hope this helps anyone who is learning similar material

Dave



On Sat, 11 Mar 2006 16:54:06 +1100, Steven D'Aprano  
<[EMAIL PROTECTED]> wrote:

> On Fri, 10 Mar 2006 21:06:27 -0600, Terry Hancock wrote:
>
>> On Sat, 11 Mar 2006 13:12:30 +1100
>> "Steven D'Aprano" <[EMAIL PROTECTED]> wrote:
>>> On Fri, 10 Mar 2006 23:24:46 +1100, Dave wrote:
>>> > Hi. I am learning PyOpenGL and I am working with a
>>> > largish fixed scene   composed of several thousand
>>> > GLtriangles. I plan to store the coords and   normals in
>>> > a NumPy array.
>>> >
>>> > Is this the fastest solution in python?
>>
>>> Optimization without measurement is at best a waste of
>>> time and at worst counter-productive. Why don't you time
>>> your code and see if it is fast enough?
>>>
>>> See the timeit module, and the profiler.
>>
>> Talk about knee-jerk reactions. ;-)
>
> Yes, let's.
>
>> It's a *3D animation* module -- of course it's going to be
>> time-critical.  Sheesh.  Now *that* is stating the obvious.
>
> Did I say it wasn't? I asked if the current solution is fast enough. If
> the current solution is fast enough, then why waste time trying to speed
> it up? Does the Original Poster think that PCs will get slower in the
> future?
>
>
>> The obvious solution is actually a list of tuples.
>
> But that's not the solution being asked about, nor did I suggest it.
>
>
>> But
>> it's very possible that that won't be fast enough, so the
>> NumPy approach may be a significant speedup. I doubt you
>> need more than that, though.
>
> I didn't argue against the NumPy approach. I suggested that, instead of
> *asking* if there was something faster, the O.P. should actually *try it*
> and see if it is fast enough.
>
> If you think that is bad advice, please tell us what you consider good
> advice.
>
>
>



-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/

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


Global Threading Lock 2 - Re: "RuntimeError: dictionary changed size during iteration"..

2006-03-13 Thread robert
Raymond Hettinger wrote:
>>Is a copy.deepcopy  ( -> "cPickle.dump(copy.deepcopy(obj),f)" ) an
>>atomic opertion with a guarantee to not fail?
> 
> No.  It is non-atomic.
> 
> It seems that your application design intrinsically incorporates a race
> condition -- even if deepcopying and pickling were atomic, there would
> be no guarantee whether the pickle dump occurs before or after another
> thread modifies the structure.  While that design smells of a rat, it
> may be that your apps can accept a dump of any consistent state and
> that possibly concurrent transactions may be randomly included or
> excluded without affecting the result.

Yes it is designed so with a discipline to be consistent and to allow 
many threads without much locking; and the .dump is a autosave/backup 
(=> ok at any time).

The requirement is weaker than atomicity. "Not crash" would be ok. In 
that case the file was stored half => a corrupt pickle.
( In that case the app worked with a auto-multi-backup strategy, so the 
crashed app recovered auto form the next backup at UnpicklingError, but 
  a real workaround is not possible without rewriting dump or deepcopy - 
I use this multi-try on RuntimeError so far, but thats not "legal Python 
code" )

> Python's traditional recommendation is to put all access to a resource
> in one thread and to have other threads communicate their transaction
> requests via the Queue module.  Getting results back was either done
> through other Queues or by passing data through a memory location
> unique to each thread.  The latter approach has become trivially simple
> with the advent of Py2.4's thread-local variables.

(passing through TLS? TLS are usally used for not-passing, or?)

That queue/passing-through-only-an-extra-global-var communication is 
acceptable for thin thread interaction.
( hope this extra global var is thread-safe in future Python's :-) )

But "real" thread-programming should also be possible in Python - and it 
is with the usual discipline in thread programming. This RuntimeError in 
iterations is the (necessary) only compromise, I know of. (Maybe this 
RuntimeError must not even be thrown from Python, when walking through 
variable sequences is done smartly - but smart practice may cost speed, 
so a compromise.)

It can be handled commonly by keys() and some error catching. key 
functions like deepcopy and dump (which cannot easily be subclassed) 
should fit into that "highest common factor" and not "judge" themselves 
about _how_ thread programming has to be done.


> Thinking about future directions for Python threading, I wonder if
> there is a way to expose the GIL (or simply impose a temporary
> moratorium on thread switches) so that it becomes easy to introduce
> atomicity when needed:
> 
>gil.acquire(BLOCK=True)
>try:
>   #do some transaction that needs to be atomic
>finally:
>   gil.release()

Thats exectly what I requested here:

<[EMAIL PROTECTED]>

and here:

<[EMAIL PROTECTED]>

That "practical hammer" (little ugly, but very practical) would enable 
to keep big threaded code VHL pythonic and keep us from putting 
thousands of trivial locks into the code in low level language manner. 
Some OS-functions like those of the socket module (on UNIX) do so anyway 
( often unwanted :-( )

In addition Python should define its time atoms, and thus also the 
definite sources of this (unavoidable?) RuntimeError - as explained in 
the later link.

>>Or can I only retry several times in case of RuntimeError?  (which would
>>apears to me as odd gambling; retry how often?)
> 
> 
> Since the app doesn't seem to care when the dump occurs,  it might be
> natural to put it in a while-loop that continuously retries until it
> succeeds; however, you still run the risk that other threads may never
> leave the object alone long enough to dump completely.

I have 5 trials max as of now. The error was about once in 3 months in 
my case: that should solve the problem for the rest of the universe ...
If not, there is another bug going on.

I may switch to a solution with subclassed deepcopy withough 
.iteritems(). But its lot of work to ensure,that it is really ok  - and 
consumes another few megs of memory and a frequent CPU peakload. So I 
may leave the loop and may probably not switch at all ...

Robert

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


Re: How to best update remote compressed, encrypted archives incrementally?

2006-03-13 Thread robert
[EMAIL PROTECTED] wrote:

> Would rsync into a remote encrypted filesystem work for you?
> 

the sync (selection) is custom anyway. The remote filesystem is 
general/unknow.   FTP(S) / SFTP is the only standard given.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: automatic from module import * expansion

2006-03-13 Thread Diez B. Roggisch
Keith Jackson wrote:

> Does anybody know of a tool that will take a module as input, look for
> any wildcard imports, and then identify what symbols in the module come
> from which wildcard import? It could then expand out the from module
> import * to from module import foo, bar. It might need to ask the user
> on this, since they might want the wildcard import for something
> special, but it would still be *much* nicer then expanding the imports
> out by hand.
> 
> Apologies ahead of time if I've missed something obvious. I did spend
> some quality time with google, and couldn't find anything.

No - and given that you could do

--- module.py ---
import random

for i in xrange(random.randint(10, 100)):
globals()["FOO%i" % i] = "hallo"

--- module.py ---

there is not a chance of such a tool being more than a heuristic. Such
things only work in a static typed world where you know the number of
declarations.

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


RE: Anomalous behaviour when compiling regular expressions?

2006-03-13 Thread Harvey.Thomas
Fredrik wrote:

> your definition of "equivalent" is a bit unusual:
> 
> >>> re.match("(a|b*c*)+", "abc").groups()
> ('',)
> >>> re.match("(a|b)*", "abc").groups()
> ('b',)
> >>> re.match("(a|b|c)*", "abc").groups()
> ('c',)
> 
> that you don't get an error for
>
> >>> r = re.compile('(a|b*c*)+')
> >>> r.match('def').group()
> 
> might be a compiler bug.  running it on 2.3 gives you another error,
> though:
>
> >>> re.match("(a|b*c*)+", "abc").groups()
> Traceback (most recent call last):
>  File "", line 1, in ?
>  File "C:\python23\lib\sre.py", line 132, in match
>return _compile(pattern, flags).match(string)
> RuntimeError: maximum recursion limit exceeded
>
> (a repeated group with a min-length of zero can match anything an
infinite number of times, which is, in general, not > > what you want)

I agree to a certain extent, but by analogy


]>


is a valid SGML/XML document and their is a lot of (superficial?)
similarity between DTD content models and REs. The element declaration
would (should?) normally be written as









The information contained in this email message may be confidential. If you are 
not the intended recipient, any use, interference with, disclosure or copying 
of this material is unauthorised and prohibited. Although this message and any 
attachments are believed to be free of viruses, no responsibility is accepted 
by Informa for any loss or damage arising in any way from receipt or use 
thereof.  Messages to and from the company are monitored for operational 
reasons and in accordance with lawful business practices. 
If you have received this message in error, please notify us by return and 
delete the message and any attachments.  Further enquiries/returns can be sent 
to [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE: great headache....

2006-03-13 Thread Joel Hedlund
> Sorry to offend, I was just extrapoloating from personal experience.

No worries, man. No offense taken :-)

> but I could not get going with Eclipse
> ...
> Even installing it the first time seemed to be a mystery.

Yeah I felt the same too when I first installed it. I had in fact given up 
using Eclipse, but then I found that starter guide I linked to in my last post. 
It really is excellent. It's thorough and to the point, and I really recommend 
it to people who are interested in PyDev.

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


Re: automatic from module import * expansion

2006-03-13 Thread astyonax
Sorry but I doesn't understand your need. If you need a ''dinamic''
import, you can use __import__(module)

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


Re: capturing stdout from lynx..

2006-03-13 Thread [EMAIL PROTECTED]
perfect!

that worked great!

thank you!

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


Re: Which GUI toolkit is THE best?

2006-03-13 Thread Thomas Guettler
Am Fri, 10 Mar 2006 16:10:09 +0100 schrieb Sybren Stuvel:

> Thomas Guettler enlightened us with:
>> The licence for QT is GPL, this means you cannot use it in
>> commercial application. That is why I never looked at it.
> 
> Ehmm... from their website:

>From http://www.trolltech.com/products/qt/licensing.html

> The Qt Commercial License is the correct license to use for the
> construction of proprietary, commercial software. The license allows
> you to:
> - Build commercial software and software whose source code you
>   wish to keep private.
> - Freely choose licensing for the software you are writing
>   (Proprietary, Open Source or both).
> - Be able to gain access to Qt Solutions, Trolltech support and
>   commercial-only Qt components such as commercial database
>   drivers and the Visual Studio Integration on Windows. 

Have you read all the text?

"""
Two qualities of the Qt Commercial License should be emphasized:

You need it before you start development of proprietary software.

You must purchase a Qt Commercial License from Trolltech or from any of
its authorized resellers before you start developing. The Commercial
license does not allow the incorporation of code developed with the Open
Source Edition of Qt into a proprietary product.
"""

There is a GPL version for Linux. But the GPL does not allow linking
with closed source software.


-- 
Thomas Güttler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: [EMAIL PROTECTED]

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


Re: How to find cause for Python/Pythonwin crash only on Dual Core Machines ?

2006-03-13 Thread darrenk
I believe the problem exists with any processor that supports
hardware-based data execution prevention (DEP).
Goto
Control Panel - System - Advanced tab - Performance Settings - DEP tab.
Turn on DEP for all ... except those I select:
Add the Pythonwin.exe to the list.

Now it should work.

-D

Larry Bates wrote:
> robert wrote:
> > There is a strange freeze/crash only on dual core machines:
> >
>
> I've run on Dual 1.7, 2.4Ghz Xeon machines and a hyperthreaded
> 3.0Ghz machine for several years with no problems.  I don't think
> there is an inherent problem.
> 
> -Larry Bates

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


doctest-alike for a unix shell?

2006-03-13 Thread Paddy
Hi,
Anyone know of something that can turn an interactive bash or tcsh
session into a test the 
way doctest does?

- Cheers, Paddy.

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


Re: Which GUI toolkit is THE best?

2006-03-13 Thread Sybren Stuvel
Thomas Guettler enlightened us with:
> There is a GPL version for Linux. But the GPL does not allow linking
> with closed source software.

The availability of a GPL license does not negate the availability of
a commercial license. You can write commercial, closed source software
on Linux using Qt legally.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations?

2006-03-13 Thread anamax
> robert wrote:
> Meanwhile I think this is a bug of cPickle.dump: It should use .keys()
> instead of free iteration internally, when pickling elementary dicts.
> I'd file a bug if no objection.

What should happen if there's a delete between the time the .keys()
runs and the time that the deleted element is processed by
cPickle.dump?

-andy

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


PEP 8 example of 'Function and method arguments'

2006-03-13 Thread Martin P. Hellwig
While I was reading PEP 8 I came across this part:

"""
Function and method arguments
Always use 'self' for the first argument to instance methods.
Always use 'cls' for the first argument to class methods.
"""

Now I'm rather new to programming and unfamiliar to some basic concepts 
of OOP. However I wrote most of my classes in the new style way and by 
this I have always used 'self' for the first argument of an Instance 
method, but now I'm unsure what actually the difference is between an 
instance and a class method is and when to use it in which case.

Could somebody please enlighten me (a rtfm/wrong newsgroup is just as 
welcome of course), preferably in a short code example?

TIA

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


Re: how exactly do binary files work in python?

2006-03-13 Thread Scott David Daniels
Steven D'Aprano wrote:
[Generally fine stuff, I am elaborating rather than dis-agreeing.]
> On Sun, 12 Mar 2006 22:01:46 -0500, John Salerno wrote:
> 
>> Erik Max Francis wrote:
>>
>>> You can use the struct module for converting fundamental types to a 
>>> portable string representation for writing to binary files.
>> But if it's a string, why not just use a text file? What does a binary 
>> file do that a text file doesn't, aside from not converting the end of 
>> line characters?
> 
> Nothing. It is all bytes under the hood.
Modeling a file as "a continuous undifferentiated string of bytes under
the hood" is a Unix-ism.  There were (and are) other models.

> When writing lines to a file, Python does not automatically append the
> line marker, so you need to do so yourself. 
This is, indeed the behavior with "write," but not with "print"
A "print" statement ending w/o a comma will tack an end-of-line onto its
output.

 > But some other languages do -- I believe C++ is one of those languages.
 > So C++ needs to know whether you are writing in text mode so it can
 > append that end-of-line maker, or binary mode so it doesn't.
Actually C++ (and C) convert any ('\12' == '\n' == LF) character to
the local file system's "line terminator" character on output to a
text-mode file.

 > Since Python doesn't modify the line you write to the file, it doesn't
 > care whether you are writing in text or binary mode, it is all the same.
Well, actually CPython uses C I/O, so it does convert the '\n' chars
just as C does.

> Operating systems such as Unix and Linux don't distinguish between binary
> and text mode, the results are the same. I'm told that Windows does
> distinguish between the two, although I couldn't tell you how they
> differ.

The way Windows differs from Unix:
 If the actual file data is built as:
 f = open('dead_parrot', 'wb')
 f.write('dead\r\nparrot')
 f.close()
 g = open('ex_parrot', 'w')
 g.write('Dead\nParrot')
 g.close()
 ft = open('dead_parrot', 'r')
 ft.read(6) returns 'dead\np'
 gt = open('ex_parrot', 'r')
 gt.read(6) returns 'Dead\nD'

 fb = open('dead_parrot', 'rb')
 fb.read(6) returns 'dead\r\n'
 gb = open('ex_parrot', 'rb')
 gb.read(6) returns 'Dead\r\n'

In case you didn't follow the above too precisely, both files
(dead_parrot and ex_parrot) have exactly the same byes as contents.

This, by the way, is one of the few places Windows did it "by the
standard" and Unix "made up their own standard."  The Unix decision
was, essentially: "there are too many ways to get in trouble with
both CR and LF determining line ending: what do you do for LF-CR pairs,
What does a LF by itself mean w/o a CR,   Let's just treat LF
as a single-character line separator."  Note how funny this for how
you type: you type for a line, but  sends
a CR ('\r' == '\15' == ASCII 13), which the I/O systems somewhere 
magically transforms into a LF ('\n' == '\12' == ASCII 10).

The C standard (which evolved with Unix) does these translation
"for you" (or "to you" depending on your mood) because it was meant
to be compatible with _many_ file systems, including those which did
not explicitly represent ends-of-lines (text files are such systems
are sequences of lines, and there is a maximum length to each line).
By the way, before you think such systems are foolish, think about
how nice it might sometimes be to get to line 20972 of a file without
reading through the entire front of the file.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Very, Very Green Python User

2006-03-13 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
> ... Is the Python debugger fairly stable?
Yes, but it is not massively featured.  The "Pythonic" way is to
rarely use a debugger (test first and straightforward code should
lead to "shallow" bugs).  Often for most of us judiciously placed
print statements suffice.

 > The one you get with Perl stinks on ice. More than
> anything else, I would like to have a powerful OO environment where I
> do not have to worry about the debugger sucking 
Do watch your language on this newsgroup.  Lots of people read this
group and there is no good reason to offend them.  In turn, you will be
cut some slack.

> A couple blemishes I'm concerned about, though:
> 
> Python closures are apparently very poor, but from what I can surmise
> of the PyGTK2 page, instances of objects are dynamic enough to add new
> methods, so you get your callbacks, at least.

What do you mean by "very poor"?  Python prefers you to use functions
defined with a suitable name in places other languages provide stronger
lambda expressions, if that's what you mean.  Also, there is no easy way
to affect the variables of an encasing function, if that is what you
mean.

> Double-underscore methods are rewritten with the class name? That's an
> ugly hack, but remember I'm coming from Perl. If the language doesn't
> pull many other hijinks, that's OK.

Double-underscore is a strong language convention and warning.  Names
both beginning and ending with double-underscore may be "magic" in
that interacting with them affects more behavior than the same code
using a different name.  Instance variables with double-underscore as
a leading convention get "mangled" just so that when you are designing
"mixin" classes you can easily choose names that should not collide
with the instance variable names of classes using your "mixin" classes.

> I have plenty of docs and stuff, now I'm just looking for wisdom. As a
> seasoned Python user, what do you have to impart?

I think if you spend the effort to learn to use Python you'll have a
wonderful experience.  Welcome to the newsgroup.


--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 8 example of 'Function and method arguments'

2006-03-13 Thread Steven Bethard
Martin P. Hellwig wrote:
> While I was reading PEP 8 I came across this part:
> 
> """
> Function and method arguments
>Always use 'self' for the first argument to instance methods.
>Always use 'cls' for the first argument to class methods.
> """
> 
> Now I'm rather new to programming and unfamiliar to some basic concepts 
> of OOP. However I wrote most of my classes in the new style way and by 
> this I have always used 'self' for the first argument of an Instance 
> method, but now I'm unsure what actually the difference is between an 
> instance and a class method is and when to use it in which case.
> 
> Could somebody please enlighten me (a rtfm/wrong newsgroup is just as 
> welcome of course), preferably in a short code example?

You're probably doing fine.

 class C(object):

 # instance method
 def foo(self):
 ...

 # class method
 @classmethod
 def bar(cls):
 ...

It's probably pretty unlikely that you've declared any class methods, 
but if you have, you should be able to identify them by the call to 
``classmethod``.  If you don't see any of those, you're fine.

A class method is just a method that can be called like:

 Class.method()

instead of having to be called like:

 instance.method()

For 99% of the methods you write, I'd expect them to be instance methods.

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


Re: Please, I Have A Question before I get started

2006-03-13 Thread Scott David Daniels
Skipper wrote:
> ... I am not asking for anyone to do this for me I simply want to 
> know if I can do what I need to do with Python 
> Can python do this?  I realize I am responsible for the menu sets,
> pictures  attaching sounds etc  

As you have been told by many other respondents above, the task is
not as simple as it seems it should be.  If you decide to go ahead
and attempt it in Python (after you have learned some easier stuff),
you will definitely get lots of assistance here.  You just need to
decide which mountains you want to climb, and which ones you pass up.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Very, Very Green Python User

2006-03-13 Thread Fredrik Lundh
Scott David Daniels wrote:

> > ... Is the Python debugger fairly stable?
> Yes, but it is not massively featured.  The "Pythonic" way is to
> rarely use a debugger (test first and straightforward code should
> lead to "shallow" bugs).  Often for most of us judiciously placed
> print statements suffice.

combined with a modular design, so you can make sure that individual
functions, classes, and modules work as expected before you use them
to build larger stuff...





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


Re: Environmental Variables

2006-03-13 Thread John Salerno
Sathyaish wrote:
> In which physical file are the python environmental variables located?
> I know I can access them using the:
> 
> 
> os.environ.get('PYTHONSTARTUP')
> 
> or
> 
> os.environ.get('PYTHONPATH')
> 
> 
> to get their values. But out of the program, if I need to look at them
> and alter their values, where do I find them? Are they the OS
> environmental variables as I suspect? If they are, then I'll find them
> with the other OS environ variables in My
> Computer->System->Properties->Advanced->Environmental Variables.
> 
> But I checked that place and did not find any default values for them.
> 

As far as PYTHONPATH goes, I added that one manually to my list of 
environment variables. As far as I know, it's not there by default.

Now, can someone tell me if adding it manually interferes with anything 
else Python itself is doing?
-- 
http://mail.python.org/mailman/listinfo/python-list


Announcing edupython list

2006-03-13 Thread Anna Ravenscroft
In order to facilitate small groups
working on specific Python-in-Education projects, we have launched an
edupython list on google groups(http://groups.google.com/group/edupython
 or [EMAIL PROTECTED]).
We envision participation by people trying to coordinate work on the
nuts and bolts implementation of a project, with frequent progress
reports and requests for suggestions and comments coming back to
edu-sig. The list developed as a result of a quite well-attended and
enthusiastic BOF meeting at PyCon.
This edupython list is not intended to replace edu-sig,
which remains very strong for theoretical and philosophical
discussions, and for getting input and suggestions from a wider group,
but is also necessarily higher bandwidth. We invite anyone working on
Python-related education projects to join the list. Cordially,Anna Martelli Ravenscroft
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: IOS-style command line interface module?

2006-03-13 Thread hugonz
Hell, this sounds interesting. Do you mean like matching commands when
they are not yet  complete, like

sh tech

instead of:

show tech-support
?

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


Re: Python Love :)

2006-03-13 Thread rtilley
BWill wrote:
> and ixnay on the ubyray or else I'll tell you where to stick your 
> endblock delimiter :P

OK, I can't help it... which is more readable:

a_string.reverse(ruby)
a_string[::-1]  (python)

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


Re: Is this possible in Python?

2006-03-13 Thread alainpoint

Kay Schluehr wrote:
> Storing arguments away before they are evaluated doesn't work in
> Python. You have to hack the compiler in order to access the parsetree.
> You might take a look at the compiler package of the standard library
> that enables access to ASTs. Thus you could define lazy evaluation and
> just-in-time compilation of some particular ASTs. I do not recommend
> doing this for real purposes, but it is a good excercise and sooner or
> later you become an expert yourself :)
>
> Kay

I made some investigation and reached a (partial) solution to my
problem. It is inspired from a cookbook recipe but it only works for
generator expressions.:
import tokenize
import token
def magic_function(s):
cursor = None   # to be set to the cursor of the connection
return_type = object# can be set to dict or list
_iterating = False # used in next()
readline = open(s.gi_frame.f_code.co_filename).readline
first_line = s.gi_frame.f_code.co_firstlineno
flag = False
source = ''# the source code
for t in
tokenize.generate_tokens(open(s.gi_frame.f_code.co_filename).readline):
# check all tokens until the last parenthesis is closed
t_type,t_string,(r_start,c_start),(r_end,c_end),line = t
t_name = token.tok_name[t_type]
if r_start == first_line:
if t_name == 'NAME' and t_string=="magic_function":
flag = True
res = t_string
start = 0 # number of parenthesis
continue
if flag:
source += ' '+t_string
if t_name == 'OP':
if t_string=='(':
start += 1
elif t_string == ')':
start -= 1
if start == 0:
break
return source[2:-2]

assert magic_function(i+2 for i in [1,2])=="i+2 for i in [1,2]"
or
print magic_function(i+2 for i in [1,2])

A general solution is possible and i am sure there are people around
that will provide such a solution

Alain

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


Re: Is this possible in Python?

2006-03-13 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> Hi
> 
> I wonder if Python is capable of the following: define a function which
> returns its argument.
> I mean:
> def magic_function(arg):
> .. some magic code ...
> 
> that behaves the following way:
> 
> assert magic_function(3+4)=="3+4"
> assert magic_function([i for i in range(10)])=="i for i in range(10)]"
> 
> It is not trivial at all and might require some bytecode hacking that i
> am unable to do myself BUT you are the experts ;-)
> 
> Alain

You probably want to learn Lisp, where what you want to do is trivial:

(defmacro magic (arg) arg)

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


Re: Python Love :)

2006-03-13 Thread Paul Rubin
rtilley <[EMAIL PROTECTED]> writes:
> a_string.reverse  (ruby)
> a_string[::-1](python)

reversed(a_string) (python)
-- 
http://mail.python.org/mailman/listinfo/python-list


trying to find repeated substrings with regular expression

2006-03-13 Thread Robert Dodier
Hello all,

I'm trying to find substrings that look like 'FOO blah blah blah'
in a string. For example give 'blah FOO blah1a blah1b FOO blah2
FOO blah3a blah3b blah3b' I want to get three substrings,
'FOO blah1a blah1b', 'FOO blah2', and 'FOO blah3a blah3b blah3b'.

I've tried numerous variations on '.*(FOO((?!FOO).)*)+.*'
and everything I've tried either matches too much or too little.

I've decided it's easier for me just to search for FOO, and then
break up the string based on the locations of FOO.

But I'd like to better understand regular expressions.
Can someone suggest a regular expression which will return
groups corresponding to the FOO substrings above?

Thanks for any insights, I appreciate it a lot.

Robert Dodier

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


Re: Python Love :)

2006-03-13 Thread gregarican
Paul Rubin wrote:

> reversed(a_string) (python)

Which version of Python offers this function? It doesn't seem to be
available in the 2.3 version I have installed...

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


Re: Python Love :)

2006-03-13 Thread Paul Rubin
"gregarican" <[EMAIL PROTECTED]> writes:
> > reversed(a_string) (python)
> 
> Which version of Python offers this function? It doesn't seem to be
> available in the 2.3 version I have installed...

I think it's new in 2.4.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which GUI toolkit is THE best?

2006-03-13 Thread Paul Boddie
Thomas Guettler wrote:
>
> Have you read all the text?
>
> """
> Two qualities of the Qt Commercial License should be emphasized:
>
> You need it before you start development of proprietary software.
>
> You must purchase a Qt Commercial License from Trolltech or from any of
> its authorized resellers before you start developing. The Commercial
> license does not allow the incorporation of code developed with the Open
> Source Edition of Qt into a proprietary product.
> """
>
> There is a GPL version for Linux. But the GPL does not allow linking
> with closed source software.

My understanding of how it all works is this: Trolltech offers you Qt
under the GPL; you can choose to accept the GPL; you then uphold the
GPL in the distribution of your work. Alternatively, you request that
Trolltech license the software to you under the "Qt Commercial
License"; they decide whether or not they want to license it to you; if
they decide "yes", you get to distribute your proprietary software with
the proprietary edition of the product.

What people don't usually understand (or rather complain about loudly)
is that Trolltech can refuse to license Qt to you under the commercial
licence, as is their right as the owner of the copyrighted work. As far
as I know, you can still obtain Qt under the GPL from them in such a
situation, although this is fairly academic since there are lots of
people offering Qt under the GPL in a variety of GNU/Linux
distributions, for example. Usually, the people making a fuss about all
this have already licensed Qt under the GPL, however, and believe that
they have a right to "switch over" to another licence, but neither the
GPL nor any basic aspect of copyright practice supports such a notion.

So, yes, you either say up front that you're developing proprietary
software and buy into that special deal with the copyright holder, or
you don't. Of course, you could try and distribute non-commercial,
evaluation, trial, educational-use-only, non-redistributable or
NDA-affected versions of your favourite proprietary software products
and see which court of law that takes you to - in these debates nobody
seems to ask themselves whether Bill Gates and/or Steve Jobs would let
you switch around, slip out of that NDA, give you special upgrades,
strike through clauses in that EULA, and so on down the list of things
that nobody thought about when putting together that now-shaky business
model.

Paul

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


Re: Environmental Variables

2006-03-13 Thread Diez B. Roggisch
Dennis Lee Bieber wrote:
> The Amiga did have a means for such... It differentiated between
> local and global environment variables. Locals were kept in a process
> memory structure and behaved as they do on most other OSs... Globals,
> however, were short files maintained in ENV: (a logical name to a disk
> directory); so any process changing the file contents (whether
> explicitly using open/write/close,  or implicitly with SETENV name
> value) would be visible in all other processes. Locals were defined
> using just SET name value.

Well, the amiga lacked a MMU - so you could do _anything_ if you really
wanted :)

And I consider such a "feature" risky - think of buffer-overflows which
could be provoked in running processes with other user-rights.

But nonetheless I loved the AMIGA and its OS - actually I only moved to a PC
in 96 when I discovered that there was a OS (Linux) that appealed to me in
similar ways as the AMIGA-os did.

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


Re: Is this possible in Python?

2006-03-13 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi
>
> I wonder if Python is capable of the following: define a function which
> returns its argument.
> I mean:
> def magic_function(arg):
>.. some magic code ...
>
> that behaves the following way:
>
> assert magic_function(3+4)=="3+4"
> assert magic_function([i for i in range(10)])=="i for i in range(10)]"

The arguments to Python functions are Python objects.  In order to return 
the argument as a string, you must pass it as a string.

>>> def magic(s): return s, eval(s)

>>> magic('3+4')
('3+4', 7)
>>> magic('[i**2 for i in [1,2,3]]')
('[i**2 for i in [1,2,3]]', [1, 4, 9])

Terry Jan Reedy



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


Re: Is this possible in Python?

2006-03-13 Thread Caleb Hattingh
Hi

I don't think this is what you want (a string representation of the 
argument passed to a function as that argument is at runtime is way 
beyond my abilities), but this can retrieve the literal text in the 
function call as it appears in the .py file, assuming you have the .py 
file available and not just the .pyc:

### Call this file "pyfunargtest.py"
def fun(i):
 pass

fun(8+7)

def test():
 fname = 'pyfunargtest.py'
 testfunname = 'f'
 flines = open(fname,'r').readlines()
 for i in flines:
 if i.find(testfunname)>-1 and i.find('def '+testfunname)==-1:
 s = i
 break
 leftbracketposition = s.find('(')
 rightbracketposition = s.find(')')
 arg = s[leftbracketposition+1:rightbracketposition]
 return arg

print test()
### Output:
# 8+7



[EMAIL PROTECTED] wrote:
> Hi
> 
> I wonder if Python is capable of the following: define a function which
> returns its argument.
> I mean:
> def magic_function(arg):
> .. some magic code ...
> 
> that behaves the following way:
> 
> assert magic_function(3+4)=="3+4"
> assert magic_function([i for i in range(10)])=="i for i in range(10)]"
> 
> It is not trivial at all and might require some bytecode hacking that i
> am unable to do myself BUT you are the experts ;-)
> 
> Alain
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which GUI toolkit is THE best?

2006-03-13 Thread Paul Rubin
"Paul Boddie" <[EMAIL PROTECTED]> writes:
> What people don't usually understand (or rather complain about loudly)
> is that Trolltech can refuse to license Qt to you under the commercial
> licence, as is their right as the owner of the copyrighted work.

What is the deal here?  Why would they refuse, to someone willing to
pay the commercial license fee?  They are a business, and as such,
they presumably like gettng money.  And someone wanting to develop a
proprietary app with Qt that users have to pay for, shouldn't mind
paying Trolltech for the commercial Qt license.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suse linux 10 and wx.listctrl display issues

2006-03-13 Thread ianaré
Well that definitly works, thanks. Is there any way to keep the themes
though?

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


Re: Please, I Have A Question before I get started

2006-03-13 Thread JW
Skipper wrote:
> I can not believe that there isn't a GUI programing tool that will
> allow me to build GUI apps - just like I use Dreamweaver to build a
> web page ... a WYSIWYG builder that does a few simplet things and
> calls other programs ...
>
> Oh well  no silver bullet!

If you are interested in programming, the best way is to find a
motivating goal to learn.  It sounds like you have a very motivating
goal.  However, it will probably take quite a long time for you to get
to a point where you can make a useful tool for your son.  While your
problem description is straightforward, the implementation is not.

One route you might consider is contacting your local engineering
college for help.  My alumnus recently solicited funds for a "Life
Interaction Device" for Abigail, a 6 year old girl with Cerebral Palsy:

http://www.ee.utulsa.edu/Abigail/index.html

It sounds as if Abagail's needs are far greater than your son's, but
your project would make an interesting design project for CS students
at an undergraduate level.

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


Re: IOS-style command line interface module?

2006-03-13 Thread David Wilson
Doh, I am indeed referring to the standard "cmd" module - thanks!

To [EMAIL PROTECTED], the above module does what you describe.

Thanks again,


David.

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


Re: Please, I Have A Question before I get started

2006-03-13 Thread Kent Johnson
Ravi Teja wrote:
> I do not think that technology has gone backwards. Hyper card
> alternatives still exist.
> http://www.metacard.com/

At $995 per seat it's not likely to be used for a home project.

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


No more then 1 Instance of Application..

2006-03-13 Thread Math
Hello,

Pardon my English...
Does anybody know what I have to do to run only 1 instance of my Python 
Application?
How do I check if I'm running more instances of a Application?
Thank you all

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


Re: Python Love :)

2006-03-13 Thread Peter Otten
Paul Rubin wrote:

> "gregarican" <[EMAIL PROTECTED]> writes:
>> > reversed(a_string) (python)
>> 
>> Which version of Python offers this function? It doesn't seem to be
>> available in the 2.3 version I have installed...
> 
> I think it's new in 2.4.

Needs a little help, though:

>>> print reversed("abba")


>>> class Str(str):
... def __reversed__(self):
... return self[::-1]
...
>>> reversed(Str("abba"))
'abba'

Now if only I had picked a better example :-)

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


Re: Which GUI toolkit is THE best?

2006-03-13 Thread Chris Mellon
On 13 Mar 2006 10:19:05 -0800, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> "Paul Boddie" <[EMAIL PROTECTED]> writes:
> > What people don't usually understand (or rather complain about loudly)
> > is that Trolltech can refuse to license Qt to you under the commercial
> > licence, as is their right as the owner of the copyrighted work.
>
> What is the deal here?  Why would they refuse, to someone willing to
> pay the commercial license fee?  They are a business, and as such,
> they presumably like gettng money.  And someone wanting to develop a
> proprietary app with Qt that users have to pay for, shouldn't mind
> paying Trolltech for the commercial Qt license.
> --

Qt (commercial) licensing is a subscription - you pay per developer
per year - so an obvious thing for people to attempt (and I have no
idea if this has been tried, but I wouldn't doubt it) is for a company
to download the GPL version, develop the application internally, and
then purchase 1 license when they're ready to ship. This would
seriously bite into TTs income and they aren't interested in allowing
you do this, so while you're free to download the GPL version and
develop all you want, TT won't sell you a commercial license "after
the fact" like this.

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


Re: trying to find repeated substrings with regular expression

2006-03-13 Thread Kent Johnson
Robert Dodier wrote:
> Hello all,
> 
> I'm trying to find substrings that look like 'FOO blah blah blah'
> in a string. For example give 'blah FOO blah1a blah1b FOO blah2
> FOO blah3a blah3b blah3b' I want to get three substrings,
> 'FOO blah1a blah1b', 'FOO blah2', and 'FOO blah3a blah3b blah3b'.
> 
> I've tried numerous variations on '.*(FOO((?!FOO).)*)+.*'
> and everything I've tried either matches too much or too little.

FOO(.*?)(?=FOO|$)


> I've decided it's easier for me just to search for FOO, and then
> break up the string based on the locations of FOO.

Use re.split() for this.

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


  1   2   >