Re: Merging two dictionaries

2010-08-02 Thread Gary Herron

On 08/01/2010 11:11 PM, Douglas Garstang wrote:

On Sun, Aug 1, 2010 at 10:58 PM, Gary Herron  wrote:
   

On 08/01/2010 10:09 PM, Douglas Garstang wrote:
 

Anyone,

I have the two dictionaries below. How can I merge them, such that:

1. The cluster dictionary contains the additional elements from the
default dictionary.
2. Nothing is removed from the cluster dictionary.

The idea here is that the two dictionaries are read from different
files where, if the value isn't found in the cluster dictionary, it's
pulled from the default one, and I can have a new dictionary
reflecting this. The update() method on dictionaries doesn't seem to
work. The resulting dictionary always seems to be the one passed as a
parameter.

default = {
 'cluster': {
 'platform': {
 'elements': {
 'data_sources': {
 'elements': {
 'db_min_pool_size': 10
 },
 },
 },
 },
 }
}

cluster = {
 'cluster': {
 'name': 'Customer 1',
 'description': 'Production',
 'environment': 'production',
 'platform': {
 'elements': {
 'data_source': {
 'elements': {
 'username': 'username',
 'password': 'password'
 },
 },
 },
 },
 }
}

The resulting dictionary would therefore look like this:

new_dict = {
 'cluster': {
 'name': 'Customer 1',
 'description': 'Production',
 'environment': 'production',
 'platform': {
 'elements': {
 'data_source': {
 'elements': {
 'username': 'username',
 'password': 'password',
 'db_min_pool_size': 10 # This was added from
the default.
 },
 },
 },
 },
 }
}


Thanks,
Doug.


   

Your dictionaries are annoyingly complicated -- making it hard to see what's
going on.  Here I've replaced all the distractions of your dictionary
nesting with a simple (string) value.  Now when you try to update

 

default = {'cluster': 'some_value'}
cluster = {'cluster': 'another_value'}
cluster.update(default)
print cluster
   

{'cluster': 'some_value'}

If you read up on what update is supposed to do, this is correct -- keys in
default are inserted into cluster -- replacing values if they already exist.

I believe update is not what you want for two reasons:

  1.  It's doubtful that you want a default to replace an existing value, and
that's what update does.

  2.  I get the distinct impression that you are expecting the update to be
applied recursively down through the hierarchy.  Such is not the case.




And I just have to ask: Of what use whatsoever is a dictionary (hierarchy)
that contains *one* single value which needs a sequence of 6 keys to access?

print
default['cluster']['platform']['elements']['data_sources']['elements']['db_min_pool_size']
 

10
   

Seems absurd unless there is lots more going on here.
 

Thanks. Any particular reason you replied off-list?
   


Huh?  Oh hell.  My mistake.  (This is now back on the list -- where it 
should have been to start with.)




Anyway, I'm trying to model a cluster of servers in a yaml file that
gets edited by humans and a tree structure makes it easier to
understand the context of each invidual key. If it was arrange in a
flat fashion, each key would have to be longer in order to make it
unique and provide some context as to what the user was actually
editing.

I actually didn't paste the whole dictionary. I cut it down to make it
easier to explain. When you see the full version, the multiple levels
make more sense. Tried various approaches so far, and none work. I
can't traverse the tree recursively because each time you recurse, you
lose the absolute position of the key your currently at, and then
there's no way to update the values.

Doug.
   


Ok.  Thanks for simplifying things before sending the question out to 
the list.  You probably wouldn't have gotten a response otherwise.


I'm not sure I believe the reasoning for the inability to recurse.  It 
seems rather simple to recurse through the structures in tandem, adding 
any key:value found in the default to the other if not already present.


Gary Herron




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


Re: Merging two dictionaries

2010-08-02 Thread Douglas Garstang
On Sun, Aug 1, 2010 at 11:57 PM, Gary Herron  wrote:
> On 08/01/2010 11:11 PM, Douglas Garstang wrote:
>>
>> On Sun, Aug 1, 2010 at 10:58 PM, Gary Herron
>>  wrote:
>>
>>>
>>> On 08/01/2010 10:09 PM, Douglas Garstang wrote:
>>>

 Anyone,

 I have the two dictionaries below. How can I merge them, such that:

 1. The cluster dictionary contains the additional elements from the
 default dictionary.
 2. Nothing is removed from the cluster dictionary.

 The idea here is that the two dictionaries are read from different
 files where, if the value isn't found in the cluster dictionary, it's
 pulled from the default one, and I can have a new dictionary
 reflecting this. The update() method on dictionaries doesn't seem to
 work. The resulting dictionary always seems to be the one passed as a
 parameter.

 default = {
     'cluster': {
         'platform': {
             'elements': {
                 'data_sources': {
                     'elements': {
                         'db_min_pool_size': 10
                     },
                 },
             },
         },
     }
 }

 cluster = {
     'cluster': {
         'name': 'Customer 1',
         'description': 'Production',
         'environment': 'production',
         'platform': {
             'elements': {
                 'data_source': {
                     'elements': {
                         'username': 'username',
                         'password': 'password'
                     },
                 },
             },
         },
     }
 }

 The resulting dictionary would therefore look like this:

 new_dict = {
     'cluster': {
         'name': 'Customer 1',
         'description': 'Production',
         'environment': 'production',
         'platform': {
             'elements': {
                 'data_source': {
                     'elements': {
                         'username': 'username',
                         'password': 'password',
                         'db_min_pool_size': 10 # This was added from
 the default.
                     },
                 },
             },
         },
     }
 }


 Thanks,
 Doug.



>>>
>>> Your dictionaries are annoyingly complicated -- making it hard to see
>>> what's
>>> going on.  Here I've replaced all the distractions of your dictionary
>>> nesting with a simple (string) value.  Now when you try to update
>>>
>>>
>>
>> default = {'cluster': 'some_value'}
>> cluster = {'cluster': 'another_value'}
>> cluster.update(default)
>> print cluster
>>
>>>
>>> {'cluster': 'some_value'}
>>>
>>> If you read up on what update is supposed to do, this is correct -- keys
>>> in
>>> default are inserted into cluster -- replacing values if they already
>>> exist.
>>>
>>> I believe update is not what you want for two reasons:
>>>
>>>  1.  It's doubtful that you want a default to replace an existing value,
>>> and
>>> that's what update does.
>>>
>>>  2.  I get the distinct impression that you are expecting the update to
>>> be
>>> applied recursively down through the hierarchy.  Such is not the case.
>>>
>>>
>>>
>>>
>>> And I just have to ask: Of what use whatsoever is a dictionary
>>> (hierarchy)
>>> that contains *one* single value which needs a sequence of 6 keys to
>>> access?
>>>
>>> print
>>>
>>> default['cluster']['platform']['elements']['data_sources']['elements']['db_min_pool_size']
>>>
>>
>> 10
>>
>>>
>>> Seems absurd unless there is lots more going on here.
>>>
>>
>> Thanks. Any particular reason you replied off-list?
>>
>
> Huh?  Oh hell.  My mistake.  (This is now back on the list -- where it
> should have been to start with.)
>
>
>> Anyway, I'm trying to model a cluster of servers in a yaml file that
>> gets edited by humans and a tree structure makes it easier to
>> understand the context of each invidual key. If it was arrange in a
>> flat fashion, each key would have to be longer in order to make it
>> unique and provide some context as to what the user was actually
>> editing.
>>
>> I actually didn't paste the whole dictionary. I cut it down to make it
>> easier to explain. When you see the full version, the multiple levels
>> make more sense. Tried various approaches so far, and none work. I
>> can't traverse the tree recursively because each time you recurse, you
>> lose the absolute position of the key your currently at, and then
>> there's no way to update the values.
>>
>> Doug.
>>
>
> Ok.  Thanks for simplifying things before sending the question out to the
> list.  You probably wouldn't have gotten a response otherwise.
>
> I'm not sure I believe the reasoning for the inability to recurse.  It seems
> rather simple to recurse through the structures in ta

Re: Merging two dictionaries

2010-08-02 Thread Chris Rebert
On Mon, Aug 2, 2010 at 12:06 AM, Douglas Garstang
 wrote:
> Actually, I had issues with trying recurse through the structures in
> tandem too. This didn't work:
>
> for a,b,c,d in ( cluster.iteritems(), default.iteritems() ):
>    ... do something ...
>
> It returns an unpack error.

Well, yeah. That for-loop has several problems:
- You're iterating over the items of a 2-tuple. It's just like:
for a,b,c,d in [1, 2]:
It's not treated any differently just because the items happen to be
iterators themselves. The iterators aren't automagically iterated
through in parallel just by putting them in a tuple. That would
require a zip().
- iteritems() returns a sequence of 2-tuples. Even when zipped, these
tuples don't get magically unpacked and repacked into 4-tuples:
for a, b, c, d in zip([(1,2), (3,4)], [(5,6), (7,8)]):
# still fails; can't unpack 2 separate tuples (i.e. (1,2) (5,6) )
directly into 4 variables; the nesting is wrong
- iteritems() returns the keys in an arbitrary order; the two
iteritems() calls won't be in any way "synchronized" so the keys match
up

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Merging two dictionaries

2010-08-02 Thread Paul Rubin
Douglas Garstang  writes:
> default = {...
> 'data_sources': { ...
> cluster = {...
> 'data_source': { ...

Did you want both of those to say the same thing instead of one
of them being 'data_source' and the other 'data_sources' ?

If yes, then the following works for me:

def merge(cluster, default):
# destructively merge default into cluster
for k,v in cluster.iteritems():
if k in default and type(v)==dict:
assert type(default(k))==dict
merge(v,default[k])
for k,v in default.iteritems():
if k not in cluster:
cluster[k] = v
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch windows shutdown/reboot message

2010-08-02 Thread Tim Golden

On 02/08/2010 02:17, rechardchen wrote:

I'm writing a python script which runs as a windowsxp service.
The problem is how to catch the windows shutdown/reboot message and do
some cleaning job when system is going down?

The atexit module and signal module on windows dont seems to work. I
guess the python win32api may be of help, but I am not familiar with it...
Thank you


Have a look at the SENS stuff:

  http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html

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


Re: Problem with Elementtree and XMLSchem instance type

2010-08-02 Thread NewBlue
> "Lawrence" == Lawrence D'Oliveiro  
> writes:

Lawrence> In message
Lawrence> ,
Lawrence> Roland
Lawrence> Hedberg wrote:

> And there is the problem, I've lost the coupling between the prefix
>> 'fed' and the namespace
>> "http://docs.oasis-open.org/wsfed/federation/200706";.

Lawrence> Why is this a problem?
我在设立
-- 
自从你离开了以后,我一直等待着你回来
世人笑我懵懂,我笑世人不懂
My homepage:[http://211.92.88.40/~newblue]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Merging two dictionaries

2010-08-02 Thread Peter Otten
Douglas Garstang wrote:

> I have the two dictionaries below. How can I merge them, such that:
> 
> 1. The cluster dictionary contains the additional elements from the
> default dictionary.
> 2. Nothing is removed from the cluster dictionary.

def inplace_merge(default, cluster):
assert isinstance(default, dict)
assert isinstance(cluster, dict)

d = set(default)
c = set(cluster)
default_only = d - c
both = d & c
for key in both:
dv = default[key]
cv = cluster[key]
if isinstance(cv, dict):
inplace_merge(dv, cv)
cluster.update((dk, default[dk]) for dk in default_only)

should work once you've fixed your example dicts.

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


Re: How to capture all the environment variables from shell?

2010-08-02 Thread Thorsten Kampe
* Tim Chase (Mon, 26 Jul 2010 21:42:24 -0500)
> On 07/26/10 21:26, Steven W. Orr wrote:
> > Please! Never export anything from your .bashrc unless you
> > really know what you're doing. Almost all exports should be
> > done in your .bash_profile
> 
> Could you elaborate on your reasoning why (or why-not)?  I've 
> found that my .bash_profile doesn't get evaluated when I crank up 
> another terminal window, while my bashrc does.  Thus I tend to 
> put my exports in my ~/.bashrc so they actually take effect in my 
> shell...

~/.bash_profile is only evaluated for login shells and ~/.bashrc only 
for non-login shells. Thus it's recommended to keep ~/.bash_profile 
empty (except a source statement for .bashrc) and put all your settings, 
aliases, exports, etc. in .bashrc.

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


Re: Access stdout from external program.

2010-08-02 Thread Jean-Michel Pichavant

Paul Lemelle wrote:

Hi JM,

My last dumb question:  When I try to run the below script as an 
executable, I get the following error:

ptt...@ptttestvm:~$ ./argv.py 4
import: unable to open X server `/tmp/launch-c8feFG/org.x:0' @ 
import.c/ImportImageCommand/361.

./argv.py: line 8: syntax error near unexpected token `print'
./argv.py: line 8: `   print x'

The script:
# Writing the output to a standard argv argument

#!/usr/bin/env python

import sys

for x in sys.argv:
   print x
 


#END

Any idea why?

Thanks,
Paul



Please don't remove python-list.

I see 2 possibilities:

1/ this is related to the open X server, for that I can't help you, 
something related to your exported display if you're remotely logged on 
the machine
2/ you are using python 2.x syntax within a python 3 interpreter. Try 
"print (x)".



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


Capturing running Application

2010-08-02 Thread S.Selvam
Hi all,

 I am using python 2.6(running ubuntu 9.10 ).

I want to display the amount of time spent( by an user)  among all the
 running applications like Gedit, Firefox, GIMP and display the result
graphically.

For eg:
Firefox: 60%
Gedit:25%
Terminal:15%

I think, i need to capture the currently focussed application, update the
time spent in some format and display it graphically.

I am not sure about the modules that need to be used.I welcome your ideas.





-- 
Regards,
S.Selvam

   " I am because we are "
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Tim Wintle
On Sun, 2010-08-01 at 20:01 -0400, Terry Reedy wrote:
> Not every C programmer knows or wants to learn C++.

I think Terry is the only person that's mentioned this - but I'd like to
give extra support to it - I for one prefer C to C++ (as someone that
writes quite a lot of C extension modules).

And as Stephen mentioned - just because C is not an OO language, doesn't
mean you can't write OO code in it - you just have to pass an instance
of the class method is defined on in as the first parameter (like you do
in Python).


Tim

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


Re: The untimely dimise of a weak-reference

2010-08-02 Thread Bruno Desthuilliers

Gregory Ewing a écrit :
(snip)


import weakref

class weakmethod(object):

  def __init__(self, bm):
self.ref = weakref.ref(bm.im_self)
self.func = bm.im_func

  def __call__(self, *args, **kwds):
obj = self.ref()
if obj is None:
  raise ValueError("Calling dead weak method")
self.func(obj, *args, **kwds)


Would be better with :

  return self.func(obj, *args, *kwds)

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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Jean-Michel Pichavant

Paul Rubin wrote:

Michele Simionato  writes:
  

I am actually more radical than that. From
http://www.artima.com/weblogs/viewpost.jsp?thread=237121:
In this series I have argued that super is tricky; I think nobody can...



When I look at that URL, I see a Java stack dump:

  java.lang.RuntimeException: 
com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid
  at 
com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112)
  ...

Seems appropriate.
  

remove the ending double dot.

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


Re: Trying to set a cookie within a python script

2010-08-02 Thread Steven D'Aprano
On Sun, 01 Aug 2010 23:39:34 -0700, Νίκος wrote:

> If you just click in my web page to see the script run in action due to
> the cgitb module i use it will provide you both the source code that the
> error appears and the error as well.
> 
> All you have to do is click here:
> http://www.webville.gr/cgi-bin/koukos.py

I'll do this just once, but next time, don't expect others to track down 
the error message for you. We're volunteers, we don't owe you anything, 
so if you want us to help, you make it easy for us. Some people have 
access to email, but not web. If you can't be bothered to copy and paste 
the error message into an email or news post, why should we be bothered 
to help you?


The error you are getting is:

NameError: name 'time' is not defined 

That tells you that you don't have a function called time() defined 
anywhere. You need to import the time module first:

import time

and then use the fully qualified function name time.time(), or do:

from time import time

and then use the function alone time().

> As for the encoding why when i print greek characters they dont appear
> correctly in chrome in runtime?

What encoding does the web page claim to be?

You need to check the document encoding, and see that it matches the 
document encoding you are actually using.




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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Steven D'Aprano
On Sun, 01 Aug 2010 23:15:11 -0700, Michele Simionato wrote:

> On Jul 31, 5:08 am, Steven D'Aprano  cybersource.com.au> wrote:
>> I have read Michelle Simionato's articles on super in Python.
> 
> One "l" please! I am a man! ;-)

My apologies. You'd think I would know the difference between Michele and 
Michelle :(


[snip]
> Still I believe that super is a red herring and that you should really
> start thinking: what advantages did
> multiple inheritance *really* bring into my code? Could have I done
> without? And what would have happen?
> These are the relevant question, not the exact meaning of super in hairy
> hierarchies.

Yes, these are very good points. It's always worth looking at 
alternatives to subclassing in the first place. Far too often it's not 
just the first idiom people think of, but the *only* idiom they think of.



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


Re: Normalizing A Vector

2010-08-02 Thread Bartc
"Alain Ketterlin"  wrote in message 
news:877hkdhyl5@dpt-info.u-strasbg.fr...
> Lawrence D'Oliveiro  writes:
>
>> Say a vector V is a tuple of 3 numbers, not all zero. You want to 
>> normalize
>> it (scale all components by the same factor) so its magnitude is 1.
>>
>> The usual way is something like this:
>>
>> L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2])
>> V = (V[0] / L, V[1] / L, V[2] / L)

> Your best bet is to define a function that does the normalization. Your
> (local) name will disappear at the end of the call. If you want it to
> work for any vector size:
>
> def norm(V):
>L = math.sqrt( sum( [x**2 for x in V] ) )
>return [ x/L for x in V ]

There's a cost involved in using those fancy constructions. I found the 
following to be about twice as fast, when vectors are known to have 3 
elements:

def norm3d(v):
L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2]))
return (v[0]/L,v[1]/L,v[2]/L)

(Strangely, changing those divides to multiplies made it slower.)

-- 
Bartc


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


Re: Normalizing A Vector

2010-08-02 Thread Alain Ketterlin
"Bartc"  writes:

>> def norm(V):
>>L = math.sqrt( sum( [x**2 for x in V] ) )
>>return [ x/L for x in V ]
>
> There's a cost involved in using those fancy constructions.

Sure. The above has three loops that take some time.

> I found the following to be about twice as fast, when vectors are
> known to have 3 elements:
>
> def norm3d(v):
> L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2]))
> return (v[0]/L,v[1]/L,v[2]/L)
>
> (Strangely, changing those divides to multiplies made it slower.)

You mean by setting L to 1.0 / math.sqrt(...) and using v[0]*L etc.?
I think * and / have the same cost on floats, and the added / adds
some cost. But what you observe is probably caused by the overloading of
"*", that needs more type checks. You may try with operator.mul to see
if the call compensates the cost of type checking, but I doubt it.

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


python3: signal.signal/singal.alarm not working as expected

2010-08-02 Thread Alan
Hi there,

I have this example code to illustrate a problem I am having with python3.
It works fine with python 2.6 and 2.7 but does not with python 3.1.

Please, can someone tell me why or how to fix this example?


from __future__ import print_function
import os, subprocess, signal

def signal_handler( signum, frame ):

print( "PID: %s" % pid )
print( "Timed out! Process %s killed, max exec time (%ss) exceeded" %
(pid, timeTol ) )
os.kill( int( pid ), 15 )
raise Exception( "Taking too long to finish... aborting!" )

if __name__ == '__main__':

timeTol = 5

cmd = 'find /'

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(timeTol)

p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout
= subprocess.PIPE)
pid = p.pid

out = str( p.communicate()[0].decode() )
print(out)


Many thanks,

Alan

-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Normalizing A Vector

2010-08-02 Thread Bartc

"Alain Ketterlin"  wrote in message
news:87fwyxgvuv@dpt-info.u-strasbg.fr...
> "Bartc"  writes:

>> def norm3d(v):
>> L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2]))
>> return (v[0]/L,v[1]/L,v[2]/L)
>>
>> (Strangely, changing those divides to multiplies made it slower.)
>
> You mean by setting L to 1.0 / math.sqrt(...) and using v[0]*L etc.?

Yes.

> I think * and / have the same cost on floats, and the added / adds
> some cost.

I expected no measurable difference, not running Python anyway (I tried it
in gcc and using divides increased runtimes by 50%, corresponding to some 1% 
for Python).

I would naturally have written it using multiplies, and was just surprised
at a 3-4% slowdown.

> But what you observe is probably caused by the overloading of
> "*", that needs more type checks.

That sounds reasonable.

-- 
Bartc



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


Re: beginner python GUI question

2010-08-02 Thread Chris Hare

On Aug 1, 2010, at 8:33 PM, rechardchen wrote:

> 于 2010-8-2 6:15, Chris Hare 写道:
>> I hope I can explain this correctly.
>> 
>> I have a GUI, which is already being processed by a mainloop.  I want to be 
>> able to open a second window so the user can interact with specific 
>> information in the second window.  I pulled together this code example
>> 
>> from Tkinter import *
>> 
>> class Net:
>>  def __init__(self,tkWin):
>>  self.window = tkWin
>>  def show(self,t):   
>>  self.l = Label(self.window,text=t)
>>  self.l.grid()
>> button = Button(self.window, text="Again")
>>  button.bind("", self.Again)
>>  button.grid()
>>  def Again(self,event):
>>  win3 = Tk()
>>  x = Net(win3)
>>  x.show("window 3")
>> 
>> root = Tk()
>> root.title = "test"
>> f = Frame(root,bg="Yellow")
>> l = Label(f,text="window 1")
>> f.grid()
>> l.grid()
>> 
>> win2 = Tk()
>> x = Net(win2)
>> x.show("window 2")
>> if __name__ == "__main__":
>>  root.mainloop()
>> 
>> Is this the right way to do things, or would you suggest something different?
>> 
>> Thanks,
>> Chris
>> 
> Using Tkinter.Toplevel may be better. :)
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I thought that would be a good idea, so I changed the code a bit to this:

from Tkinter import *

class Net:
def __init__(self):
self.window = Toplevel()
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
button = Button(self.window, text="Again")
button.bind("", self.Again)
button2 = Button(self.window, text="Dismiss")
button2.bind("", self.window.destroy)
button.grid()
button2.grid()
def Again(self,event):
x = Net()
x.show("window 3")

root = Tk()
root.title = "test"
f = Frame(root,bg="Yellow")
l = Label(f,text="window 1")
f.grid()
l.grid()

x = Net()
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

I put the call to Topevel into the Class.  This however, gets me an error 
message

Traceback (most recent call last):
  File "a.py", line 27, in 
x = Net()
  File "a.py", line 5, in __init__
self.window = Toplevel()
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1978, in __init__
self.title(root.title())
TypeError: 'str' object is not callable

I should think it would work, but I don't understand why it doesn't.

Thanks

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


run subprocesses in parallel

2010-08-02 Thread Santiago Caracol
Hello,

I want to run several subprocesses. Like so:

p1 = Popen("mycmd1" + " myarg", shell=True)
p2 = Popen("mycmd2" + " myarg", shell=True)
...
pn = Popen("mycmdn" + " myarg", shell=True)

What would be the most elegant and secure way to run all n
subprocesses in parallel?

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


Re: run subprocesses in parallel

2010-08-02 Thread Christian Heimes
> I want to run several subprocesses. Like so:
> 
> p1 = Popen("mycmd1" + " myarg", shell=True)
> p2 = Popen("mycmd2" + " myarg", shell=True)
> 
> pn = Popen("mycmdn" + " myarg", shell=True)
> 
> What would be the most elegant and secure way to run all n
> subprocesses in parallel?

They already run in parallel. Depending on your command this may not be
secure due to race conditions. You might want to drop shell=True and use
a list as arguments instead. The shell=True argument is frowned upon and
should only be used if your really, really need a shell.

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


Re: beginner python GUI question

2010-08-02 Thread Peter Otten
Chris Hare wrote:

>>> root = Tk()
>>> root.title = "test"

> I should think it would work, but I don't understand why it doesn't.

Try

root.title("test")

title() is a method that you are hiding with your attribute leading to 
problems later on.

By the way, what kind of documentation are you using for your efforts?

Here's a concise one:

http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html

Also, effbot.org has a lot of information that you best access via Google.

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


Re: How to catch windows shutdown/reboot message

2010-08-02 Thread rechardchen

于 2010-8-2 16:00, Tim Golden 写道:

On 02/08/2010 02:17, rechardchen wrote:

I'm writing a python script which runs as a windowsxp service.
The problem is how to catch the windows shutdown/reboot message and do
some cleaning job when system is going down?

The atexit module and signal module on windows dont seems to work. I
guess the python win32api may be of help, but I am not familiar with
it...
Thank you


Have a look at the SENS stuff:

http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html

TJG

Thanks, the extended handler functionality works. :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to set a cookie within a python script

2010-08-02 Thread Νίκος
Steven,

First of all thank you for your response. I cant beleive i neglected
to import the time module!

The only reason that i asked you guys to follow the link was for you
to see the actualt coding and error report as python produces it by
itself with all the relative characteristics. Of course it was not due
to boredom and there was no need to be aggresive with me as this
wasn't the case. I thouigh that by giving the URL was easier for you
guys.

Now the script runs but for some reason only the code block within the
'else' tun each time:

This:
else:
print "ΑΠΟ ΔΩ ΚΑΙ ΣΤΟ ΕΞΗΣ ΔΕΝ ΣΕ ΕΙΔΑ, ΔΕΝ ΣΕ ΞΕΡΩ, ΔΕΝ ΣΕ ΑΚΟΥΣΑ!
ΘΑ ΕΙΣΑΙ ΠΛΕΟΝ Ο ΑΟΡΑΤΟΣ ΕΠΙΣΚΕΠΤΗΣ!!"
cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 )  #this 
cookie
will expire in an year

The cookie is only get set and never expires

i changed the if with this

if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') ==
'nikos':#if visitor cookie exist

but still no luck.

As for the encoding Notepad++, which is what i use for an editor say
its UTF-8 without BOM.

Isn't this what i'm supposed to use?

My Python scripts only containes english and greek letters, so i
though usign UTF-8 is the way to go. No?! Please if you explain to me
in greater detail!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner python GUI question

2010-08-02 Thread Chris Hare

On Aug 2, 2010, at 7:25 AM, Peter Otten wrote:

> Chris Hare wrote:
> 
 root = Tk()
 root.title = "test"
> 
>> I should think it would work, but I don't understand why it doesn't.
> 
> Try
> 
> root.title("test")
> 
> title() is a method that you are hiding with your attribute leading to 
> problems later on.
> 
> By the way, what kind of documentation are you using for your efforts?
> 
> Here's a concise one:
> 
> http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html
> 
> Also, effbot.org has a lot of information that you best access via Google.
> 
> Peter
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I have several python books and I have been using effbot and various other 
sources.  Thanks for the help.  Your suggestion (and a couple others I added) 
got my example working exactly like I want it, so I can incorporate that into 
my program.  Thanks again.

Chris

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


Re: Mechanize - save to XML or CSV

2010-08-02 Thread Simon Brunning
On 2 August 2010 14:13, flebber  wrote:
> HI guys and gals this is probably a simple question but I can't find
> the answer directly in the docs for python mechanize.
>
> http://pypi.python.org/pypi/mechanize/
>
> Is it possible to retrieve and save a web page data as xml or a csv
> file?

Sure, but mechanize only does the first half of the job. You retrieve
the data using mechanize, then use another module for the save-as bit.
ElementTree for XML and csv for, um, for csv are both in the standard
library.

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Grant Edwards
On 2010-08-02, Christian Heimes  wrote:

> In your opinion what would Python gain from a C++ implementation?

Greater buzzword-compliance -- an important characteristic highly
prized by Human-Resources poeple and mid-level managers here in the
US.

;)

-- 
Grant

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


AMY JACKSON HOT PICTURES including upcoming movies, biography,

2010-08-02 Thread amyjack1
AMY JACKSON HOT PICTURES including upcoming movies, biography,

http://amyjacksons.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Mark Lawrence

On 01/08/2010 12:10, Lawrence D'Oliveiro wrote:

In message, Mark
Lawrence wrote:


On 01/08/2010 08:18, Lawrence D'Oliveiro wrote:


In message, Mark
Lawrence wrote:


On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:


In message, Mark
Lawrence wrote:


Personally I find double clicking on an msi file rather easier.


Easier than apt-get dist-upgrade?


I'm sorry but I only do English, could you please translate. :)


I run Debian Unstable, which has new goodies coming out on a weekly
basis. The last time I checked for updates, there were over 500 packages
I had installed for which updates were available. It only took a command
like the above to upgrade them all.

How many .msi files would you have to click on to achieve the Windows
equivalent?


... I simply couldn't cope with over 500 installed packages.


Precisely my point. Go back to playing with your .msi toys.

Oh, and.


Repeating what was obviously deliberately snipped.

"No idea, but your mental capacity is clearly infinitely higher than 
mine, as I simply couldn't cope with over 500 installed packages.  What 
do they all do, make your lunch and fetch the beer from the fridge 
amongst other things?"


How does any user or an admin cope with 500 packages?  Can Python help 
here, assume an eight hour working day?


c:\Python31\Lib>python
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> 8*60*60/500
57.6

So every working day you have 57.6 seconds to use each package. 
Strangely I don't think anyone will get too much done.  Am I in cloud 
cuckoo land or are you?


As it happens, I'm also not a windows fan, did most of my work on VMS. 
Which to repeat myself stands for Very Much Safer.  Thinking of which 
did *nix ever get around to providing proper clustering, or does VMS 
still rule?


Mark Lawrence.

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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 10:23, Jean-Michel Pichavant wrote:

Paul Rubin wrote:

Michele Simionato  writes:

I am actually more radical than that. From
http://www.artima.com/weblogs/viewpost.jsp?thread=237121:
In this series I have argued that super is tricky; I think nobody can...


When I look at that URL, I see a Java stack dump:

java.lang.RuntimeException:
com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid
at
com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112)

...

Seems appropriate.

remove the ending double dot.

JM


aka the colon. :)

Cheers.

Mark  Lawrence

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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 07:15, Michele Simionato wrote:

On Jul 31, 5:08 am, Steven D'Aprano  wrote:

I have read Michelle Simionato's articles on super in Python.


One "l" please! I am a man! ;-)


Please prove it, get your bits out!!! :)


 M. Simionato



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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Benjamin Kaplan
On Mon, Aug 2, 2010 at 8:21 AM, Mark Lawrence wrote:

> On 01/08/2010 12:10, Lawrence D'Oliveiro wrote:
>
>> In message, Mark
>> Lawrence wrote:
>>
>>  On 01/08/2010 08:18, Lawrence D'Oliveiro wrote:
>>>
>>>  In message, Mark
 Lawrence wrote:

  On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:
>
>  In message, Mark
>> Lawrence wrote:
>>
>>  Personally I find double clicking on an msi file rather easier.
>>>
>>
>> Easier than apt-get dist-upgrade?
>>
>
> I'm sorry but I only do English, could you please translate. :)
>

 I run Debian Unstable, which has new goodies coming out on a weekly
 basis. The last time I checked for updates, there were over 500 packages
 I had installed for which updates were available. It only took a command
 like the above to upgrade them all.

 How many .msi files would you have to click on to achieve the Windows
 equivalent?

>>>
>>> ... I simply couldn't cope with over 500 installed packages.
>>>
>>
>> Precisely my point. Go back to playing with your .msi toys.
>>
>> Oh, and.
>>
>
> Repeating what was obviously deliberately snipped.
>
> "No idea, but your mental capacity is clearly infinitely higher than mine,
> as I simply couldn't cope with over 500 installed packages.  What do they
> all do, make your lunch and fetch the beer from the fridge amongst other
> things?"
>
> How does any user or an admin cope with 500 packages?  Can Python help
> here, assume an eight hour working day?
>
> c:\Python31\Lib>python
> Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> 8*60*60/500
> 57.6
>
> So every working day you have 57.6 seconds to use each package. Strangely I
> don't think anyone will get too much done.  Am I in cloud cuckoo land or are
> you?
>
>
You seem to be mistaken as to what a "package" is.

Python :
* python
* python-minimal
* python2.6
* libbz2
* libc6
* libdb4.8
* libncursesw5
* libreadline6
* mime-support
* python2.6-minimal
* libssl0.9.8
* zlib1g
* debconf
* perl-base
* dpkg
* coreutils
* lzma
* libacl1
* libattr1
* libselinux1
* libgcc1
* libstdc++6
* gcc-4.4-base
* libncurses5
* readline-common

So these are the packages needed just to run Python in Ubuntu. It doesn't
include the packages required for the kernel, the desktop environment, the
window manager, the terminal, and whatever else you want running. In my
fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
close to 1500 packages installed.






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


THANKS GOD! I GOT $2000 FROM PAYPAL....

2010-08-02 Thread paypal cash
THANKS GOD!  I GOT $2000 FROM PAYPAL  At  http://ukcollegegirls.co.cc

I have hidden the PayPal Form link in an image.
in that website On Top Side Above search box ,
click on image and enter your  PayPal  id And Your name.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread David Cournapeau
On Mon, Aug 2, 2010 at 10:20 AM, Christian Heimes  wrote:

>
> In your opinion what would Python gain from a C++ implementation?

The elusive advantages of "OO" in C++ are relatively minor compared to
RIIA which would make reference counting much easier to deal with. But
even that is not a strong enough argument for C++. The little C++ we
have in scipy had causes a lot of headache - C++ portability is still
an issue once you are outside the 4-5 main OS/Compilers combinations,

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Thomas Jollans
On 08/02/2010 04:42 PM, Grant Edwards wrote:
> On 2010-08-02, Christian Heimes  wrote:
> 
>> In your opinion what would Python gain from a C++ implementation?
> 
> Greater buzzword-compliance -- an important characteristic highly
> prized by Human-Resources poeple and mid-level managers here in the
> US.
> 
> ;)
> 

C++Python would never beat IronPython on that front
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 16:41, Benjamin Kaplan wrote:

On Mon, Aug 2, 2010 at 8:21 AM, Mark Lawrencewrote:


On 01/08/2010 12:10, Lawrence D'Oliveiro wrote:


In message, Mark
Lawrence wrote:

  On 01/08/2010 08:18, Lawrence D'Oliveiro wrote:


  In message, Mark

Lawrence wrote:

  On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:


  In message, Mark

Lawrence wrote:

  Personally I find double clicking on an msi file rather easier.




Easier than apt-get dist-upgrade?



I'm sorry but I only do English, could you please translate. :)



I run Debian Unstable, which has new goodies coming out on a weekly
basis. The last time I checked for updates, there were over 500 packages
I had installed for which updates were available. It only took a command
like the above to upgrade them all.

How many .msi files would you have to click on to achieve the Windows
equivalent?



... I simply couldn't cope with over 500 installed packages.



Precisely my point. Go back to playing with your .msi toys.

Oh, and.



Repeating what was obviously deliberately snipped.

"No idea, but your mental capacity is clearly infinitely higher than mine,
as I simply couldn't cope with over 500 installed packages.  What do they
all do, make your lunch and fetch the beer from the fridge amongst other
things?"

How does any user or an admin cope with 500 packages?  Can Python help
here, assume an eight hour working day?

c:\Python31\Lib>python
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

8*60*60/500

57.6

So every working day you have 57.6 seconds to use each package. Strangely I
don't think anyone will get too much done.  Am I in cloud cuckoo land or are
you?



You seem to be mistaken as to what a "package" is.

Python :
* python
* python-minimal
* python2.6
* libbz2
* libc6
* libdb4.8
* libncursesw5
* libreadline6
* mime-support
* python2.6-minimal
* libssl0.9.8
* zlib1g
* debconf
* perl-base
* dpkg
* coreutils
* lzma
* libacl1
* libattr1
* libselinux1
* libgcc1
* libstdc++6
* gcc-4.4-base
* libncurses5
* readline-common

So these are the packages needed just to run Python in Ubuntu. It doesn't
include the packages required for the kernel, the desktop environment, the
window manager, the terminal, and whatever else you want running. In my
fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
close to 1500 packages installed.


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





I'll stick with my msi files and/or windows update then, unless I have 
the luck to get back to VMS.  As I said earlier it strikes me that this 
*nix stuff is simply archaic.


Kindest regards.

Mark Lawrence.


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


Re: Merging two dictionaries

2010-08-02 Thread Douglas Garstang
On Mon, Aug 2, 2010 at 12:47 AM, Paul Rubin  wrote:
> Douglas Garstang  writes:
>> default = {...
>>                 'data_sources': { ...
>> cluster = {...
>>                 'data_source': { ...
>
> Did you want both of those to say the same thing instead of one
> of them being 'data_source' and the other 'data_sources' ?
>
> If yes, then the following works for me:
>
>    def merge(cluster, default):
>        # destructively merge default into cluster
>        for k,v in cluster.iteritems():
>            if k in default and type(v)==dict:
>                assert type(default(k))==dict
>                merge(v,default[k])
>        for k,v in default.iteritems():
>            if k not in cluster:
>                cluster[k] = v
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Hmmm, using that gives me:

Traceback (most recent call last):
  File "./test4.py", line 48, in ?
merge(cluster, default)
  File "./test4.py", line 42, in merge
assert type(default(k))==dict
TypeError: 'dict' object is not callable

where line 42 is 'assert type(default(k))==dict', and the inputs are:

default = {
'cluster': {
'platform': {
'elements': {
'data_sources': {
'elements': {
'db_min_pool_size': 10
},
},
},
},
}
}

cluster = {
'cluster': {
'name': 'Customer 1',
'description': 'Customer Production',
'environment': 'production',
'platform': {
'elements': {
'data_source': {
'elements': {
'username': 'username',
'password': 'password'
},
},
},
},
}
}

and it's called with:

merge(cluster, default)

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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Ethan Furman

Steven D'Aprano wrote:

On Sat, 31 Jul 2010 13:29:25 +, Brian Victor wrote:


Steven D'Aprano wrote:

On Sat, 31 Jul 2010 14:25:39 +1200, Gregory Ewing wrote:


Steven D'Aprano wrote:


  A
 / \
C   B
 \ /
  D
 / \
E   F

Yes, a super call might jog left from C to B, but only when being
called from one of the lower classes D-F. That's still an upwards
call relative to the originator, not sidewards.

But it's not an upward call relative to the class mentioned in the
super() call, which is why I say it's misleading.

Which class would that be?

I think I'm going to need an example that demonstrates what you mean,
because I can't make heads or tails of it. Are you suggesting that a
call to super(C, self).method() from within C might call
B.method(self)?

Yes, it would.

[snip example]

Right, now I see what you mean. I don't have a problem with that 
behaviour, it is the correct behaviour, and you are making the call from 
D in the first place, so it *must* call B at some point.


If you initiate the call from C instead:

[snip]

I think the point is that when D initiates the  super() chain, and C 
calls super, B will then get its turn -- which has to seem arbitrary 
from C's point of view.


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


Re: Merging two dictionaries

2010-08-02 Thread Peter Otten
Douglas Garstang wrote:

> On Mon, Aug 2, 2010 at 12:47 AM, Paul Rubin  
wrote:

>> If yes, then the following works for me:
>>
>>def merge(cluster, default):
>># destructively merge default into cluster
>>for k,v in cluster.iteritems():
>>if k in default and type(v)==dict:
>>assert type(default(k))==dict
>>merge(v,default[k])
>>for k,v in default.iteritems():
>>if k not in cluster:
>>cluster[k] = v
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> 
> Hmmm, using that gives me:
> 
> Traceback (most recent call last):
>   File "./test4.py", line 48, in ?
> merge(cluster, default)
>   File "./test4.py", line 42, in merge
> assert type(default(k))==dict
> TypeError: 'dict' object is not callable
> 
> where line 42 is 'assert type(default(k))==dict', and the inputs are:

Not making an attempt to understand the code that you are about to use?

default(k) 

should be

default[k]

Peter

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread David Robinow
On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan
 wrote:
>...
> So these are the packages needed just to run Python in Ubuntu. It doesn't
> include the packages required for the kernel, the desktop environment, the
> window manager, the terminal, and whatever else you want running. In my
> fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
> close to 1500 packages installed.
 As an admittedly stupid comparison, I have 1579 DLLs in my
\windows\system32 directory.
Some number of these have been upgraded by Windows Update. This is XP
Service Pack 3.
I'm not sure if this means that Windows is better because it has more
packages or that it is worse because it's got too many. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread donn

On 02/08/2010 17:35, Mark Lawrence wrote:

aka the colon. :)

Ha. This is a case of the colon being the appendix!

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


Re: Merging two dictionaries

2010-08-02 Thread Douglas Garstang
On Mon, Aug 2, 2010 at 1:09 AM, Peter Otten <__pete...@web.de> wrote:
> Douglas Garstang wrote:
>
>> I have the two dictionaries below. How can I merge them, such that:
>>
>> 1. The cluster dictionary contains the additional elements from the
>> default dictionary.
>> 2. Nothing is removed from the cluster dictionary.
>
> def inplace_merge(default, cluster):
>    assert isinstance(default, dict)
>    assert isinstance(cluster, dict)
>
>    d = set(default)
>    c = set(cluster)
>    default_only = d - c
>    both = d & c
>    for key in both:
>        dv = default[key]
>        cv = cluster[key]
>        if isinstance(cv, dict):
>            inplace_merge(dv, cv)
>    cluster.update((dk, default[dk]) for dk in default_only)
>
> should work once you've fixed your example dicts.
>
> Peter
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Wooo! I think that did it!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run subprocesses in parallel

2010-08-02 Thread Nobody
On Mon, 02 Aug 2010 14:21:38 +0200, Christian Heimes wrote:

> You might want to drop shell=True and use
> a list as arguments instead.

The two issues (whether "shell" is True/False and whether the command is
a list or string) are orthogonal.

You should always use a list for the command, unless you are given a
string (e.g. by the user) which must be executed verbatim.

> The shell=True argument is frowned upon and
> should only be used if your really, really need a shell.

It's the use of a string (rather than a list) for the command which is
particularly frowned upon, as this tends to be error prone if any of the
arguments contain characters which are significant to the shell (most
commonly spaces, although other characters are also problematic).

On Unix, using a list for the command effectively necessitates that
shell=False (if you use a list with shell=True, the first element in the
list is executed as the command, with any remaining elements used to
initialise $1, $2, etc).

On Windows, the list is converted to a string in the same way regardless
of whether shell is True or False. The shell parameter determines whether
the string is passed directly to CreateProcess or whether it has
"%COMSPEC% /c " prepended to it. If shell is False, the first element in
the list (the program) must refer to a binary executable and include the
.exe (etc) extension. If shell is True, the program can be a batch file,
Python script, etc, and will be executed according to its extension.

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


Re: Accumulate function in python

2010-08-02 Thread Aahz
In article <7xpqyjgvjm@ruckus.brouhaha.com>,
Paul Rubin   wrote:
>
>I think Peter Otten's solution involving a generator is the one most in
>the current Python spirit.  It's cleaner (for my tastes) than the ones
>that use things like list.append.

Agreed
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Normal is what cuts off your sixth finger and your tail..."  --Siobhan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Merging two dictionaries

2010-08-02 Thread Paul Rubin
Douglas Garstang  writes:
> where line 42 is 'assert type(default(k))==dict', and the inputs are:

Woops, cut and paste error.  default(k) should say default[k].  Or you
could remove the assertion altogether.
-- 
http://mail.python.org/mailman/listinfo/python-list


Behavior of re.split on empty strings is unexpected

2010-08-02 Thread John Nagle
The regular expression "split" behaves slightly differently than string 
split:


>>> import re
>>> kresplit = re.compile(r'[^\w\&]+',re.UNICODE)  

>>> kresplit2.split("   HELLOTHERE   ")
['', 'HELLO', 'THERE', '']

>>> kresplit2.split("VERISIGN INC.")
['VERISIGN', 'INC', '']

I'd thought that "split" would never produce an empty string, but
it will.

The regular string split operation doesn't yield empty strings:

>>> "   HELLO   THERE ".split()
['HELLO', 'THERE']

If I try to get the functionality of string split with re:

>>> s2 = "   HELLO   THERE  "
>>> kresplit4 = re.compile(r'\W+', re.UNICODE)
>>> kresplit4.split(s2)
['', 'HELLO', 'THERE', '']

I still get empty strings.

The documentation just describes re.split as "Split string by the 
occurrences of pattern", which is not too helpful.


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


constructing and using large lexicon in a program

2010-08-02 Thread Majdi Sawalha
Dear List members,

I am developing a morphological analyzer that depends on a large lexicon. i 
construct a Lexicon class that reades a text file and construct a dictionary of 
the lexicon entries. 
the other class will use the lexicon class to chech if the word is found in the 
lexicon. the problem that this takes long time as each time an object of that 
class created, then it needs to call the lexicon many times. then when the 
lexicon is called it re-construct the lexicon again. is there any way to 
construct the lexicon one time during the execution of the program? and then 
the 
other modules will search the already constructed lexicon.

best regards
Majdi
 
Faculty of Engineering
School of Computing
University of Leeds
Leeds, LS2 9JT
UK
http://www.comp.leeds.ac.uk/sawalha 


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


Re: constructing and using large lexicon in a program

2010-08-02 Thread Michael Torrie
On 08/02/2010 11:46 AM, Majdi Sawalha wrote:
> I am developing a morphological analyzer that depends on a large lexicon. i 
> construct a Lexicon class that reades a text file and construct a dictionary 
> of 
> the lexicon entries. 
> the other class will use the lexicon class to chech if the word is found in 
> the 
> lexicon. the problem that this takes long time as each time an object of that 
> class created, then it needs to call the lexicon many times. then when the 
> lexicon is called it re-construct the lexicon again. is there any way to 
> construct the lexicon one time during the execution of the program? and then 
> the 
> other modules will search the already constructed lexicon.

Can you not create a module that, upon import, initializes this lexicon
as a module attribute?  Modules are by definition singleton objects,
which is the pattern that you probably need.  Any other module could
import this module and get the already-created lexicon object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread MRAB

John Nagle wrote:
The regular expression "split" behaves slightly differently than string 
split:


 >>> import re
 >>> kresplit = re.compile(r'[^\w\&]+',re.UNICODE)   


 >>> kresplit2.split("   HELLOTHERE   ")
['', 'HELLO', 'THERE', '']

 >>> kresplit2.split("VERISIGN INC.")
['VERISIGN', 'INC', '']

I'd thought that "split" would never produce an empty string, but
it will.

The regular string split operation doesn't yield empty strings:

 >>> "   HELLO   THERE ".split()
['HELLO', 'THERE']


Yes it does.

>>> "   HELLOTHERE   ".split(" ")
['', '', '', 'HELLO', '', '', '', 'THERE', '', '', '']


If I try to get the functionality of string split with re:

 >>> s2 = "   HELLO   THERE  "
 >>> kresplit4 = re.compile(r'\W+', re.UNICODE)
 >>> kresplit4.split(s2)
['', 'HELLO', 'THERE', '']

I still get empty strings.

The documentation just describes re.split as "Split string by the 
occurrences of pattern", which is not too helpful.



It's the plain str.split() which is unusual in that:

1. it splits on sequences of whitespace instead of one per occurrence;

2. it discards leading and trailing sequences of whitespace.

Compare:

>>> "  A  B  ".split(" ")
['', '', 'A', '', 'B', '', '']

with:

>>> "  A  B  ".split()
['A', 'B']

It just happens that the unusual one is the most commonly used one, if
you see what I mean! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread Peter Otten
John Nagle wrote:

> The regular string split operation doesn't yield empty strings:
> 
> >>> "   HELLO   THERE ".split()
> ['HELLO', 'THERE']

Note that invocation without separator argument (or None as the separator) 
is special in that respect:

>>> " hello there ".split(" ")
['', 'hello', 'there', '']

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Benjamin Kaplan
On Mon, Aug 2, 2010 at 9:51 AM, David Robinow  wrote:

> On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan
>  wrote:
> >...
> > So these are the packages needed just to run Python in Ubuntu. It doesn't
> > include the packages required for the kernel, the desktop environment,
> the
> > window manager, the terminal, and whatever else you want running. In my
> > fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
> > close to 1500 packages installed.
>  As an admittedly stupid comparison, I have 1579 DLLs in my
> \windows\system32 directory.
> Some number of these have been upgraded by Windows Update. This is XP
> Service Pack 3.
> I'm not sure if this means that Windows is better because it has more
> packages or that it is worse because it's got too many. :)
>  --
>

A package is usually more than one file.
http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist


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


namespaces, scoping and variables

2010-08-02 Thread Chris Hare
I am having a problem getting around this variable namespace thing.

Consider these code bits

File a.py
from Tkinter import *
import a1

def doAgain():
x = a1.Net()
x.show("Again!")

root = Tk()
root.title("test")
f = Frame(root,bg="Yellow")
l = Button(root,text="window 1",command=doAgain)
f.grid()
l.grid()
a = 5
x = a1.Net()
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

File a1.py
from Tkinter import *

class Net:
def __init__(self):
self.window = Toplevel()
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
button = Button(self.window, text="Again")
button.bind("", self.Again)
button2 = Button(self.window, text="Dismiss")
button2.bind("", self.hide)
button.grid()
button2.grid()
def Again(self,event):
x = Net()
x.show(a)
def hide(self,event):
self.window.destroy()


When I run a.py, it imports a1.py and click on the Again button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File "/Volumes/Development/py/a1.py", line 17, in Again
x.show(a)
NameError: global name 'a' is not defined

I believe this is the expected behavior.  so my question is this -- how do I 
tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
to pass it as part of the function call, or what?  using

global a

in a1.py doesn't change anything.

since I am using SQLite for the disk database, I was thinking I could keep all 
the "global" variables in an in memory database and just access them when I 
need to, but other ideas are welcome.

Thanks,
Chris

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


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread John Nagle

On 8/2/2010 11:02 AM, MRAB wrote:

John Nagle wrote:

The regular expression "split" behaves slightly differently than
string split:

occurrences of pattern", which is not too helpful.



It's the plain str.split() which is unusual in that:

1. it splits on sequences of whitespace instead of one per occurrence;


   That can be emulated with the obvious regular expression:

re.compile(r'\W+')


2. it discards leading and trailing sequences of whitespace.


   But that can't, or at least I can't figure out how to do it.


It just happens that the unusual one is the most commonly used one, if
you see what I mean! :-)


   The no-argument form of "split" shouldn't be that much of a special
case.

John Nagle

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


Re: namespaces, scoping and variables

2010-08-02 Thread Thomas Jollans
On 08/02/2010 09:33 PM, Chris Hare wrote:
> I am having a problem getting around this variable namespace thing.
> 
> Consider these code bits
> 
> File a.py
> from Tkinter import *
> import a1
> 
> def doAgain():
>   x = a1.Net()
>   x.show("Again!")
> 
> root = Tk()
> root.title("test")
> f = Frame(root,bg="Yellow")
> l = Button(root,text="window 1",command=doAgain)
> f.grid()
> l.grid()
> a = 5
> x = a1.Net()
> x.show("window 2")
> if __name__ == "__main__":
>   root.mainloop()
> 
> File a1.py
> from Tkinter import *
> 
> class Net:
>   def __init__(self):
>   self.window = Toplevel()
>   def show(self,t):   
>   self.l = Label(self.window,text=t)
>   self.l.grid()
> button = Button(self.window, text="Again")
>   button.bind("", self.Again)
> button2 = Button(self.window, text="Dismiss")
>   button2.bind("", self.hide)
>   button.grid()
>   button2.grid()
>   def Again(self,event):
>   x = Net()
>   x.show(a)
>   def hide(self,event):
>   self.window.destroy()
> 
> 
> When I run a.py, it imports a1.py and click on the Again button, I get the 
> error
> 
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File 
> "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
>  line 1410, in __call__
> return self.func(*args)
>   File "/Volumes/Development/py/a1.py", line 17, in Again
> x.show(a)
> NameError: global name 'a' is not defined
> 
> I believe this is the expected behavior.  so my question is this -- how do I 
> tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
> to pass it as part of the function call, or what?  using
> 
> global a
> 
> in a1.py doesn't change anything.
> 
> since I am using SQLite for the disk database, I was thinking I could keep 
> all the "global" variables in an in memory database and just access them when 
> I need to, but other ideas are welcome.

"global" in Python isn't the same as "global" in C, or in PHP.

"Global" is, in essence, a shorter way of saying "within the scope of
this module" -- which keeps the "global" nice and clean.

You should probably just pass in the object you call "a" when creating
the object that uses it, or when calling the function/method when
calling it. If you don't want to do that, you can simply import the
module where your global data is stored -- beware of "from XYZ import
...", though - that copies the variables, and won't do you much good here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread Thomas Jollans
On 08/02/2010 09:41 PM, John Nagle wrote:
> On 8/2/2010 11:02 AM, MRAB wrote:
>> John Nagle wrote:
>>> The regular expression "split" behaves slightly differently than
>>> string split:
> occurrences of pattern", which is not too helpful.
>>>
>> It's the plain str.split() which is unusual in that:
>>
>> 1. it splits on sequences of whitespace instead of one per occurrence;
> 
>That can be emulated with the obvious regular expression:
> 
> re.compile(r'\W+')
> 
>> 2. it discards leading and trailing sequences of whitespace.
> 
>But that can't, or at least I can't figure out how to do it.

[ s in rexp.split(long_s) if s ]

> 
>> It just happens that the unusual one is the most commonly used one, if
>> you see what I mean! :-)
> 
>The no-argument form of "split" shouldn't be that much of a special
> case.
> 
> John Nagle
> 

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


Re: namespaces, scoping and variables

2010-08-02 Thread Dave Angel

Chris Hare wrote:

I am having a problem getting around this variable namespace thing.

Consider these code bits

File a.py
from Tkinter import *
import a1

def doAgain():
x =1.Net()
x.show("Again!")

root =k()
root.title("test")
f =rame(root,bg="Yellow")
l =utton(root,text="window 1",command=doAgain)
f.grid()
l.grid()
a =
x =1.Net()
x.show("window 2")
if __name__ ="__main__":
root.mainloop()

File a1.py
from Tkinter import *

class Net:
def __init__(self):
self.window =oplevel()
def show(self,t):   
self.l =abel(self.window,text=t)
self.l.grid()
button =utton(self.window, text="Again")
button.bind("", self.Again)
button2 =utton(self.window, text="Dismiss")
button2.bind("", self.hide)
button.grid()
button2.grid()
def Again(self,event):
x =et()
x.show(a)
def hide(self,event):
self.window.destroy()


When I run a.py, it imports a1.py and click on the Again button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File "/Volumes/Development/py/a1.py", line 17, in Again
x.show(a)
NameError: global name 'a' is not defined

I believe this is the expected behavior.  so my question is this -- how do I 
tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
to pass it as part of the function call, or what?  using

global a

in a1.py doesn't change anything.

since I am using SQLite for the disk database, I was thinking I could keep all the 
"global" variables in an in memory database and just access them when I need 
to, but other ideas are welcome.

Thanks,
Chris


  
First rule is never have circular referencing between modules.  In other 
words, since a.py imports a1.py, a.py can refer to things in a1.py, but 
never the other way around.  Any time you need to look backwards, find 
another means.


One approach is to create another module c.py as a container to hold 
those things that both a and a1 need.  That way they both import c, and 
there's no problem.


Another approach is to pass the global from a.py into a1.py, and use it 
that way.


And since you only have these two modules, you could just define it in 
a1.py, and reference it from a.py as

  a1.a

I would point out that using the same name for a module and a global 
variable is bad practice.  it certainly makes it hard to describe in 
this case.


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


Re: Why is python not written in C++ ?

2010-08-02 Thread Mithrandir
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 08/01/2010 07:34 PM, Albert Hopkins wrote:
> On Mon, 2010-08-02 at 01:08 +0200, candide wrote:
>> Python is an object oriented langage (OOL). The Python main 
>> implementation is written in pure and "old" C90. Is it for historical 
>> reasons?
>>
>> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more 
>> suitable to implement an OOL with another one.
>>
>> Has it ever been planned to rewrite in C++ the historical implementation 
>> (of course in an object oriented design) ?
> 
> Disclaimer: I am neither a C nor C++ programmer.  In fact I can barely
> even program in Python ;-)
> 
> I would propose that in fact most programming languages are implemented
> in C.  Sun's (Oracle's) Java compiler and runtime are written in ANSI C.
> The core of the Gnu Compiler Collection (which includes C++ and
> Objective-C compilers) is written in C.  The official Ruby is
> implemented in C. The Squeak Smalltalk implementation uses C instead of
> C++.  I can't even think of a programming language that is implemented
> in C++ (maybe C++ is).
> 
> C seems to be a good, portable language for writing interpreters and
> compilers.
> 
> But I wonder if someone has/has tried to write a programming language in
> C++ and what were their experiences.
> 

(Sorry if this is a double post, but apparently my last one didn't go
through.)

I know that LOLCode has a .NET implementation (1), although it's "very
much alpha."  And someone was apparently working on a C++ only
implementation of LOLCode (2), although that was 3 years ago.

LOLCode itself is very much alpha anyway and development seems to be
very slow (or dead.)

Python has a way of extending it's modules with C or C++ (3).

1: http://lolcode.com/implementations/lolcode.net
2: http://forum.lolcode.com/viewtopic.php?id=14
3: http://docs.python.org/release/2.5.2/ext/intro.html

- -- 
People should read more.
https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain
"All that is gold does not glitter,
not all those who wander are lost;
the old that is strong does not wither,
deep roots are not reached by the frost.
- From the ashes a fire shall be woken,
a light from the shadows shall spring;
renewed shall be blade that was broken,
the crownless again shall be king."
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJMVyNqAAoJEKo37V1xH7gTeOUH/2/KYc4busZbATSB09ZUgW+v
BmydxDTZaPQd0B56JWSeUiz0/kZrufdDrVc3XUTNNF2oa8ExW51IgsaZOxn2UJGv
ydplycT1axs5hrzDG72v2Oo7/poPDxSsvpF58dBsb0XSI25I+orHKrTQpwvKz9cf
x6nzahUoygTbaVqZUyxCW2Tc7Rv4T2gpskssD8sIYqaRNofNnPbf3h3NA+q4LMkR
+F2UF3r1RE1jwJhs6RNAvUJBdLrHkA3isRsjQE38l6AioLdeTs2yrRtc+6xUkAig
RxR11qLZl5OOer/Jrmg1My0+ZTYGnIcAfChxPh1YnHuYbp+H7doqLjlKIkoXZms=
=F9Ou
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces, scoping and variables

2010-08-02 Thread MRAB

Chris Hare wrote:

I am having a problem getting around this variable namespace thing.

Consider these code bits

File a.py
from Tkinter import *
import a1

def doAgain():
x = a1.Net()
x.show("Again!")

root = Tk()
root.title("test")
f = Frame(root,bg="Yellow")
l = Button(root,text="window 1",command=doAgain)
f.grid()
l.grid()
a = 5
x = a1.Net()
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

File a1.py
from Tkinter import *

class Net:
def __init__(self):
self.window = Toplevel()
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
button = Button(self.window, text="Again")
button.bind("", self.Again)
button2 = Button(self.window, text="Dismiss")
button2.bind("", self.hide)
button.grid()
button2.grid()
def Again(self,event):
x = Net()
x.show(a)
def hide(self,event):
self.window.destroy()


When I run a.py, it imports a1.py and click on the Again button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File "/Volumes/Development/py/a1.py", line 17, in Again
x.show(a)
NameError: global name 'a' is not defined

I believe this is the expected behavior.  so my question is this -- how do I 
tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
to pass it as part of the function call, or what?  using

global a

in a1.py doesn't change anything.

since I am using SQLite for the disk database, I was thinking I could keep all the 
"global" variables in an in memory database and just access them when I need 
to, but other ideas are welcome.


Why in a database? If you need the modules to share it then you could
put it in a shared module and refer to it there:

File a.py
-
import my_globals
...
my_globals.a = 5


File a1.py
--
import my_globals
...
x.show(my_globals.a)
--
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces, scoping and variables

2010-08-02 Thread Ethan Furman

Chris Hare wrote:

I am having a problem getting around this variable namespace thing.

Consider these code bits

File a.py
from Tkinter import *
import a1

def doAgain():
x = a1.Net()
x.show("Again!")

root = Tk()
root.title("test")
f = Frame(root,bg="Yellow")
l = Button(root,text="window 1",command=doAgain)
f.grid()
l.grid()
a = 5
x = a1.Net()
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

File a1.py
from Tkinter import *

class Net:
def __init__(self):
self.window = Toplevel()
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
button = Button(self.window, text="Again")
button.bind("", self.Again)
button2 = Button(self.window, text="Dismiss")
button2.bind("", self.hide)
button.grid()
button2.grid()
def Again(self,event):
x = Net()
x.show(a)
def hide(self,event):
self.window.destroy()


When I run a.py, it imports a1.py and click on the Again button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File "/Volumes/Development/py/a1.py", line 17, in Again
x.show(a)
NameError: global name 'a' is not defined

I believe this is the expected behavior.  so my question is this -- how do I 
tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
to pass it as part of the function call, or what?  using

global a

in a1.py doesn't change anything.


The global keyword does not make a variable global.  It tells the 
interpreter that the variable in question can be find in the module 
scope, not the function/method scope.  In other words, the variable is 
global to the module, but not to the whole program.


What you'll need to do is pass a into Net when you instanciate it, like 
so (untested):


  def doAgain():
  x = a1.Net(a)
  x.show("Again!")

and in Net:

class Net:
def __init__(self, some_number):
self.some_number = some_number
self.window = Toplevel()
.
.
.
def Again(self,event):
x = Net(self.some_number)
x.show()

Keep in mind, though, that if you change a in a.py after you've 
instanciated Net, your Net instance will not see the change.  For the 
change to show up, a would need to be mutable, and you would have to 
mutate it.  The other option is to change the Net instance's some_number 
directly (i.e. x.some_number = 9).


Hope this helps.

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


Re: namespaces, scoping and variables

2010-08-02 Thread Chris Hare
Thanks to everyone for answering my question.  I think its clear now.  I'll 
just go the "stuff 'em in a module and import that" route.

Chris

On Aug 2, 2010, at 3:03 PM, MRAB wrote:

> Chris Hare wrote:
>> I am having a problem getting around this variable namespace thing.
>> Consider these code bits
>> File a.py
>> from Tkinter import *
>> import a1
>> def doAgain():
>>  x = a1.Net()
>>  x.show("Again!")
>> root = Tk()
>> root.title("test")
>> f = Frame(root,bg="Yellow")
>> l = Button(root,text="window 1",command=doAgain)
>> f.grid()
>> l.grid()
>> a = 5
>> x = a1.Net()
>> x.show("window 2")
>> if __name__ == "__main__":
>>  root.mainloop()
>> File a1.py
>> from Tkinter import *
>> class Net:
>>  def __init__(self):
>>  self.window = Toplevel()
>>  def show(self,t):   
>>  self.l = Label(self.window,text=t)
>>  self.l.grid()
>>button = Button(self.window, text="Again")
>>  button.bind("", self.Again)
>>button2 = Button(self.window, text="Dismiss")
>>  button2.bind("", self.hide)
>>  button.grid()
>>  button2.grid()
>>  def Again(self,event):
>>  x = Net()
>>  x.show(a)
>>  def hide(self,event):
>>  self.window.destroy()
>> When I run a.py, it imports a1.py and click on the Again button, I get the 
>> error
>> Exception in Tkinter callback
>> Traceback (most recent call last):
>>  File 
>> "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
>>  line 1410, in __call__
>>return self.func(*args)
>>  File "/Volumes/Development/py/a1.py", line 17, in Again
>>x.show(a)
>> NameError: global name 'a' is not defined
>> I believe this is the expected behavior.  so my question is this -- how do I 
>> tell the code in a1.py about the variable a, which exists in a.py?  Do I 
>> have to pass it as part of the function call, or what?  using
>> global a
>> in a1.py doesn't change anything.
>> since I am using SQLite for the disk database, I was thinking I could keep 
>> all the "global" variables in an in memory database and just access them 
>> when I need to, but other ideas are welcome.
> Why in a database? If you need the modules to share it then you could
> put it in a shared module and refer to it there:
> 
> File a.py
> -
> import my_globals
> ...
> my_globals.a = 5
> 
> 
> File a1.py
> --
> import my_globals
> ...
>   x.show(my_globals.a)
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Trying to set a cookie within a python script

2010-08-02 Thread Νίκος
Hello, any ideas?!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how best to clear objects from a frame

2010-08-02 Thread Chris Hare

On Aug 1, 2010, at 10:13 PM, rantingrick wrote:

> On Aug 1, 7:12 pm, Chris Hare  wrote:
>> Here is the situation:
>> 
>> I have a window with a bunch of widgets in it.  I want to clear the objects 
>> in a given frame and recreate them to update them.  
> 
> You need to check out the "w.update" and "w.update_idletasks" methods
> available on all Tkinter widgets. Just FYI: to remove a widget from
> view without destroying it use "w.pack_forget" or "w.grid_forget".
> However if you are simply trying to refresh a widget use one of the
> update methods.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I will have a look at those.  Consider a frame with a label and a button.  How 
do I address the label to change it from another function in the class?  

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


Re: namespaces, scoping and variables

2010-08-02 Thread rantingrick
On Aug 2, 3:12 pm, Chris Hare  wrote:
> Thanks to everyone for answering my question.  I think its clear now.  I'll 
> just go the "stuff 'em in a module and import that" route.

Chris, first of all i want you to know that this message is not meant
to offend but it may offend you -- hopefully your a rational person
and can deal with criticism.

This code is horrible. What are you trying to do exactly? Is this
purely academic or are you actually using this code for a real
purpose? The "Net" class looks like a dialog. Are you wishing to
create a dialog? If so, then you would be better off subclassing
tkSimpleDialog.Dialog instead of rolling your own. Please explain what
you are trying to do from a users perspective so we can properly guide
you.

Also you should use 4 space indention and never use tabs. This is the
accepted way. Although Python does allow freedom i would suggest that
coding in a uniformly accepted manner is more productive for the
entire community. Google "Python Style Guide" for more info.

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


Re: Trying to set a cookie within a python script

2010-08-02 Thread Thomas Jollans
On 08/02/2010 04:20 AM, Νίκος wrote:
> Also my greek print appear in funny encoding although i do use # -*-
> coding: utf-8 -*-

That's because you never told the web browser which encoding you're using.

Content-Type: text/html; charset=UTF-8
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to set a cookie within a python script

2010-08-02 Thread Thomas Jollans
On 08/02/2010 10:13 PM, Νίκος wrote:
> Hello, any ideas?!

That's no way to treat a friendly volunteer mailing list like this one!


On 08/02/2010 02:32 PM, Νίκος wrote:
> As for the encoding Notepad++, which is what i use for an editor say
> its UTF-8 without BOM.
> 
> Isn't this what i'm supposed to use?
> 
> My Python scripts only containes english and greek letters, so i
> though usign UTF-8 is the way to go. No?! Please if you explain to me
> in greater detail!

As I said, you have to tell the browser what you're up to.

Also, I just checked the link (shame on me), and you're not using UTF-8
at all. You're using some weird Windows-xyz or ISO-8859-xyz Greek
codepage from the previous millennium. (which obviously my browser
didn't know, it thought you were using ISO-8859-1, because that's what
my browser does, which you weren't)


So: tripple-check that

 * your file is 
 * Python knows that
 * the web browser knows that
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: let optionparse.Optionparser ignore unknown command line switches.

2010-08-02 Thread News123
On 08/01/2010 07:53 PM, Jon Clements wrote:
> On 1 Aug, 16:43, News123  wrote:
>> On 08/01/2010 05:34 PM, Steven W. Orr wrote:
>>
>>
>>
>>> On 08/01/10 07:27, quoth News123:
 On 08/01/2010 01:08 PM, News123 wrote:
> I wondered, whether there's a simple/standard way to let
> the Optionparser just ignore unknown command line switches.
>>
 In order to  illustrate, what I try to achieve:
>>
 import optparse
 parser = optparse.OptionParser()
 parser.add_option("-t","--test",dest="test",action="store_true")
 argv=["tst.py","-t","--ignoreme_and_dont_fail"]
 try:
 (options,args)=parser.parse_args(argv)
 except:
 # due to --ignoreme_and_dont_fail
 # I will end up here and neither options nor
 # args will be populated
 print "parser error:"
 # However I would love to be able to see here
 # that options.test is true despite the
 # error, that occurred afterwards
 print "T",options.test
>>
>> in my case one imported module should parse some of the options (but
>> only the one it understands) already during import.
>> the main program will have to parse the same options again.
> 
> Take it up a level.
> 
> Dedicate a module (called app_configuration) or something to do the
> option parsing -- everything the application can support is listed
> there... It's a bad idea to ignore invalid options...
Well the main application would abort the program. I'ts jsut one module
which would like to pre-fetch some options.
> 
> When that's imported it runs the parsing for sys.argv whatever... and
> you guarantee a variable called app_settings (or whatever) is present
> in that module.
> 
> Any module that needs the settings, just imports app_configuration and
> tries to take what it understands...
> 
> Would that work for you?
> 

It's not really what I'm looking for, though it might be what I'll end
up doing.

currently I have several apps all importing one module, but all parsing
different options.

There's one common option and I'd like to have one module behaving
differently depending on this option.

My idea was to just change this one module and leave everything else
unmodified.

Another not so nice solution, which could be a very quick and dirty hack
(to be removed lateron) would be to just add to this one module


if "--myoption" in sys.argv:
dosomething

but I'd have prefered a real Optionparser (ignoring unknown options)
I could even make sure, that the unknown options follow the common options.







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


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread John Nagle

On 8/2/2010 12:52 PM, Thomas Jollans wrote:

On 08/02/2010 09:41 PM, John Nagle wrote:

On 8/2/2010 11:02 AM, MRAB wrote:

John Nagle wrote:

The regular expression "split" behaves slightly differently than
string split:

occurrences of pattern", which is not too helpful.



It's the plain str.split() which is unusual in that:

1. it splits on sequences of whitespace instead of one per occurrence;


That can be emulated with the obvious regular expression:

 re.compile(r'\W+')


2. it discards leading and trailing sequences of whitespace.


But that can't, or at least I can't figure out how to do it.


[ s in rexp.split(long_s) if s ]


   Of course I can discard the blank strings afterward, but
is there some way to do it in the "split" operation?  If
not, then the default case for "split()" is too non-standard.

   (Also, "if s" won't work;   if s != ''   might)

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


checking that process binds a port, fuser functionality

2010-08-02 Thread Zdenek Maxa
Hello,

I need to start a process (using subprocess.Popen()) and wait until the
new process either fails or successfully binds a specified port. The
fuser command seems to be indented exactly for this purpose. Could
anyone please provided a hint to a handy Python library to do this or
would the advice be to parse fuser command output?

This needs to happen on Linux and Python 2.4.

Thanks a lot in advance.

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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 17:53, donn wrote:

On 02/08/2010 17:35, Mark Lawrence wrote:

aka the colon. :)

Ha. This is a case of the colon being the appendix!

\d

 Is there a better newsgroup in the world than c.l.py? No!

Kindest regards.

Mark Lawrence.

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


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread Benjamin Kaplan
On Mon, Aug 2, 2010 at 2:22 PM, John Nagle  wrote:

> On 8/2/2010 12:52 PM, Thomas Jollans wrote:
>
>> On 08/02/2010 09:41 PM, John Nagle wrote:
>>
>>> On 8/2/2010 11:02 AM, MRAB wrote:
>>>
 John Nagle wrote:

> The regular expression "split" behaves slightly differently than
> string split:
>
 occurrences of pattern", which is not too helpful.
>>>

> It's the plain str.split() which is unusual in that:

 1. it splits on sequences of whitespace instead of one per occurrence;

>>>
>>>That can be emulated with the obvious regular expression:
>>>
>>> re.compile(r'\W+')
>>>
>>> 2. it discards leading and trailing sequences of whitespace.

>>>
>>>But that can't, or at least I can't figure out how to do it.
>>>
>>
>> [ s in rexp.split(long_s) if s ]
>>
>
>   Of course I can discard the blank strings afterward, but
> is there some way to do it in the "split" operation?  If
> not, then the default case for "split()" is too non-standard.
>
>   (Also, "if s" won't work;   if s != ''   might)
>
>John Nagle
> --
>


What makes it non-standard? The fact that it's not a 1-line
regex? The default case for str.split is designed to handle the most common
case: you want to break a string into words, where a word is defined as a
sequence of non-whitespace characters.


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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 19:14, Benjamin Kaplan wrote:

On Mon, Aug 2, 2010 at 9:51 AM, David Robinow  wrote:


On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan
  wrote:

...
So these are the packages needed just to run Python in Ubuntu. It doesn't
include the packages required for the kernel, the desktop environment,

the

window manager, the terminal, and whatever else you want running. In my
fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
close to 1500 packages installed.

  As an admittedly stupid comparison, I have 1579 DLLs in my
\windows\system32 directory.
Some number of these have been upgraded by Windows Update. This is XP
Service Pack 3.
I'm not sure if this means that Windows is better because it has more
packages or that it is worse because it's got too many. :)
  --



A package is usually more than one file.
http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist



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





This is all very well, but what is the unladen airspeed velocity of a 
swallow in flight?  Answers on a postcard please, given that I expect 
both direction and speed!


Kindest regards.

Mark Lawrence.

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 00:08, candide wrote:

Python is an object oriented langage (OOL). The Python main
implementation is written in pure and "old" C90. Is it for historical
reasons?

C is not an OOL and C++ strongly is. I wonder if it wouldn't be more
suitable to implement an OOL with another one.

Has it ever been planned to rewrite in C++ the historical implementation
(of course in an object oriented design) ?


I can't understand why any serious programmer mentions C++. As soon as I 
read it, I have to rush either to the kitchen to find a bowl to throw up 
in, or head for the toilet so I can talk to the great white telephone.


Kindest regards.

Mark Lawrence.

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


Re: how best to clear objects from a frame

2010-08-02 Thread Mark Lawrence

On 02/08/2010 04:13, rantingrick wrote:

On Aug 1, 7:12 pm, Chris Hare  wrote:

Here is the situation:

I have a window with a bunch of widgets in it.  I want to clear the objects in 
a given frame and recreate them to update them.


You need to check out the "w.update" and "w.update_idletasks" methods
available on all Tkinter widgets. Just FYI: to remove a widget from
view without destroying it use "w.pack_forget" or "w.grid_forget".
However if you are simply trying to refresh a widget use one of the
update methods.


I don't understand the technical content of this thread, but I'm very 
pleased to see rantingrick being positive, well done!!! :) I know that 
we've crossed swords in the past but believe that bygones should be 
bygones.  Can we call it quits and help to take Python forward?


Kindest regards.

Mark Lawrence.

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Peter
On Aug 3, 7:42 am, Mark Lawrence  wrote:
> On 02/08/2010 00:08, candide wrote:

>
> I can't understand why any serious programmer mentions C++. As soon as I
> read it, I have to rush either to the kitchen to find a bowl to throw up
> in, or head for the toilet so I can talk to the great white telephone.
>
> Kindest regards.
>
> Mark Lawrence.

With you there Mark - IMO C++ is an abortion that should never have
seen the light of day. The idea of experimenting with creating an OO
language by extending C wasn't such a bad idea for a "play thing" (by
Stroustrop) but the fact that it somehow escaped from the Lab and
people picked it up and ran with it on a commercial basis is just
plain wrong!

Personally I liken it to one of those genetically engineered diseases
they play around with in biological warfare labs - and unfortunately
this one escaped! It has probably set the computing industry back
untold years in terms of advancement...

Unfortunately I am forced to use it in my day to day life, but at the
end of every day I go home and use a purgative to get it out of my
system. But there are many deluded youngsters out there who just don't
seem to know any better, but then the signs of the breakdown of
society surround us on a daily basis and I guess C++ is just another
signpost on the way...

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Michael Torrie
On 08/02/2010 03:42 PM, Mark Lawrence wrote:
> I can't understand why any serious programmer mentions C++. As soon as I 
> read it, I have to rush either to the kitchen to find a bowl to throw up 
> in, or head for the toilet so I can talk to the great white telephone.

Sometimes, C++ is just the right tool for the job, despite all its
warts.  For example, programming GTK apps with GTKmm in C++ is way more
pleasant than using C (but nowhere as pleasant as Python).  C++'s object
semantics (guaranteed destruction, scoping, etc) can sometimes work very
well when you need the speed of a compiled language, but don't want to
be quite as low-level as C.

In this case, C++ is certainly not a better tool for the job than C.
But plenty of serious programmers know how to leverage C++ and do so
quite successfully.  Just because C++ makes you ill in no way proves
that C++ is unfit for certain purposes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread Thomas Jollans
On 08/02/2010 11:22 PM, John Nagle wrote:
>> [ s in rexp.split(long_s) if s ]
> 
>Of course I can discard the blank strings afterward, but
> is there some way to do it in the "split" operation?  If
> not, then the default case for "split()" is too non-standard.
> 
>(Also, "if s" won't work;   if s != ''   might)

Of course it will work. Empty sequences are considered false in Python.

Python 3.1.2 (release31-maint, Jul  8 2010, 09:18:08)
[GCC 4.4.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> sprexp = re.compile(r'\s+')
>>> [s for s in sprexp.split('   spaces   every where !  ') if s]
['spaces', 'every', 'where', '!']
>>> list(filter(bool, sprexp.split('   more  spaces \r\n\t\t  ')))
['more', 'spaces']
>>>

(of course, the list comprehension I posted earlier was missing a couple
of words, which was very careless of me)
-- 
http://mail.python.org/mailman/listinfo/python-list


Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning

2010-08-02 Thread ben owen

Hi everyone, I'm new to this and was needing help with trying to learn/work 
with Python 2.7 on my computer. I'm running Windows 7 and trying to learn 
python programming from an older book from 1999 by Mark Lutz and David Ascher 
my boss gave me, and for some reason none of my script/modules for the 
exercises are working on my comp. Mostly they give either a syntax error on the 
python command line or something about the file/module not being found on the 
windows command line. Also, does anyone where i can find/get something similar 
to the book for my own?

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


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 2 Aug, 01:08, candide  wrote:

> Has it ever been planned to rewrite in C++ the historical implementation
> (of course in an object oriented design) ?

OO programming is possible in C.  Just take a look at GNOME and GTK.

Perl is written in C++. That is not enough to make me want to use
it ;)

To be honest, C++ can be a great tool. But very few know how to use it
correctly. C++ textbooks are also written by people who don't
understand the language, and teach bad habits. The typical examples
revealing incompetence are use of new[] instead of std::vector, and
dynamic resourse allocation outside contructors.

C++ compilers used to be bloatware generators; C++ compilers of 2010
are not comparable to those of 1990. C++ is also a PITA for
portability. It is not sufficient for Python to only build with
Microsoft Visual Studio.








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


Re: Why is python not written in C++ ?

2010-08-02 Thread Paul Rubin
Michael Torrie  writes:
> Sometimes, C++ is just the right tool for the job, despite all its
> warts  C++'s object semantics (guaranteed destruction, scoping,
> etc) can sometimes work very well when you need the speed of a
> compiled language, but don't want to be quite as low-level as C.
> 
> In this case, C++ is certainly not a better tool for the job than C.

The stuff C++ adds to C is a mix of good and bad, and it's reasonably
possible to use just the good stuff and ignore the bad.  At that point
you've got a pure improvement over C, although a lot of C's shortcomings
can't be papered over and still remain.

Certain folks in the functional-programming community consider OO to be
a 1980's or 1990's approach that didn't work out, and that what it was
really trying to supply was polymorphism.  C++ programs these days
apparently tend to use template-based generics rather than objects and
inheritance for that purpose.  

I've never programmed in Ada but I'm intrigued by these articles:

  http://adahome.com/Ammo/cpp2ada.html 
  http://www.adaic.org/whyada/ada-vs-c/cada_art.html

I have the impression that Ada has an undeservedly bad rap because of
its early implementations and its origins in military bureaucracy.  I'd
certainly consider it as an alternative to C or C++ if I had to write a
big program in a traditional procedural language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 2 Aug, 05:04, Tomasz Rola  wrote:

> And one should not forget about performance. C++ was for a long time
> behind C, and even now some parts (like iostreams) should be avoided in
> fast code.

For fast I/O one must use platform specific APIs, such as Windows' i/o
completion ports and memory mapping.

iostreams in C++ and stdio in C are ok for less demanding tasks.


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


Re: Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning

2010-08-02 Thread James Mills
On Tue, Aug 3, 2010 at 8:07 AM, ben owen  wrote:
> Hi everyone, I'm new to this and was needing help with trying to learn/work
> with Python 2.7 on my computer. I'm running Windows 7 and trying to learn
> python programming from an older book from 1999 by Mark Lutz and David
> Ascher my boss gave me, and for some reason none of my script/modules for
> the exercises are working on my comp. Mostly they give either a syntax error
> on the python command line or something about the file/module not being
> found on the windows command line. Also, does anyone where i can find/get
> something similar to the book for my own?

Start with the mighty fine Python tutorial on the
Python Documentation website (1)

cheers
James

1. http://docs.python.org/

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 3 Aug, 00:27, Paul Rubin  wrote:

> Certain folks in the functional-programming community consider OO to be
> a 1980's or 1990's approach that didn't work out, and that what it was
> really trying to supply was polymorphism.  C++ programs these days
> apparently tend to use template-based generics rather than objects and
> inheritance for that purpose.  

It avoids virtual function calls at the expense of unreable code and
errors that are nearly impossible to trace. It seems many thinks this
is a good idea because Microsoft did this with ATL and WTL. There are
also those who thinks template metaprogramming is a good idea. But who
uses a C++ compiler to dumb to unroll a for loop? In my experience,
trying to outsmart a modern compiler is almost always a bad idea.

> I have the impression that Ada has an undeservedly bad rap because of
> its early implementations and its origins in military bureaucracy.  

It is annyingly verbose, reminds me of Pascal (I hate the looks of
it), and is rumoured to produce slow bloatware. And don't forget
Ariane 5 ;)


> I'd
> certainly consider it as an alternative to C or C++ if I had to write a
> big program in a traditional procedural language.

I still prefer Fortran 95 :-)







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


Re: Why is python not written in C++ ?

2010-08-02 Thread Aahz
In article ,
Peter   wrote:
>On Aug 3, 7:42=A0am, Mark Lawrence  wrote:
>> On 02/08/2010 00:08, candide wrote:
>>
>> I can't understand why any serious programmer mentions C++. As soon as I
>> read it, I have to rush either to the kitchen to find a bowl to throw up
>> in, or head for the toilet so I can talk to the great white telephone.
>
>With you there Mark - IMO C++ is an abortion that should never have
>seen the light of day. The idea of experimenting with creating an OO
>language by extending C wasn't such a bad idea for a "play thing" (by
>Stroustrop) but the fact that it somehow escaped from the Lab and
>people picked it up and ran with it on a commercial basis is just
>plain wrong!

http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Normal is what cuts off your sixth finger and your tail..."  --Siobhan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Martin Gregorie
On Mon, 02 Aug 2010 15:54:52 -0700, sturlamolden wrote:

> On 3 Aug, 00:27, Paul Rubin  wrote:
> 
>> Certain folks in the functional-programming community consider OO to be
>> a 1980's or 1990's approach that didn't work out, and that what it was
>> really trying to supply was polymorphism.  C++ programs these days
>> apparently tend to use template-based generics rather than objects and
>> inheritance for that purpose.
> 
> It avoids virtual function calls at the expense of unreable code and
> errors that are nearly impossible to trace. It seems many thinks this is
> a good idea because Microsoft did this with ATL and WTL. There are also
> those who thinks template metaprogramming is a good idea. But who uses a
> C++ compiler to dumb to unroll a for loop? In my experience, trying to
> outsmart a modern compiler is almost always a bad idea.
> 
>> I have the impression that Ada has an undeservedly bad rap because of
>> its early implementations and its origins in military bureaucracy.
> 
> It is annyingly verbose, reminds me of Pascal (I hate the looks of it),
> and is rumoured to produce slow bloatware. 

> And don't forget Ariane 5 ;)
> 
This had nothing to do with Ada per se and everything to do with 
shortcuts:

- re-use of an Ariane 4 component without changing its parameters
  to match the Ariane 5 flight profile
- not removing Ariane 4-only code intended to handle launch holds
  and not used at all in Ariane 5
- a programming fault that allowed an exception code to be sent
  to another component as if it was valid data.

Inadequate testing allowed all these to be flown without finding the 
errors.

Bottom line: All this would still have happened regardless of the 
programming language used. However, don't just listen to me: read the 
final report on Ariane 501 here: 

http://www.di.unito.it/~damiani/ariane5rep.html


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 3 Aug, 01:14, Martin Gregorie 
wrote:

> Bottom line: All this would still have happened regardless of the
> programming language used.

I am quite sure C and Fortran makes it unlikely for an unhandled
exception to trigger the autodestruct sequence. But it's nice to know
when flying that modern avionics is programmed in a language where
this is possible.

;)

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Mark Lawrence

On 03/08/2010 00:03, Aahz wrote:

In article,
Peter  wrote:

On Aug 3, 7:42=A0am, Mark Lawrence  wrote:

On 02/08/2010 00:08, candide wrote:

I can't understand why any serious programmer mentions C++. As soon as I
read it, I have to rush either to the kitchen to find a bowl to throw up
in, or head for the toilet so I can talk to the great white telephone.


With you there Mark - IMO C++ is an abortion that should never have
seen the light of day. The idea of experimenting with creating an OO
language by extending C wasn't such a bad idea for a "play thing" (by
Stroustrop) but the fact that it somehow escaped from the Lab and
people picked it up and ran with it on a commercial basis is just
plain wrong!


http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html


Haven't been able to read this properly as the stomach has been shaking 
too much to control the mouse and/or arrow keys/page up/down etc.  Hum, 
marks out of 10, 1.649072354865927**trillions.  For the cryptographers, 
is this a decent random number?


Kindest regards.

Mark Lawrence

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Mark Lawrence

On 03/08/2010 00:14, Martin Gregorie wrote:

On Mon, 02 Aug 2010 15:54:52 -0700, sturlamolden wrote:


On 3 Aug, 00:27, Paul Rubin  wrote:


Certain folks in the functional-programming community consider OO to be
a 1980's or 1990's approach that didn't work out, and that what it was
really trying to supply was polymorphism.  C++ programs these days
apparently tend to use template-based generics rather than objects and
inheritance for that purpose.


It avoids virtual function calls at the expense of unreable code and
errors that are nearly impossible to trace. It seems many thinks this is
a good idea because Microsoft did this with ATL and WTL. There are also
those who thinks template metaprogramming is a good idea. But who uses a
C++ compiler to dumb to unroll a for loop? In my experience, trying to
outsmart a modern compiler is almost always a bad idea.


I have the impression that Ada has an undeservedly bad rap because of
its early implementations and its origins in military bureaucracy.


It is annyingly verbose, reminds me of Pascal (I hate the looks of it),
and is rumoured to produce slow bloatware.



And don't forget Ariane 5 ;)


This had nothing to do with Ada per se and everything to do with
shortcuts:

- re-use of an Ariane 4 component without changing its parameters
   to match the Ariane 5 flight profile
- not removing Ariane 4-only code intended to handle launch holds
   and not used at all in Ariane 5
- a programming fault that allowed an exception code to be sent
   to another component as if it was valid data.

Inadequate testing allowed all these to be flown without finding the
errors.

Bottom line: All this would still have happened regardless of the
programming language used. However, don't just listen to me: read the
final report on Ariane 501 here:

http://www.di.unito.it/~damiani/ariane5rep.html



A bug is a bug is a bug?

Except in my code.  Never written a bug in my life.  Cross my heart and 
hope to die.  Of course I'm lying. :)


Kindest regards.

Mark Lawrence.

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


Package management (was: Why is there no platform independent way of clearing a terminal?)

2010-08-02 Thread Ben Finney
Mark Lawrence  writes:

> How does any user or an admin cope with 500 packages?

Operating systems with good package management come with tools that help
the administrator do this job easily.

Also, operating systems with good package management encourage the
small-pieces-loosely-joined philosophy to apply to packages also: the
packages tend to be smaller and more focussed, and fit together in more
well-defined ways, than those on other OSen.

This isn't automatic, but the support of a good package management
system allows a robust policy to be implemented by the vendor for good
quality packages in the OS.

So “installing 500 packages” is not an unusual nor onerous thing to do
on such an OS. The job of making them all work well together is
delegated upstream, to one's distribution vendor. But the fact that
they're small pieces, loosely joined, means that if any one of them is
causing a problem, it's far more likely that a motivated administrator
can do something about it locally, rather than being at the mercy of the
vendor.

> Can Python help here, assume an eight hour working day?

Sadly, Python's package management is rather lacking by these standards.
The Distutils legacy assumption of “package recipient, system
administrator, and end user are all the same person”, among other design
decisions, makes it unusually difficult to have the necessary separation
of concerns between OS packaging, system administration, and end user.

There have been great strides in recent years to improve the Distutils
shortcomings (see the Distutils forum archives for the details), but the
changes are in part backward-incompatible, and it will be some time
before Python is on a par with, e.g., Perl in this area.

> So every working day you have 57.6 seconds to use each package.

Your mistaken assumption is that one would use these packages separate
from each other. That's like assuming that the limit of usefulness of
modules in a Python program is how much one can use each of them
separate from all the others.

In both cases, they're not used separately most of the time; they're
used in conjunction, and their distinction is more to enable the people
responsible for maintaining them to do so as distinct pieces when it
makes sense to do so, and as larger aggregate collections when that
makes sense.

OS packages are not only applications. They are any discrete, coherent
“piece” of an operating system; applications usually encompass one or
several packages, and most packages are not applications.

-- 
 \   “We must respect the other fellow's religion, but only in the |
  `\   sense and to the extent that we respect his theory that his |
_o__) wife is beautiful and his children smart.” —Henry L. Mencken |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread MRAB

Mark Lawrence wrote:

On 02/08/2010 19:14, Benjamin Kaplan wrote:

On Mon, Aug 2, 2010 at 9:51 AM, David Robinow  wrote:


On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan
  wrote:

...
So these are the packages needed just to run Python in Ubuntu. It 
doesn't

include the packages required for the kernel, the desktop environment,

the

window manager, the terminal, and whatever else you want running. In my
fairly clean Ubuntu VM (I use it almost exclusively for testing), I 
have

close to 1500 packages installed.

  As an admittedly stupid comparison, I have 1579 DLLs in my
\windows\system32 directory.
Some number of these have been upgraded by Windows Update. This is XP
Service Pack 3.
I'm not sure if this means that Windows is better because it has more
packages or that it is worse because it's got too many. :)
  --



A package is usually more than one file.
http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist 





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





This is all very well, but what is the unladen airspeed velocity of a 
swallow in flight?  Answers on a postcard please, given that I expect 
both direction and speed!



African or European? :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 3 Aug, 01:37, Mark Lawrence  wrote:

> A bug is a bug is a bug?

According to Grace Hopper, a bug might be a moth, in which case the
best debugger is a pair of forceps.
-- 
http://mail.python.org/mailman/listinfo/python-list


simple integer subclass

2010-08-02 Thread Andreas Pfrengle
I'm trying to define a subclass of int called int1. An int1-object
shall behave exactly like an int-object, with the only difference that
the displayed value shall be value + 1 (it will be used to display
array indices starting at 1 instead of 0). Right now I have:

class int1(int):
def __str__(self):
return int.__str__(self + 1)

However, if I calculate with int1 and int- (or other number) objects,
the result is always coerced to an int (or other number object), e.g:
a = int1(5)
b = 5
print a  # "6"
print a+b  #"10"

How can I tell int1 to be the "default integer object"? Do I need to
overload *every* mathematical operation method of int, or is there an
easier way?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Christian Heimes
Am 03.08.2010 01:03, schrieb Aahz:
> http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html

I don't understand why the URL contains the word "joke". Every word is
true. Hell yeah! :)

Christian

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Carey Tilden
On Mon, Aug 2, 2010 at 3:18 PM, sturlamolden  wrote:
>
> Perl is written in C++. That is not enough to make me want to use
> it ;)

I realize this was meant to be funny, but it's not true, and detracts
from the point you were trying to make.  Maybe skip the pointless jabs
at Perl and stick to things you know more about.
-- 
http://mail.python.org/mailman/listinfo/python-list


calling a class method from a menu in a different class

2010-08-02 Thread Chris Hare

What I am trying to do is call a class function from a menu, for example

displaySubMenu.add_radiobutton(label="Medium", 
variable=radarPanelSize, command=radarWidgets.refresh) 

class radarWidgets:
def __init__(self,root):
self.window = root
def refresh(self):
global radar
global refreshTimer
self.refreshTimer.cancel()
logging.debug("handlesRadarRefreshByTimer()")
#
# destroy the existing frame the radar is in
#
self.w.destroy()
self.lblLastUpdate.destroy()
self.btnRefresh.destroy()
#
# rebuild the radarWidgets
#
self.createImage()
self.refreshTimer = threading.Timer( 900, self.refresh)
self.refreshTimer.start()

This doesn't work because the instance of radarWidgets was defined in a 
different class ..

class mainDisplay:
def __init__(self,root):
self.window = root
def show(self): 
#
# Configure the base frame
# 
base=Frame(self.window,bg=backColor,width=1200, height=800)
base.grid()
frameRadar = Frame(base, bd=0, bg=backColor)
frameRadar.grid(row=2,column=1,sticky=N+E+S+W)
#
radar = radarWidgets(frameRadar)
radar.show()

so the actual instance is called "radar".  If I put the instance name in the 
menu item, I get an error that "radar" is unknown.  If I use 
RadarWidgets.refresh ins the command for the menu, I get the error:

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

Any ideas?

Thanks!



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


Re: Why is python not written in C++ ?

2010-08-02 Thread Peter
On Aug 3, 8:27 am, Paul Rubin  wrote:
...
>
> Certain folks in the functional-programming community consider OO to be
> a 1980's or 1990's approach that didn't work out, and that what it was
> really trying to supply was polymorphism.  C++ programs these days
> apparently tend to use template-based generics rather than objects and
> inheritance for that purpose.  
>
> I've never programmed in Ada but I'm intrigued by these articles:
>
>  http://adahome.com/Ammo/cpp2ada.html
>  http://www.adaic.org/whyada/ada-vs-c/cada_art.html
>
> I have the impression that Ada has an undeservedly bad rap because of
> its early implementations and its origins in military bureaucracy.  I'd
> certainly consider it as an alternative to C or C++ if I had to write a
> big program in a traditional procedural language.

I used to work for defence contractors - Ada (IMO :-)) is the very
best OO language for real-time and embedded systems. It scales
fantastically well to large, multi-platform jobs as well. If I had my
way we would use it where I work now (biomedical field) but that isn't
an option - too many folk are brought up on a steady diet of C/C++ and
therefore don't know any better, plus there is a dearth of Ada
compilers for the CPU's that we use here (all embedded work). I have
used fortran, C, C++, some Java, Ada (and Python :-)), if I had my
choice for the type of programming I do here at work, it would
definitely go to Ada by a country mile.

Having said that though, I won't replace Python with it on my desktop
for the type of stuff I do around the fringes of my job (test scripts
etc) and my personal programming :-)

But for anyone who wants to expand their horizons, learning Ada would
be an excellent choice (although like any learning activity, unless
you have a concrete goal in mind you will probably just waste your
time :-)). It is not an easy language to just pick up and run with
because the strong type-checking FORCES you to think about and design
your program very carefully from the very beginning - something that
many programmers find an abhorrence for :-) But I always used to tell
people - by the time I got a program to compile then I figured 99% of
the bugs were already discovered! Try that with C/C++ or almost any
other language you care to name :-)

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


simple (I hope!) problem

2010-08-02 Thread samwyse
I'm writing for the Google app engine and have stubbed my toe yet
again on a simple obstacle.  Non-trivial app engines programs require
the import of several modules that aren't normally in my PYTHONPATH.
I'd like to be able to test my code outside of the app engine
framework.  I've tried several solutions in the past that worked but
weren't particularly elegant or portable.  Now I've had a new idea.
Here's my latest attempt:

import os, re
if __name__ == '__main__':
pass
else
from google.appengine.ext import webapp
register = webapp.template.create_template_register()

This works great, except my code makes use of the resister object in
several places, like this:

register.filter(emptylines)

Fortunately, I don't need the functionality of the object, I just want
something that won't generate an error when I use it.  So, what is the
quickest way to to create such an object (replacing the 'pass' in my
first snippet).  My solution is this:

class C:
def filter(self, *args, **kwds):
pass
register = C()

but it seems like I should be able to do something "better", as
measured by lines of code, faking more than just a 'filter' method, or
both.  Any ideas?  Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple integer subclass

2010-08-02 Thread samwyse
On Aug 2, 6:52 pm, Andreas Pfrengle  wrote:
> I'm trying to define a subclass of int called int1. An int1-object
> shall behave exactly like an int-object, with the only difference that
> the displayed value shall be value + 1 (it will be used to display
> array indices starting at 1 instead of 0). Right now I have:
>
> class int1(int):
>     def __str__(self):
>         return int.__str__(self + 1)
>
> However, if I calculate with int1 and int- (or other number) objects,
> the result is always coerced to an int (or other number object), e.g:
> a = int1(5)
> b = 5
> print a      # "6"
> print a+b  #"10"
>
> How can I tell int1 to be the "default integer object"? Do I need to
> overload *every* mathematical operation method of int, or is there an
> easier way?

I had a similar problem a few years ago, and couldn't find a solution
then.  The thread from back then may shed some light on your problem.
http://groups.google.com/group/comp.lang.python/browse_thread/thread/10cfe2affc265ac/2ad03b121c1c6489
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Paul Rubin
sturlamolden  writes:
> It is annyingly verbose, reminds me of Pascal (I hate the looks of
> it), and is rumoured to produce slow bloatware. 

The earliest Ada compilers were terrible, but they are about like C
compilers now, so the output code is ok (see Alioth shootout for
example).  I agree about the verbosity but I don't think that's too big
a problem in the sorts of systems that need to be written in such
languages.

> And don't forget Ariane 5 ;)

I have looked into that a few times and I do wonder whether the language
or release process could have been of any help.  One possibility is
using something like SPARK to ensure the absence of overflow exceptions.
Another is automatic test generation something like

  http://www.stanford.edu/~engler/klee-osdi-2008.pdf 

but that approach was probably unknown at the time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Roy Smith
In article 
<0ed1fb16-87cb-4fb9-85b2-08d876445...@q22g2000yqm.googlegroups.com>,
 sturlamolden  wrote:

> The typical examples revealing incompetence are use of
> new[] instead of std::vector

To be fair, there were usable C++ compilers before there were usable STL 
implementations.  Thus, it should not be surprising to find older C++ 
code bases eschewing the use of STL.  That's not to say that this trend 
should be propagated in current educational material.

> and dynamic resourse allocation outside contructors.

This one I don't understand.  Yes, I get RAII, but surely there are 
valid reasons to allocate memory outside of constructors.  Containers 
which resize themselves (such as std::vector) are one obvious example.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >