Re: tokenize module after installation

2007-08-09 Thread Martin v. Löwis
> After installation my program that uses tokenize module,when I run
> myprogram.exe (vgsveki.exe):
> 
> AttributeError: 'module' object has no attribute 'untokenize'

Perhaps you use the 2.4 version of tokenize.py here, which did
not have untokenize.

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


how to get command output using python

2007-08-09 Thread Indu Shreenath
Hey,
  I want to get the output of DIR /AD /B to a variable using python.
  How to do this?
  Thanks,
  Indu

   
-
 Download prohibited? No problem. CHAT from any browser, without download.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to get output.

2007-08-09 Thread Indu Shreenath

Hey,
  I did write the following,
  but it does not work.
   
  import subprocess as sp
try:
   = sp.Popen("DIR . /AD /B", stdout=sp.PIPE)
result = p.communicate()[0]
print result   
 except:   
   print "error"
   
  This throws error.
  DIR . /AD /B will list out only directories in the current directory.
   
  Thanks,
  Indu
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: 
  indu_shreenath schrieb:
> Hey,
> I want to get the output of "DIR /AD /B" command to a varriable using 
> python. How can I do this?

Using the subprocess-module.


However, I'm not sure what DIR /AD /B does - but there are many 
functions in module os that might deliver what you want without invoking 
an external command.

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


   
-
 5, 50, 500, 5000 - Store unlimited mails in your inbox. Click here.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to get output.

2007-08-09 Thread Indu Shreenath
Hey,
   
  I did write the following:
  but it does not work.
   
  import subprocess as sp
try:
   = sp.Popen("DIR . /AD /B", stdout=sp.PIPE)
result = p.communicate()[0]
print result   
 except:   
   print "error"
   
  This throws error.
  DIR . /AD /B will list out only directories in the current directory.
   
  Thanks,
  Indu


"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
  indu_shreenath schrieb:
> Hey,
> I want to get the output of "DIR /AD /B" command to a varriable using 
> python. How can I do this?

Using the subprocess-module.


However, I'm not sure what DIR /AD /B does - but there are many 
functions in module os that might deliver what you want without invoking 
an external command.

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


   
-
 Unlimited freedom, unlimited storage. Get it now-- 
http://mail.python.org/mailman/listinfo/python-list

Expect Telnet

2007-08-09 Thread Vinay Sagar Prakash
Hi all,

I am not sure how this works, but am composing my query here.

I am trying to expect the below snippet using telnetlib.

#
bash# install
blah blah blah
do you want to continue [y/n]? y
blah blah blah
 blah blah blah
blah blah blah
blah blah blah
Installation complete
bash#
##

For the above, i am doing
t.read_until("bash#")
t.write("install\n")
t.read_until("n]? ")
t.write("y\n")
t.read_until("bash#")
t.write('exit\n")

However, from the time i key 'y/n' till the install script exits, there is a
lot of data that is to be logged. I takes around 1 hour for the whole script
to exit.
Is there some way i can read whats happening behind the scenes until it hits
the read_until?

Thanks for the help
-- 
Vinay
-- 
http://mail.python.org/mailman/listinfo/python-list

Python mode

2007-08-09 Thread jay

I'm starting to learn how to use emacs (on Mac OS 10.4)
and I found that you can load something called python-mode.el which  
looks like it can help when writing Python
code in emacs.  I'm hoping it can color python syntax as well as  
indent it correctly, etc.

My problems are:

1.  Where should you place the 'python-mode.el' file?  I downloaded a  
folder from 'sourceforge.net' that contains 4
files (python-mode.el, doctest-mode.el, pycomplete.el and  
pycomplete.py).  I couldn't find any installation
instructions anywhere.  Do I use all 4 files or just the one and where  
should it go?  One web-site said the 'python-
mode.el' file needed to be compiled before being moved to whereever it  
needs to go.  How does one compile these things?


2.  All the web-sites I found about installing this said I should  
change my .emacs file which should be located in
my home folder.  I can't find a .emacs file anywhere on my machine.   
The only thing close to it is a .emacs.d folder
which contains an autosave folder.  Does anyone know where this .emacs  
file is located?  Or do I need to manually create one?


Thanks for looking at my questions.

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

Re: wxPython before MainLoop

2007-08-09 Thread 7stud
On Aug 8, 11:25 pm, "[david]" <[EMAIL PROTECTED]> wrote:
> I'd like to refresh the display before I start the main loop.
>
> I have code like this:
>
> app = App()
> app.Show()
> app.long_slow_init()
> app.MainLoop()
>
> The main frame partly loads at Show, but because the mainloop has not
> started yet, the display does not update until long_slow_init() finishes.
>
> Alternatively, I could code
>
> app = App()
> app.long_slow_init()
> app.Show()
> app.MainLoop()
>
> Which would give me a crisp Show, but there would be a long slow wait
> before the app showed any activity at all. I would need a splash screen.
>
> I'd rather not have a splash screen (and I don't know how anyway). I'd
> like to just make app.Show() finish correctly before running
> long_slow_init.
>
> Is there a wx internal method that I can use to give Windows the
> opportunity to finish painting the frame before I run long_slow_init()?
>
> Or is there a better idea?
>
> (david)

You can use a separate thread to execute long_slow_init():

--
import wx
import threading
import time

class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "My Window")

panel = wx.Panel(self, -1)
button = wx.Button(panel, -1, "click me, quick!", pos=(40,
40))
self.Bind(wx.EVT_BUTTON, self.onclick)

def onclick(self, event):
print "button clicked"

def receive_result(self, result):
print "Hey, I'm done with that long, slow initialization."
print "The result was:", result


class MyApp(wx.App):
def __init__(self):
wx.App.__init__(self, redirect=False)


def OnInit(self):
the_frame = MyFrame()
the_frame.Show()

t = MyThread(the_frame)
t.start()   #calls run() in t's class

return True


class MyThread(threading.Thread):
def __init__(self, a_frame):
threading.Thread.__init__(self)

self.frame_obj = a_frame

def run(self):
self.result = self.long_slow_init()

def long_slow_init(self):
print "starting long_slow_init()..."
time.sleep(6)
result = 20.5

#Send result to frame:
wx.CallAfter(self.frame_obj.receive_result, result)

app = MyApp()
app.MainLoop()



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


Re: how to get output.

2007-08-09 Thread indu_shreenath
Hey,

I did write the following:
but it does not work.

import subprocess as sp
try:
 = sp.Popen("DIR . /AD /B", stdout=sp.PIPE)
result = p.communicate()[0]
print result
 except:
 print "error"

This throws error.
DIR . /AD /B will list out only directories in the current directory.

Thanks,
Indu


On Aug 9, 11:46 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> indu_shreenath schrieb:
>
> > Hey,
> > I want to get the output of "DIR /AD /B" command to a varriable using
> > python. How can I do this?
>
> Using the subprocess-module.
>
> However, I'm not sure what DIR /AD /B does - but there are many
> functions in module os that might deliver what you want without invoking
> an external command.
>
> Diez


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


Re: how to get output.

2007-08-09 Thread Peter Otten
 [EMAIL PROTECTED] wrote:

> I corrected a typ below.
> 
> On Aug 9, 12:50 pm, [EMAIL PROTECTED] wrote:
>> Hey,
>>
>> I did write the following:
>> but it does not work.
>>
>> import subprocess as sp
>> try:
>> p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE)
>> result = p.communicate()[0]
>> print result
>>  except:
>>  print "error"
>>
>> This throws error.
>> DIR . /AD /B will list out only directories in the current directory.

try:
...
except:
print "error"

is a really bad idea because it hides any meaningful and therefore valuable
information about the error.

IIRC the "dir" command is internal to the dos shell and therefore has to be
called indirectly. The actual command is "cmd", not "dir":

[following snippet found at
http://www.python-forum.de/viewtopic.php?p=73048&sid=13808229538bd52de4ef75c32cf67856]

>>> import subprocess 
>>> args = ["cmd", "/C", "dir", "J:\\", "/O", "/AD", "/B"] 
>>> process = subprocess.Popen(args, stdout = subprocess.PIPE, stderr =
subprocess.STDOUT) 
>>> print process.stdout.read() 

If you just want a list of subdirectories, here's a better approach:

>>> def directories(folder):
... return os.walk(folder).next()[1]
>>> directories(".")
[snip list of subdirectories of cwd]

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


Re: how to get output.

2007-08-09 Thread indu_shreenath
I corrected a typ below.

On Aug 9, 12:50 pm, [EMAIL PROTECTED] wrote:
> Hey,
>
> I did write the following:
> but it does not work.
>
> import subprocess as sp
> try:
> p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE)
> result = p.communicate()[0]
> print result
>  except:
>  print "error"
>
> This throws error.
> DIR . /AD /B will list out only directories in the current directory.
>
> Thanks,
> Indu
>
> On Aug 9, 11:46 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>
>
>
> > indu_shreenath schrieb:
>
> > > Hey,
> > > I want to get the output of "DIR /AD /B" command to a varriable using
> > > python. How can I do this?
>
> > Using the subprocess-module.
>
> > However, I'm not sure what DIR /AD /B does - but there are many
> > functions in module os that might deliver what you want without invoking
> > an external command.
>
> > Diez- Hide quoted text -
>
> - Show quoted text -


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


Help with Dictionaries and Classes requested please.

2007-08-09 Thread special_dragonfly
Hello,
I'm new to this group, I've read through the subject of a lot of the group
but can't find anything relevant. Perhaps my question is too basic but I'm
still stuck.
Classes and Dictionaries.
If I have a dictionary, how do I instantiate many instances of a class per
dictionary key? Either at run-time or dynamically.
Can anyone help me please?
Thank you
Dominic


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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Peter Otten
special_dragonfly wrote:

> I'm new to this group, I've read through the subject of a lot of the group
> but can't find anything relevant. Perhaps my question is too basic but I'm
> still stuck.
> Classes and Dictionaries.
> If I have a dictionary, how do I instantiate many instances of a class per
> dictionary key? Either at run-time or dynamically.
> Can anyone help me please?

No, your question is too vague rather than too basic. 
What are you trying to do? Please give a concrete example and perhaps some
code that you already have.

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread special_dragonfly

"special_dragonfly" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello,
> I'm new to this group, I've read through the subject of a lot of the group
> but can't find anything relevant. Perhaps my question is too basic but I'm
> still stuck.
> Classes and Dictionaries.
> If I have a dictionary, how do I instantiate many instances of a class per
> dictionary key? Either at run-time or dynamically.
> Can anyone help me please?
> Thank you
> Dominic
>
>

I've managed to solve the problem, I really was just being a dunce. Here's 
how incase anyone is wondering:

class MyClass:
def __init__(self):
name=""
dict={}
dict[0]=[]
dict[0].append(MyClass())
dict[0][0].name="Hello"
print dict[0][0].name

I'm sorry if I've wasted anyones time, although if there's a better way of 
doing the above I'd still be interested to know.
Dominic


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


Stackless Integration

2007-08-09 Thread Justin T.
Hi,

I've been looking at stackless python a little bit, and it's awesome.
My question is, why hasn't it been integrated into the upstream python
tree? Does it cause problems with the current C-extensions? It seems
like if something is fully compatible and better, then it would be
adopted. However, it hasn't been in what appears to be 7 years of
existence, so I assume there's a reason.

Justin

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


pep 3116 behaviour on non-blocking reads

2007-08-09 Thread Antoon Pardon
In the RawIOBase class I read the following:

.read(n: int) -> bytes

Read up to n bytes from the object and return them. Fewer than n
bytes may be returned if the operating system call returns fewer
than n bytes. If 0 bytes are returned, this indicates end of file.
If the object is in non-blocking mode and no bytes are available,
the call returns None.


I would like the developers to reconsider and return 0 bytes when no
bytes are available and let None indicate end of file.

The reason is that this can lead to clearer code that will work
independant of the blocking mode of the stream.

Consider a consumer that just has to treat each byte. Then with
the current choice the code will look something like the following
(assuming pep 315 is implemented)


|do:
|buf = stream.read(nr)
|while buf != "":
|if buf is not None:
|for b in buf:
|treat(b)


If what the method returns follows my proposal, the code to do the same
would look something like the following:


|do:
|buf = stream.read(nr)
|while buf is not None:
|for b in buff:
|treat(b)


The advantage with my propsal is that in a lot of cases an empty buffer
can be treated just the same as a non-empty one and that is reflected
in the return values of my proposal.


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


Re: wxPython before MainLoop

2007-08-09 Thread 7stud
I reorganized my Thread class a little bit:


class MyThread(threading.Thread):
def __init__(self, a_frame):
threading.Thread.__init__(self)
self.frame_obj = a_frame

def run(self):
result = self.long_slow_init()

wx.CallAfter(self.frame_obj.receive_result, result)
#CallAfter() calls the specified function with the specified
argument
#when the next pause in execution occurs in this thread.

def long_slow_init(self):
print "starting long_slow_init()..."
time.sleep(6)
result = 20.5
return result
--

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


Launching App

2007-08-09 Thread Robert Rawlins - Think Blue
Hello Guys,

 

I'm looking for the best method to launch my python app when my Linux system
boots up. At the moment I just have an entry like this in my rc.local file:

 

CD /myfolder/anotherfolder

./myapp.py

 

Is this the best way to do this? Or is there a better way? I feel like a bit
of a dummy asking this question, I just wanted to ensure the best method.

 

Thanks guys,

 

Rob

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

Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Bjoern Schliessmann
special_dragonfly wrote:

> I've managed to solve the problem, I really was just being a
> dunce. Here's how incase anyone is wondering:
> 
> class MyClass:
> def __init__(self):
> name=""
> dict={}
> dict[0]=[]
> dict[0].append(MyClass())
> dict[0][0].name="Hello"
> print dict[0][0].name
> 
> I'm sorry if I've wasted anyones time, although if there's a
> better way of doing the above I'd still be interested to know.

Since we don't know what exactly of the above you require it's very
hard to give you useful tips. Do you need instance lists, grouped
by keys?

Regards,


Björn

-- 
BOFH excuse #152:

My pony-tail hit the on/off switch on the power strip.

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


Re: wxPython before MainLoop

2007-08-09 Thread Bjoern Schliessmann
[david] wrote:

> I'd like to refresh the display before I start the main loop.
> [...]
> I'd like to just make app.Show() finish correctly before running
> long_slow_init.

IMHO, this will bring no gain. If you see an inresponsive user
interface or not is quite meaningless.

> Or is there a better idea?

As suggested, a solution using threads is feasible.

Regards,


Björn

-- 
BOFH excuse #422:

Someone else stole your IP address, call the Internet detectives!

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


Re: Launching App

2007-08-09 Thread Michael Bentley


On Aug 9, 2007, at 3:01 AM, Robert Rawlins - Think Blue wrote:

I’m looking for the best method to launch my python app when my  
Linux system boots up. At the moment I just have an entry like this  
in my rc.local file:


CD /myfolder/anotherfolder

./myapp.py



Is this the best way to do this? Or is there a better way? I feel  
like a bit of a dummy asking this question, I just wanted to ensure  
the best method.
A better way is to use the SYSV init system: create a start/stop/ 
status script for your app in /etc/init.d (use existing scripts in  
that directory for examples of what you can do). On Debian, you can  
then use update-rc.d to create the appropriate symlinks.


hope this helps,
Michael

---
Debugging is twice as hard as writing the code in the first place.   
Therefore, if you write the code as cleverly as possible, you are, by  
definition, not smart enough to debug it. --Brian W. Kernighan



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

Re: Launching App

2007-08-09 Thread Michael Bentley


On Aug 9, 2007, at 3:01 AM, Robert Rawlins - Think Blue wrote:
I’m looking for the best method to launch my python app when my Linux  
system boots up. At the moment I just have an entry like this in my  
rc.local file:


CD /myfolder/anotherfolder

./myapp.py


Is this the best way to do this? Or is there a better way? I feel  
like a bit of a dummy asking this question, I just wanted to ensure  
the best method.


A better way is to use the SYSV init system: create a start/stop/ 
status script for your app in /etc/init.d (use existing scripts in  
that directory for examples of what you can do). On Debian, you can  
then use update-rc.d to create the appropriate symlinks.


hope this helps,
Michael

---
Debugging is twice as hard as writing the code in the first place.   
Therefore, if you write the code as cleverly as possible, you are, by  
definition, not smart enough to debug it. --Brian W. Kernighan


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

Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Bruno Desthuilliers
special_dragonfly a écrit :
(snip)
> I've managed to solve the problem, I really was just being a dunce. Here's 
> how incase anyone is wondering:
> 
> class MyClass:
> def __init__(self):
> name=""
> dict={}
> dict[0]=[]
> dict[0].append(MyClass())
> dict[0][0].name="Hello"
> print dict[0][0].name
> 
> I'm sorry if I've wasted anyones time, although if there's a better way of 
> doing the above I'd still be interested to know.

# unless you need pre 2.3.x compat, better to use newstyle classes
class MyClass(object):
   # use the initializer to initialize your instance
   def __init__(self, name=''):
 # the use of 'self' is mandatory, else you only have a local var
 self.name = name

# don't use builtin names as identifiers - unless you really want to
# shadow the builtins
d = {0:[MyClass('hello')}
d[0].append(MyClass('goodbye'))
d.setdefault(1, []).append(MyClass('Yo'))
print d

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread special_dragonfly

"Bruno Desthuilliers" <[EMAIL PROTECTED]> 
wrote in message news:[EMAIL PROTECTED]
> special_dragonfly a écrit :
> (snip)
>> I've managed to solve the problem, I really was just being a dunce. 
>> Here's how incase anyone is wondering:
>>
>> class MyClass:
>> def __init__(self):
>> name=""
>> dict={}
>> dict[0]=[]
>> dict[0].append(MyClass())
>> dict[0][0].name="Hello"
>> print dict[0][0].name
>>
>> I'm sorry if I've wasted anyones time, although if there's a better way 
>> of doing the above I'd still be interested to know.
>
> # unless you need pre 2.3.x compat, better to use newstyle classes
> class MyClass(object):
>   # use the initializer to initialize your instance
>   def __init__(self, name=''):
> # the use of 'self' is mandatory, else you only have a local var
> self.name = name
>
> # don't use builtin names as identifiers - unless you really want to
> # shadow the builtins
> d = {0:[MyClass('hello')}
> d[0].append(MyClass('goodbye'))
> d.setdefault(1, []).append(MyClass('Yo'))
> print d
>
> HTH

Hello
To answer first Bjoern:
I have a dictionary and a class. The dictionary needs to be filled with 
multiple instances of the class, with multiple instances per key. Currently 
a lot of the dictionaries that are going into the program are hard coded 
because they're just 1:1 mappings, in this case though it was a many:1 
mapping and so I got a little stumped. I couldn't hard coded the mappings, 
so I then needed to find a way of doing it dynamically. I'm now reading data 
from a file containing the data for the class, and am now able to put that 
data into a dictionary.

I'm quite new to programming large things, and previous experience has only 
been in C and C++, so I'm also trying to get an idea of good programming 
practises. Other people are going to need to use this program, I need it to 
be... correct... should someone need to alter it. So loads of documentation, 
and meaningful variable names, but it's also experience that I'm lacking. Is 
there a better way of doing such-and-such, or is it sensible to do it this 
way?

The code above does what I need, thank you Bruno. I can understand that my 
code is right there next to useless when trying to describe what I need to 
do.
Were I doing this in C, I would be creating a 2D array of structures, at 
least... I believe that's how it would look.

Thank you for your help, all of you.
Dominic 


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

Re: Stackless Integration

2007-08-09 Thread Jean-Paul Calderone
On Thu, 09 Aug 2007 09:00:27 -, "Justin T." <[EMAIL PROTECTED]> wrote:
>Hi,
>
>I've been looking at stackless python a little bit, and it's awesome.
>My question is, why hasn't it been integrated into the upstream python
>tree? Does it cause problems with the current C-extensions? It seems
>like if something is fully compatible and better, then it would be
>adopted. However, it hasn't been in what appears to be 7 years of
>existence, so I assume there's a reason.

It's not Pythonic.

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


Re: Stackless Integration

2007-08-09 Thread Michael Bentley

On Aug 9, 2007, at 4:48 AM, Jean-Paul Calderone wrote:

> On Thu, 09 Aug 2007 09:00:27 -, "Justin T."  
> <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I've been looking at stackless python a little bit, and it's awesome.
>> My question is, why hasn't it been integrated into the upstream  
>> python
>> tree? Does it cause problems with the current C-extensions? It seems
>> like if something is fully compatible and better, then it would be
>> adopted. However, it hasn't been in what appears to be 7 years of
>> existence, so I assume there's a reason.
>
> It's not Pythonic.

Can you be more specific?  It's a good question that I had thought  
about asking...

---
Debugging is twice as hard as writing the code in the first place.   
Therefore, if you write the code as cleverly as possible, you are, by  
definition, not smart enough to debug it. --Brian W. Kernighan


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


Re: mmm-mode, python-mode and doctest-mode?

2007-08-09 Thread Neal Becker
Edward Loper wrote:

>> Anyone testing on xemacs?  I tried it, and C-c C-c sent xemacs into an
>> infinite loop (apparantly).
> 
> It works fine for me in XEmacs 21.4 (patch 17) (i386-debian-linux,
> Mule).  If you could answer a few questions, it might help me track down
> the problem:
> 
> - What version of xemacs are you running?
> - What version of doctest-mode are you running (0.4 or 0.5)?
> - Are you using doctest-mode by itself, or in combination with another
>mode (via mmm-mode)?
> - Does pressing control-g (possibly repeatedly) cause it to become
>unstuck?
> - Does it always freeze when you hit C-c C-c?  Or does it depend on the
>contents of the buffer?  Does it freeze if you run it in an empty
>buffer?
> 
> You could try changing the value of doctest-python-command, to see if
> that helps -- "M-x customize-variable doctest-python-command".  Set it
> to the full path to a Python interpreter.
> 
> Thanks,
> -Edward

Value: "21.5  (beta28) \"fuki\" XEmacs Lucid"

I tested with 'hello.py', which is attached.

Load hello.py.  M-x mmm-mode.  Then move cursor to the highlighted test
region (the triple quoted doctest).  C-h k C-c C-c says 'doctest-execute'. 
good.  Now C-c C-c sends xemacs into an infinite loop.

hello.py---
import math

'''
>>> print 2 + 2
4
'''

def _test():
import doctest
doctest.testmod()

if __name__ == "__main__":
_test()


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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread special_dragonfly

"special_dragonfly" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> "Bruno Desthuilliers" <[EMAIL PROTECTED]> 
> wrote in message news:[EMAIL PROTECTED]
>> special_dragonfly a écrit :
>> (snip)
>>> I've managed to solve the problem, I really was just being a dunce. 
>>> Here's how incase anyone is wondering:
>>>
>>> class MyClass:
>>> def __init__(self):
>>> name=""
>>> dict={}
>>> dict[0]=[]
>>> dict[0].append(MyClass())
>>> dict[0][0].name="Hello"
>>> print dict[0][0].name
>>>
>>> I'm sorry if I've wasted anyones time, although if there's a better way 
>>> of doing the above I'd still be interested to know.
>>
>> # unless you need pre 2.3.x compat, better to use newstyle classes
>> class MyClass(object):
>>   # use the initializer to initialize your instance
>>   def __init__(self, name=''):
>> # the use of 'self' is mandatory, else you only have a local var
>> self.name = name
>>
>> # don't use builtin names as identifiers - unless you really want to
>> # shadow the builtins
>> d = {0:[MyClass('hello')}
>> d[0].append(MyClass('goodbye'))
>> d.setdefault(1, []).append(MyClass('Yo'))
>> print d
>>
>> HTH
>


Is there anyway for python to consider the values within a string when 
entering the data into a dictionary. I know that isn't very clear so here's 
an example:

class MyClass(object):
def __init__(self,name="",age=""):
self.name=name
self.age=age

data="Gary,50"
d={0:[MyClass(data)]}
data="Adam,25"
d[0].append(MyClass(data))

The data is coming from a text file working on a line by line basis. I've 
just tried and I'm just getting the full string in the first field. That 
seems logical, now I don't want it to though!

Dominic




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

Jython - variables are stored somehow

2007-08-09 Thread nmin
Hi,

I'm using Jython in combination with java.

I wrote a jython skript, which calls a function from another jython
module called library.py.

So, executing the function genData() in skript .py runs without
problem but if I execute the same function again, the data from the
first run is stored somehow and is added to the new data.

So, if you look at the result:
#1 in DatenTypen.py return an empty list each time the program runs.
Ok ... clear so far
#2 in library.py returns an empty list, when the program runs for the
first time ... but when the function is
called again, the list contains an element. Each time you call the
function again, one element is added!
Why??  out.abschnitte should be the same as printed in #1 or not?

Here is the code:

skript.py
==
from library import *

def genData():

 
out=DMS_sendFiles_ein_Abschnitt([["testdata1.test","testdata2.test","testdata3.test"]])

return out

library.py
===
from DatenTypen import AusgangsDatenDeichMonitor
from DatenTypen import DMS_Abschnitt
from DatenTypen import DMS_GeoData
from DatenTypen import DMS_GeoDataFile

def DMS_sendFiles_ein_Abschnitt(filelist):

out=AusgangsDatenDeichMonitor()

print "out.abschnitte: "+str(out.abschnitte) #2

abschnitt=DMS_Abschnitt()

for f in filelist:
data=DMS_GeoData()

for layer in f:

datalayer=DMS_GeoDataFile()

datalayer.dateiname=layer

datalayer.dateiinhalt="TEST"

data.layerFiles.append(datalayer)

abschnitt.bildSequenze.append(data)

out.abschnitte.append(abschnitt)

return out

DatenTypen.py
===

class AusgangsDatenDeichMonitor:

abschnitte=[]

def __init__(self):
abschnitte=[]
print "Abschnitt in DatenTypen: "+str(abschnitte) #1

class DMS_Abschnitt:

bildSequenze=[]

def __init__(self):
abschnittsNummer=0
bildSequenze=[]

class DMS_GeoData:

layerFiles=[]

def __init__(self):
layerFiles=[]

class DMS_GeoDataFile:

dateiinhalt="dateiinhalt"

dateiname="dateiname"

zipped=False

def __init__(self):
dateiinhalt="dateiinhalt"
dateiname="dateiname"
zipped=False

So, I read about deleting Instances with "del" ... but it does not
work at all.

Any Ideas?

Thanks  in advance

Simon

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Neil Cerutti
On 2007-08-09, special_dragonfly <[EMAIL PROTECTED]> wrote:
> Is there anyway for python to consider the values within a
> string when entering the data into a dictionary. I know that
> isn't very clear so here's an example:
>
> class MyClass(object):
> def __init__(self,name="",age=""):
> self.name=name
> self.age=age
>
> data="Gary,50"
> d={0:[MyClass(data)]}
> data="Adam,25"
> d[0].append(MyClass(data))
>
> The data is coming from a text file working on a line by line
> basis. I've just tried and I'm just getting the full string in
> the first field. That seems logical, now I don't want it to
> though!

That's what happens if you use 0 for the key every time. ;)

If you're trying to map between ages and lists of names, then
you'll want a little helper function to manage the lists for you.

multidict_add(mdict, key, value):
  if key in mdict:
mdict[key].append(value)
  else:
mdict[key] = [value]

d = {}
multidict_add(d, 50, "Gary")
multidict_add(d, 50, "Guido")
multidict_add(d, 25, "Adam")

Now you'll get a list of names for every age.

>>> d[50]
["Gary", "Guido"]

You can use the same function to build a mapping from names to
lists of ages.

d = {}
multidict_add(d, "Gary", 50)
multidict_add(d, "Gary", 23)
multidict_add(d, "Adam", 25)

>>> d["Gary"]
[50, 23]

-- 
Neil Cerutti
The choir invites any member of the congregation who enjoys sinning to join
the choir. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Steve Holden
special_dragonfly wrote:
> "special_dragonfly" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> "Bruno Desthuilliers" <[EMAIL PROTECTED]> 
>> wrote in message news:[EMAIL PROTECTED]
>>> special_dragonfly a écrit :
>>> (snip)
 I've managed to solve the problem, I really was just being a dunce. 
 Here's how incase anyone is wondering:

 class MyClass:
 def __init__(self):
 name=""
 dict={}
 dict[0]=[]
 dict[0].append(MyClass())
 dict[0][0].name="Hello"
 print dict[0][0].name

 I'm sorry if I've wasted anyones time, although if there's a better way 
 of doing the above I'd still be interested to know.
>>> # unless you need pre 2.3.x compat, better to use newstyle classes
>>> class MyClass(object):
>>>   # use the initializer to initialize your instance
>>>   def __init__(self, name=''):
>>> # the use of 'self' is mandatory, else you only have a local var
>>> self.name = name
>>>
>>> # don't use builtin names as identifiers - unless you really want to
>>> # shadow the builtins
>>> d = {0:[MyClass('hello')}
>>> d[0].append(MyClass('goodbye'))
>>> d.setdefault(1, []).append(MyClass('Yo'))
>>> print d
>>>
>>> HTH
> 
> 
> Is there anyway for python to consider the values within a string when 
> entering the data into a dictionary. I know that isn't very clear so here's 
> an example:
> 
> class MyClass(object):
> def __init__(self,name="",age=""):
> self.name=name
> self.age=age
> 
> data="Gary,50"
> d={0:[MyClass(data)]}
> data="Adam,25"
> d[0].append(MyClass(data))
> 
> The data is coming from a text file working on a line by line basis. I've 
> just tried and I'm just getting the full string in the first field. That 
> seems logical, now I don't want it to though!
> 
If you mean you would like to store a list of values then you could try 
something like

d = {0: MyClass(*data.split(",")}

to create the objects. The .split() method turns the string into a list 
of substrings, and the * unary operator turns that list into individual 
arguments passed to the __init__() method.

However, your recent question history indicates that you would do well 
to study the Python tutorial and other beginner material, as you will 
find many valuable hints as to Python best practices which will save you 
a lot of time.

Also there is the [EMAIL PROTECTED] list if you are having problems 
of a "beginner" nature, where you might get more practical help in your 
initial use of the language.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: (Re)announcing APL 2007

2007-08-09 Thread Steve
On Aug 6, 7:20 am, Paul Mansour <[EMAIL PROTECTED]> wrote:
> On Aug 5, 11:54 pm, Mike Kent <[EMAIL PROTECTED]> wrote:
>
> > APL 2007 conference on Array Programming
>
> >  co-located with OOPSLA 2007
>
> > Sponsor:  ACM SIGAPL
>
> > Where:Montreal
>
> > When: October 21 (tutorials)
> >October 22/23  (main conference program)
>
> APL2007 Roll Call: Is anyone going to this?
>
> I'm thinking about going, but I don't want to the only one to show up,
> as in San Diego.

I'm going.

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


check if regeular expression has results

2007-08-09 Thread shahargs
Hi,
I'm looking for the best way to check if regular expression return
true (it's mean - there is a match). for example, i want "if" that
check if this regular expression: .*born.*to.* has a match.

What's the way to do that simply?

Thanks a lot,
Shahar.

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


Re: Jython - variables are stored somehow

2007-08-09 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Hi,
> 
> I'm using Jython in combination with java.
> 
> I wrote a jython skript, which calls a function from another jython
> module called library.py.
> 
> So, executing the function genData() in skript .py runs without
> problem but if I execute the same function again, the data from the
> first run is stored somehow and is added to the new data.
> 
> So, if you look at the result:
> #1 in DatenTypen.py return an empty list each time the program runs.
> Ok ... clear so far
> #2 in library.py returns an empty list, when the program runs for the
> first time ... but when the function is
> called again, the list contains an element. Each time you call the
> function again, one element is added!
> Why??  out.abschnitte should be the same as printed in #1 or not?
> 
> Here is the code:
> 
> skript.py
> ==
> from library import *
> 
> def genData():
> 
>  
> out=DMS_sendFiles_ein_Abschnitt([["testdata1.test","testdata2.test","testdata3.test"]])
> 
> return out
> 
> library.py
> ===
> from DatenTypen import AusgangsDatenDeichMonitor
> from DatenTypen import DMS_Abschnitt
> from DatenTypen import DMS_GeoData
> from DatenTypen import DMS_GeoDataFile
> 
> def DMS_sendFiles_ein_Abschnitt(filelist):
> 
> out=AusgangsDatenDeichMonitor()
> 
> print "out.abschnitte: "+str(out.abschnitte) #2
> 
> abschnitt=DMS_Abschnitt()
> 
> for f in filelist:
> data=DMS_GeoData()
> 
> for layer in f:
> 
> datalayer=DMS_GeoDataFile()
> 
> datalayer.dateiname=layer
> 
> datalayer.dateiinhalt="TEST"
> 
> data.layerFiles.append(datalayer)
> 
> abschnitt.bildSequenze.append(data)
> 
> out.abschnitte.append(abschnitt)
> 
> return out
> 
> DatenTypen.py
> ===
> 
> class AusgangsDatenDeichMonitor:
> 
> abschnitte=[]
> 
> def __init__(self):
> abschnitte=[]
> print "Abschnitt in DatenTypen: "+str(abschnitte) #1
> 
> class DMS_Abschnitt:
> 
> bildSequenze=[]
> 
> def __init__(self):
> abschnittsNummer=0
> bildSequenze=[]
> 
> class DMS_GeoData:
> 
> layerFiles=[]
> 
> def __init__(self):
> layerFiles=[]
> 
> class DMS_GeoDataFile:
> 
> dateiinhalt="dateiinhalt"
> 
> dateiname="dateiname"
> 
> zipped=False
> 
> def __init__(self):
> dateiinhalt="dateiinhalt"
> dateiname="dateiname"
> zipped=False
> 
> So, I read about deleting Instances with "del" ... but it does not
> work at all.
> 
> Any Ideas?

I think you should read a python-tutorial. The above code looks as if 
you believe that

class Foo:
name = value

def __init__(self):
name = other_value

will create a class Foo, which then has instances with the property 
"name", and that this is bound to other_value. Python isn't doing that.


name in the above example (and e.g. abschnitte in yours) are 
class-attributes. That means that ALL instances of Foo share that name!!!

What you have to do is this:

class Foo:
def __init__(self, other_value):
   self.name = other_value


please note the self in front of name!



Or, within your example:

class AusgangsDatenDeichMonitor:

 def __init__(self):
 self.abschnitte=[]
 print "Abschnitt in DatenTypen: "+str(abschnitte) #1


There are a great many tutorials for python + OO out there - go read one 
(or several).

Regards,

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


Re: wxPython before MainLoop

2007-08-09 Thread kyosohma
On Aug 9, 12:25 am, "[david]" <[EMAIL PROTECTED]> wrote:
> I'd like to refresh the display before I start the main loop.
>
> I have code like this:
>
> app = App()
> app.Show()
> app.long_slow_init()
> app.MainLoop()
>
> The main frame partly loads at Show, but because the mainloop has not
> started yet, the display does not update until long_slow_init() finishes.
>
> Alternatively, I could code
>
> app = App()
> app.long_slow_init()
> app.Show()
> app.MainLoop()
>
> Which would give me a crisp Show, but there would be a long slow wait
> before the app showed any activity at all. I would need a splash screen.
>
> I'd rather not have a splash screen (and I don't know how anyway). I'd
> like to just make app.Show() finish correctly before running
> long_slow_init.
>
> Is there a wx internal method that I can use to give Windows the
> opportunity to finish painting the frame before I run long_slow_init()?
>
> Or is there a better idea?
>
> (david)

Yeah, I think 7stud's thread is the way to go. It's what I do with
long running tasks, see also:
http://wiki.wxpython.org/LongRunningTasks

If your screen doesn't load correctly, be sure to call the Layout()
method.

Mike

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


Re: check if regeular expression has results

2007-08-09 Thread Marc 'BlackJack' Rintsch
On Thu, 09 Aug 2007 05:58:22 -0700, shahargs wrote:

> I'm looking for the best way to check if regular expression return
> true (it's mean - there is a match). for example, i want "if" that
> check if this regular expression: .*born.*to.* has a match.
> 
> What's the way to do that simply?

Simply use an ``if`` on the result of the search or match.  If the regular
expression doesn't match `None` is returned, which is `False` in a boolean
context, otherwise a match object is returned, which is `True` in a
boolean context.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: check if regeular expression has results

2007-08-09 Thread Patrick Doyle
On 8/9/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm looking for the best way to check if regular expression return
> true (it's mean - there is a match). for example, i want "if" that
> check if this regular expression: .*born.*to.* has a match.
>
> What's the way to do that simply?
>
How about

import re
re.match(".*born.*to", "This is a test")
re.match(".*born.*to.*", "This test was born so that it worked too.")

(Try these at the python prompt)

The first call to 're.match()' returns 'None' which will fail an if
test.  The second one returns a match object, which evaluates to TRUE
in an if test.

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


Re: Jython - variables are stored somehow

2007-08-09 Thread Marc 'BlackJack' Rintsch
On Thu, 09 Aug 2007 05:30:00 -0700, nmin wrote:

> So, executing the function genData() in skript .py runs without
> problem but if I execute the same function again, the data from the
> first run is stored somehow and is added to the new data.
> 
> So, if you look at the result:
> #1 in DatenTypen.py return an empty list each time the program runs.
> Ok ... clear so far
> #2 in library.py returns an empty list, when the program runs for the
> first time ... but when the function is
> called again, the list contains an element. Each time you call the
> function again, one element is added!
> Why??  out.abschnitte should be the same as printed in #1 or not?

`out.abschnitte` is a *class* attribute so it is the same list on all
instances of that class.

> class AusgangsDatenDeichMonitor:
> 
> abschnitte=[]

Everything on this level belongs to the class, so `abschnitte` is a class
attribute and shared by all instances of `AusgangsDatenDeichMonitor`.

> def __init__(self):
> abschnitte=[]
> print "Abschnitt in DatenTypen: "+str(abschnitte) #1

Remove the class attribute and change the `__init__()` to:

def __init__(self):
self.abschnitte = list()
print "Abschnitt in DatenTypen: " + str(self.abschnitte)


> So, I read about deleting Instances with "del" ... but it does not
> work at all.

You can't delete objects with ``del``, just names or references to objects
in containers.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: check if regeular expression has results

2007-08-09 Thread Neil Cerutti
On 2007-08-09, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm looking for the best way to check if regular expression return
> true (it's mean - there is a match). for example, i want "if" that
> check if this regular expression: .*born.*to.* has a match.
>
> What's the way to do that simply?

Newgroups are a poor substitute for the docs. For one thing,
newsgroups sometimes contain cranky people who say, "RTFM!" The
docs will never do that.

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


Re: check if regeular expression has results

2007-08-09 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Hi,
> I'm looking for the best way to check if regular expression return
> true (it's mean - there is a match). for example, i want "if" that
> check if this regular expression: .*born.*to.* has a match.
> 
> What's the way to do that simply?
> 

A failed match returns None. A successful match returns a match object. 
So the easiest way to check for a successful match is

pat = re.compile(...)
 
m = pat.match(some_string)
if m:
 ... you got a match ...
else:
 ... you didn't ...

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


tests

2007-08-09 Thread nikolay marinov
Hi, everyone.Does anybody have an idea how can i test two xls files for 
equality with Python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Ben Finney
"special_dragonfly" <[EMAIL PROTECTED]> writes:

> I've managed to solve the problem, I really was just being a
> dunce.

Doubtful; but at this stage we can't tell, because we still don't know
what it is you're actually trying to *do*.

> Here's how incase anyone is wondering:
> 
> class MyClass:
> def __init__(self):
> name=""
> dict={}
> dict[0]=[]
> dict[0].append(MyClass())
> dict[0][0].name="Hello"
> print dict[0][0].name

It's not clear why you are using the value 0 for a dictionary key
here; nor why you're assigning an attribute to an object after
creating the object. Neither of them are errors, but without context
it's hard to know what advice to give.

-- 
 \  "When we call others dogmatic, what we really object to is |
  `\their holding dogmas that are different from our own."  -- |
_o__)   Charles Issawi |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tests

2007-08-09 Thread kyosohma
On Aug 9, 8:21 am, nikolay marinov <[EMAIL PROTECTED]>
wrote:
> Hi, everyone.Does anybody have an idea how can i test two xls files for
> equality with Python

You should be able to read chunks of each file in binary mode and do a
compare to check for equality. Some kind of loop should do the trick.

Mike

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Bruno Desthuilliers
Neil Cerutti a écrit :
> On 2007-08-09, special_dragonfly <[EMAIL PROTECTED]> wrote:
>> Is there anyway for python to consider the values within a
>> string when entering the data into a dictionary. I know that
>> isn't very clear so here's an example:
>>
>> class MyClass(object):
>> def __init__(self,name="",age=""):
>> self.name=name
>> self.age=age
>>
>> data="Gary,50"
>> d={0:[MyClass(data)]}
>> data="Adam,25"
>> d[0].append(MyClass(data))
>>
>> The data is coming from a text file working on a line by line
>> basis. I've just tried and I'm just getting the full string in
>> the first field. That seems logical, now I don't want it to
>> though!
> 
> That's what happens if you use 0 for the key every time. ;)

Hmmm... Neil, I may be wrong but I think you didn't get the point here. 
As I understand it,  Dominic's problem is that it gets strings like 
"Gary,50" and would like to call MyClass initializer this way : 
MyClass("Gary", "50")

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Neil Cerutti
On 2007-08-09, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> Neil Cerutti a écrit :
>> On 2007-08-09, special_dragonfly <[EMAIL PROTECTED]> wrote:
>>> Is there anyway for python to consider the values within a
>>> string when entering the data into a dictionary. I know that
>>> isn't very clear so here's an example:
>>>
>>> class MyClass(object):
>>> def __init__(self,name="",age=""):
>>> self.name=name
>>> self.age=age
>>>
>>> data="Gary,50"
>>> d={0:[MyClass(data)]}
>>> data="Adam,25"
>>> d[0].append(MyClass(data))
>>>
>>> The data is coming from a text file working on a line by line
>>> basis. I've just tried and I'm just getting the full string in
>>> the first field. That seems logical, now I don't want it to
>>> though!
>> 
>> That's what happens if you use 0 for the key every time. ;)
>
> Hmmm... Neil, I may be wrong but I think you didn't get the
> point here. As I understand it,  Dominic's problem is that it
> gets strings like "Gary,50" and would like to call MyClass
> initializer this way : MyClass("Gary", "50")

My guess was he doesn't need a class at all, but needed to decide
what he's mapping from->to. It seems far-fetched to me that he
*really* wants a mapping between an index and MyClass objects
containing name and age.

So I tried to cut out the middle-man. Hopefully we can get some
closure on this.

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


Re: tests

2007-08-09 Thread André Martins
Generate a hash of two files and compare
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Bruno Desthuilliers
special_dragonfly a écrit :
> "Bruno Desthuilliers" <[EMAIL PROTECTED]> 
> wrote in message news:[EMAIL PROTECTED]
>> special_dragonfly a écrit :
>> (snip)
(and resnip)

> Hello
> To answer first Bjoern:
> I have a dictionary and a class. The dictionary needs to be filled with 
> multiple instances of the class, with multiple instances per key. Currently 
> a lot of the dictionaries that are going into the program are hard coded 
> because they're just 1:1 mappings, in this case though it was a many:1 
> mapping and so I got a little stumped. I couldn't hard coded the mappings, 
> so I then needed to find a way of doing it dynamically. I'm now reading data 
> from a file containing the data for the class, and am now able to put that 
> data into a dictionary.
> 
> I'm quite new to programming large things, and previous experience has only 
> been in C and C++, so I'm also trying to get an idea of good programming 
> practises.

FWIW, and while there of course are quite a few common rules (consistent 
and meaningfull naming, modularization with high cohesion and low 
coupling, "don't repeat yourself" etc), "good programming practises" 
greatly vary from language to language. In fact, one of the common rules 
is probably : "be idiomatic" - that is, don't try to write Pascal in 
Lisp (or C in Python...).

> Other people are going to need to use this program, I need it to 
> be... correct... should someone need to alter it. So loads of documentation, 
> and meaningful variable names, but it's also experience that I'm lacking.

Indeed.

> Is 
> there a better way of doing such-and-such, or is it sensible to do it this 
> way?

I second Steven's suggestion to spend some time going thru introductory 
material. IMHO, the official Python tutorial (to get the basics - no pun 
intended) and then DiveIntoPython (to see the language in action) should 
do.

Then you'll find that most people here will be very happy to help you 
rewrite your code in the most pythonic way if you kindly ask for help...

> Thank you for your help, all of you.

Welcome to c.l.py.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stackless Integration

2007-08-09 Thread Bruno Desthuilliers
Jean-Paul Calderone a écrit :
> On Thu, 09 Aug 2007 09:00:27 -, "Justin T." <[EMAIL PROTECTED]> 
> wrote:
>> Hi,
>>
>> I've been looking at stackless python a little bit, and it's awesome.
>> My question is, why hasn't it been integrated into the upstream python
>> tree? Does it cause problems with the current C-extensions? It seems
>> like if something is fully compatible and better, then it would be
>> adopted. However, it hasn't been in what appears to be 7 years of
>> existence, so I assume there's a reason.
> 
> It's not Pythonic.

Hum... Yes ? Really ? Care to argument ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread special_dragonfly

"Ben Finney" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "special_dragonfly" <[EMAIL PROTECTED]> writes:
>
>> I've managed to solve the problem, I really was just being a
>> dunce.
>
> Doubtful; but at this stage we can't tell, because we still don't know
> what it is you're actually trying to *do*.
>
>> Here's how incase anyone is wondering:
>>
>> class MyClass:
>> def __init__(self):
>> name=""
>> dict={}
>> dict[0]=[]
>> dict[0].append(MyClass())
>> dict[0][0].name="Hello"
>> print dict[0][0].name
>
> It's not clear why you are using the value 0 for a dictionary key
> here; nor why you're assigning an attribute to an object after
> creating the object. Neither of them are errors, but without context
> it's hard to know what advice to give.
>
The 0 for a key is just an example. The code I actually have would be just 
as meaningful at the end of the day. I could have changed MyClass for
class Animals(object):
def __init__(self, name="", type="", age=""):
self.name=name
self.type=type
self.age=age

dict={'Mouse':[Animals('George','long eared',20)]}
dict['Mouse'].append(Animals('Benny','hairy',30))
dict['Cat']=[Animals('Inigo Montoya','spanish',10)]

and Neil, Bruno has the right idea of what I was trying to do. However, your 
code came in handy still as I used your code elsewhere.see below.

def EnterDictionary(FieldsDictionary,key,data):
for i in range(0,int(data[6:])):
line=myfile.readline()
line=line.strip()
line=line[6:-1]
if key in FieldsDictionary:
FieldsDictionary[key].append(FieldClass(*line.split(",")))
else:
FieldsDictionary[key]=[FieldClass(*line.split(","))]

I'd like to thank you all for your patience with me whilst I've asked some 
really beginner-like questions. I hope I haven't annoyed you all too much...

In future I would ask however, if it's a really stupid question and you feel 
that the answer can be found either by searching google (because in some 
cases I don't know what to search for), or in one of the O'reilly books, 
just say. In either case, if you could refer me to the search term to use or 
the book to read I'd be grateful.

Dominic 


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


Re: tests

2007-08-09 Thread brad
[EMAIL PROTECTED] wrote:

> You should be able to read chunks of each file in binary mode and do a
> compare to check for equality. Some kind of loop should do the trick.

Why not a simple md5 or sha with the hash library?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Issues of state (was: Tkinter or wxpython?)

2007-08-09 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Paul Rubin   wrote:
>[EMAIL PROTECTED] (Cameron Laird) writes:
>> Others have answered this at other levels.  In elementary terms,
>> there truly is a difference, Paul, and one that's widely reified:
>> a "desktop client-server" application typically listens through
>> one socket, which therefore constitutes an index of the connection
>> or client, while a Web application communicates through a sequence
>> of independent HTTP transactions.  The latter can manage state only
>> to the extent it passes session information around.
>
>Is this significant?  In the case of a single user http app running on
>the same computer as the browser, the server should only listen on
>127.0.0.1.  Every http hit then almost certainly comes from the same
>session.  If there's doubt, the app can always set a random cookie at
>the initial screen and check that the cookie never changes.
>
>If there's only a small amount of session state (say up to a few
>hundred bytes) you can put it entirely into browser cookies and send
>it on every single http hit.

I'm not sure what we're discussing.  Yes, I agree those are 
mechanisms by which Web applications manage state.  Apparently
we agree that, in a general Web application, state management,
or related persistence, requires *some* mechanism or assumption.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get command output using python

2007-08-09 Thread Steven Harms
In python it is quite easy:

import commands

status, output = commands.getstatusoutput("my command")


status will be the return code of the command
output will be what the command displayed

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

Re: Stackless Integration

2007-08-09 Thread Jean-Paul Calderone
On Thu, 9 Aug 2007 05:05:31 -0700, Michael Bentley <[EMAIL PROTECTED]> wrote:
>
>On Aug 9, 2007, at 4:48 AM, Jean-Paul Calderone wrote:
>
>> On Thu, 09 Aug 2007 09:00:27 -, "Justin T."
>> <[EMAIL PROTECTED]> wrote:
>>> Hi,
>>>
>>> I've been looking at stackless python a little bit, and it's awesome.
>>> My question is, why hasn't it been integrated into the upstream
>>> python
>>> tree? Does it cause problems with the current C-extensions? It seems
>>> like if something is fully compatible and better, then it would be
>>> adopted. However, it hasn't been in what appears to be 7 years of
>>> existence, so I assume there's a reason.
>>
>> It's not Pythonic.
>
>Can you be more specific?  It's a good question that I had thought
>about asking...

It was meant tongue in cheek.  "It's not Pythonic" is Pythoneer codespeak
for "I have an irrational dislike of it", which is the only reason that
has ever really been given for keeping Stackless separate from CPython.

Perhaps the most reason which comes closest to being tangible is that it
is "complex" and would require "maintenance".

Jean-Paul

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


Re: tests

2007-08-09 Thread dijkstra . arjen
On Aug 9, 4:04 pm, brad <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > You should be able to read chunks of each file in binary mode and do a
> > compare to check for equality. Some kind of loop should do the trick.
>
> Why not a simple md5 or sha with the hash library?

Or even:

http://docs.python.org/lib/module-filecmp.html

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


Re: tests

2007-08-09 Thread special_dragonfly

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Aug 9, 4:04 pm, brad <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>> > You should be able to read chunks of each file in binary mode and do a
>> > compare to check for equality. Some kind of loop should do the trick.
>>
>> Why not a simple md5 or sha with the hash library?
>
> Or even:
>
> http://docs.python.org/lib/module-filecmp.html
>

My understanding of reading that is that it only looks at the file names 
themselves and not their contents. So whether filename1=filename2 and in the 
case of the function below it, whether one directory has files which are in 
the other.
Correct me if I'm wrong.
Dom

P.S. md5 or sha hash is what I'd go for, short of doing:

MyFirstFile=file("file1.xls")
MySecondFile=file("file2.xls")
If MyFirstFile==MySecondFile:
print "True"

although this won't tell you where they're different, just that they are... 


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


Re: Issues of state

2007-08-09 Thread Steve Holden
Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>,
> Paul Rubin   wrote:
>> [EMAIL PROTECTED] (Cameron Laird) writes:
>>> Others have answered this at other levels.  In elementary terms,
>>> there truly is a difference, Paul, and one that's widely reified:
>>> a "desktop client-server" application typically listens through
>>> one socket, which therefore constitutes an index of the connection
>>> or client, while a Web application communicates through a sequence
>>> of independent HTTP transactions.  The latter can manage state only
>>> to the extent it passes session information around.
>> Is this significant?  In the case of a single user http app running on
>> the same computer as the browser, the server should only listen on
>> 127.0.0.1.  Every http hit then almost certainly comes from the same
>> session.  If there's doubt, the app can always set a random cookie at
>> the initial screen and check that the cookie never changes.
>>
>> If there's only a small amount of session state (say up to a few
>> hundred bytes) you can put it entirely into browser cookies and send
>> it on every single http hit.
> 
> I'm not sure what we're discussing.  Yes, I agree those are 
> mechanisms by which Web applications manage state.  Apparently
> we agree that, in a general Web application, state management,
> or related persistence, requires *some* mechanism or assumption.

As far as I'm concerned the major issue with trying to have "desktop web 
apps" compete with true windowed applications is the difficulty of 
maintaining sensible interactions with the interface. AJAX designs have 
increased the interaction level at the expense of greater complexity - 
there is more state to be transferred, and a much higher interaction 
rate with the server. But the browser is a terrible front-end for AJAX 
designs because it doesn't record the state changes that take place as a 
result of requests for updated InnerHTML content, so if the user is 
unwise enough to press the "back" button she loses all traces of the 
non-page interactions that have taken place since the page was loaded.

So "desktop web apps" should ensure that they get displayed in browser 
windows with minimal user interface decoration. But even then there's 
always that chance that sophisticated users will use keyboard shortcuts 
like ALT-left-arrow.

That, in summary, is why my 2004 PyCon paper[1] was subtitled "The Back 
Button is Not Your Friend".

regards
  Steve

[1]: http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


py2exe, command line parameter problem

2007-08-09 Thread Karsten W.
Hello,
my small program is a Tkinter-App which supports some command line
options. When the app is started within the python environment,
everything works fine. When the py2exe-frozen app is started,
everything works until I pass command line parameters. Then the gui
window is not displayed.

It's python 2.3 on WinXp with py2exe 0.6.6.

How can I debug this behaviour?

Any hint appreciated,
Karsten.

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


Re: tests

2007-08-09 Thread Jason
On Aug 9, 8:46 am, "special_dragonfly" <[EMAIL PROTECTED]>
wrote:
> <[EMAIL PROTECTED]> wrote in message
> >http://docs.python.org/lib/module-filecmp.html
>
> My understanding of reading that is that it only looks at the file names
> themselves and not their contents. So whether filename1=filename2 and in the
> case of the function below it, whether one directory has files which are in
> the other.
> Correct me if I'm wrong.
> Dom
>
> P.S. md5 or sha hash is what I'd go for, short of doing:
>
> MyFirstFile=file("file1.xls")
> MySecondFile=file("file2.xls")
> If MyFirstFile==MySecondFile:
> print "True"
>
> although this won't tell you where they're different, just that they are...

You're incorrect.  If the shallow flag is not given or is true, the
results of os.stat are used to compare the two files, so if they have
the same size, change times, etc, they're considered the same.

If the shallow flag is given and is false, their contents are
compared.  In either case, the results are cached for efficiency's
sake.

  --Jason


The documentation for filecmp.cmp is:
  cmp(  f1, f2[, shallow])
  Compare the files named f1 and f2, returning True if they seem
equal, False otherwise.

  Unless shallow is given and is false, files with identical
os.stat() signatures are taken to be equal.

  Files that were compared using this function will not be
compared again unless their os.stat() signature changes.

  Note that no external programs are called from this function,
giving it portability and efficiency.

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


Re: Something in the function tutorial confused me.

2007-08-09 Thread Magnus Lycka
Lee Fleming wrote:
> Hello,
> I have a simple question. Say you have the following function:
> 
> def f(x, y = []):
...

> But this, the code that "fixes" the list accumulation confounds me:
> def  f(x, y=None):
> if y is None: y = []
...

> In other words, what's going on here? How is it that y accumulates
> argument values between function calls in the first function, but
> doesn't in the second one? 

I think the important thing to understand here is the
distinction between names/variables and objects/values
in Python.

While you could interpret C code like this...

void f() {
 ...
 int i = 5;
 ...
 int j = i;
 ...
}

... as "create a place in the namespace of the f function
where you can fit an integer value, and put the value 5
there. Later, create another place in the namespace of f
which is also big enough for an integer. Copy the contents
of the location named 'i', to the location named 'j'."

You would instead interpret this similar Python code...

def f():
 ...
 i = 5
 ...
 j = i
 ...

... as "create an integer object with the value 5. Then
define a name/tag/variable in the namespace of function
f which refers to the integer object with the value 5.
Later, make a new name/tag/variable in the namespace of
f which refers to the same object (happens to be an
integer with the value 5) as i refers to."

The semantics is very different.

If you understand this, Python will seem much less magical,
and you will never ask meaningless questions as whether
Python uses call by reference or call by value.

It's all a matter of understanding that all the juicy bits
in the Python data model is in the actual values or objects.
That's the stuff with type safety, a location in memory,
qualities such as mutability etc. A "variable" is basically
just a reference to an arbitrary object in a particular
namespace. Assignments semantics is not about copying
data as in C, and it's nothing arbitrarily defined in
classes as in C++. It's all about deciding which object
a name refers to.

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Bruno Desthuilliers
Neil Cerutti a écrit :
> On 2007-08-09, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
>> Neil Cerutti a écrit :
>>> On 2007-08-09, special_dragonfly <[EMAIL PROTECTED]> wrote:
 Is there anyway for python to consider the values within a
 string when entering the data into a dictionary. I know that
 isn't very clear so here's an example:

 class MyClass(object):
 def __init__(self,name="",age=""):
 self.name=name
 self.age=age

 data="Gary,50"
 d={0:[MyClass(data)]}
 data="Adam,25"
 d[0].append(MyClass(data))

 The data is coming from a text file working on a line by line
 basis. I've just tried and I'm just getting the full string in
 the first field. That seems logical, now I don't want it to
 though!
>>> That's what happens if you use 0 for the key every time. ;)
>> Hmmm... Neil, I may be wrong but I think you didn't get the
>> point here. As I understand it,  Dominic's problem is that it
>> gets strings like "Gary,50" and would like to call MyClass
>> initializer this way : MyClass("Gary", "50")
> 
> My guess was he doesn't need a class at all,

Mmm... That's possible (and if all he has in MyClass are name and age 
data attributes, then you're obviously right). But then your answer was 
perhaps a bit confusing (at least it confused me...)

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


Re: Stackless Integration

2007-08-09 Thread Steve Holden
Bruno Desthuilliers wrote:
> Jean-Paul Calderone a écrit :
>> On Thu, 09 Aug 2007 09:00:27 -, "Justin T." <[EMAIL PROTECTED]> 
>> wrote:
>>> Hi,
>>>
>>> I've been looking at stackless python a little bit, and it's awesome.
>>> My question is, why hasn't it been integrated into the upstream python
>>> tree? Does it cause problems with the current C-extensions? It seems
>>> like if something is fully compatible and better, then it would be
>>> adopted. However, it hasn't been in what appears to be 7 years of
>>> existence, so I assume there's a reason.
>> It's not Pythonic.
> 
> Hum... Yes ? Really ? Care to argument ?

Unfortunately such arguments quickly descend to the "yes it is", "no it 
isn't" level, as there is no objective measure of Pythonicity.

Twisted is a complex set of packages which is difficult to understand 
from the outside,and is motivated by a specific approach to asynchronous 
operations that is neither well understood by the majority of 
programmers nor easily-explained to them. All the teaching sessions on 
Twisted I have attended have involved a certain amount of hand-waving or 
some over-heavy code examples with inadequate explanations.

However I would say that Twisted has improve enormously over the last 
five years, and should really be a candidate for inclusion in the 
standard library. It would be a large component, though, and so there 
would be a number of heavy tasks involved, not least of them updating 
the documentation. So maintenance might be a worry unless a group stood 
up and committed to the task.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Something in the function tutorial confused me.

2007-08-09 Thread Neil Cerutti
On 2007-08-09, Magnus Lycka <[EMAIL PROTECTED]> wrote:
> It's all a matter of understanding that all the juicy bits in
> the Python data model is in the actual values or objects.
> That's the stuff with type safety, a location in memory,
> qualities such as mutability etc. A "variable" is basically
> just a reference to an arbitrary object in a particular
> namespace.

Excellent post.

Languages like C tried to make the scope of names and the extent
of the objects they refer to be the same, probably for
efficiency.  One nice property of this is that the two concepts
can be conflated into the simpler single idea of "variables".
It's simple, that is, until you create references. Then you can
get into complicated trouble by creating references to things
that may be destroyed. In Python names have lexical scope, while
the objects they refer to are eternal.

> Assignments semantics is not about copying data as in C, and
> it's nothing arbitrarily defined in classes as in C++. It's all
> about deciding which object a name refers to.

Assignment semantics are not arbitrary in C++. You do have to
define them manually for new data types, but if you get it wrong
your code is pretty much useless. You are free to create your own
assignment semantics, as long as they match the semantics of the
built in types. Python has this property as well, though you're
limited to screwing up the "augmented assignment/arithmetic"
operators.

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Sion Arrowsmith
special_dragonfly <[EMAIL PROTECTED]> wrote:
>if key in FieldsDictionary:
>FieldsDictionary[key].append(FieldClass(*line.split(",")))
>else:
>FieldsDictionary[key]=[FieldClass(*line.split(","))]

These four lines can be replaced by:

FieldsDictionary.setdefault(key, []).append(FieldClass(*line.split(",")))

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Stackless Integration

2007-08-09 Thread Terry Reedy

"Justin T." <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| I've been looking at stackless python a little bit, and it's awesome.
| My question is, why hasn't it been integrated into the upstream python
| tree? Does it cause problems with the current C-extensions? It seems
| like if something is fully compatible and better, then it would be
| adopted. However, it hasn't been in what appears to be 7 years of
| existence, so I assume there's a reason.

First, which 'stackless'?  The original continuation-stackless (of about 7 
years ago)?  Or the more current tasklet-stackless (which I think is much 
younger than that)?

The original added a feature Guido did not want (continuations) and 
required major changes to the core that would have make maintainance 
probably more difficult for most of the developers, including GvR.  For 
more, see
http://www.python.org/dev/peps/pep-0219/

Second, what do you mean by integration?  The current tasklet version is, I 
am sure, as well integrated as Tismer can make it.  Last I looked, there 
were warnings about possible incompatibilities, but perhaps these have been 
overcome.  It is just not part of the stdlib.  And as far as I know or 
could find in the PEP index, C. Tismer has never submitted a PEP asking 
that it be made so.  Doing so would mean a loss of control, so there is a 
downside as well as the obvious upside of distribution.

tjr



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


Re: tests

2007-08-09 Thread Steve Holden
Jason wrote:
> On Aug 9, 8:46 am, "special_dragonfly" <[EMAIL PROTECTED]>
> wrote:
>> <[EMAIL PROTECTED]> wrote in message
>>> http://docs.python.org/lib/module-filecmp.html
>> My understanding of reading that is that it only looks at the file names
>> themselves and not their contents. So whether filename1=filename2 and in the
>> case of the function below it, whether one directory has files which are in
>> the other.
>> Correct me if I'm wrong.
>> Dom
>>
>> P.S. md5 or sha hash is what I'd go for, short of doing:
>>
>> MyFirstFile=file("file1.xls")
>> MySecondFile=file("file2.xls")
>> If MyFirstFile==MySecondFile:
>> print "True"
>>
>> although this won't tell you where they're different, just that they are...
> 
> You're incorrect.  If the shallow flag is not given or is true, the
> results of os.stat are used to compare the two files, so if they have
> the same size, change times, etc, they're considered the same.
> 
> If the shallow flag is given and is false, their contents are
> compared.  In either case, the results are cached for efficiency's
> sake.
> 
>   --Jason
> 
> 
> The documentation for filecmp.cmp is:
>   cmp(f1, f2[, shallow])
>   Compare the files named f1 and f2, returning True if they seem
> equal, False otherwise.
> 
>   Unless shallow is given and is false, files with identical
> os.stat() signatures are taken to be equal.
> 
>   Files that were compared using this function will not be
> compared again unless their os.stat() signature changes.
> 
>   Note that no external programs are called from this function,
> giving it portability and efficiency.
> 

This discussion seems to assume that Excel spreadsheets are stored in 
some canonical form so that two spreads with the same functionality are 
always identical on disk to the last bit. I very much doubt this is true 
(consider as an example the file properties that can be set).

So really you need to define "equality". So far the tests discussed have 
concentrated on identifying identical files.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: wxPython before MainLoop

2007-08-09 Thread 7stud
On Aug 8, 11:25 pm, "[david]" <[EMAIL PROTECTED]> wrote:
> I'd like to refresh the display before I start the main loop.
>
> I have code like this:
>
> app = App()
> app.Show()
> app.long_slow_init()
> app.MainLoop()
>
> The main frame partly loads at Show, but because the mainloop has not
> started yet, the display does not update until long_slow_init() finishes.
>
> Alternatively, I could code
>
> app = App()
> app.long_slow_init()
> app.Show()
> app.MainLoop()
>
> Which would give me a crisp Show, but there would be a long slow wait
> before the app showed any activity at all. I would need a splash screen.
>
> I'd rather not have a splash screen (and I don't know how anyway). I'd
> like to just make app.Show() finish correctly before running
> long_slow_init.
>
> Is there a wx internal method that I can use to give Windows the
> opportunity to finish painting the frame before I run long_slow_init()?
>
> Or is there a better idea?
>
> (david)

I don't see my original post, so here it is again


You can use another thread to execute long_slow_init():

--
import wx
import threading
import time

class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "My Window")

panel = wx.Panel(self, -1)
button = wx.Button(panel, -1, "click me, quick!", pos=(40,
40))
self.Bind(wx.EVT_BUTTON, self.onclick)

def onclick(self, event):
print "button clicked"

def receive_result(self, result):
print "Hey, I'm done with that long, slow initialization."
print "The result was:", result


class MyApp(wx.App):
def __init__(self):
wx.App.__init__(self, redirect=False)


def OnInit(self):  #called by wx.Python
the_frame = MyFrame()
the_frame.Show()

t = MyThread(the_frame)
t.start()  #calls t.run()

return True

class MyThread(threading.Thread):
def __init__(self, a_frame):
threading.Thread.__init__(self)
self.frame_obj = a_frame

def run(self):
result = self.long_slow_init()

wx.CallAfter(self.frame_obj.receive_result, result)
#CallAfter() calls the specified function with the
#specified argument when the next pause in execution
#occurs in this thread:

def long_slow_init(self):
print "starting long_slow_init()..."
time.sleep(6)
result = 20.5
return result


app = MyApp()
app.MainLoop()

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Bruno Desthuilliers
special_dragonfly a écrit :
> "Ben Finney" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> "special_dragonfly" <[EMAIL PROTECTED]> writes:
>>
>>> I've managed to solve the problem, I really was just being a
>>> dunce.
>> Doubtful; but at this stage we can't tell, because we still don't know
>> what it is you're actually trying to *do*.
>>
>>> Here's how incase anyone is wondering:
>>>
>>> class MyClass:
>>> def __init__(self):
>>> name=""
>>> dict={}
>>> dict[0]=[]
>>> dict[0].append(MyClass())
>>> dict[0][0].name="Hello"
>>> print dict[0][0].name
>> It's not clear why you are using the value 0 for a dictionary key
>> here; nor why you're assigning an attribute to an object after
>> creating the object. Neither of them are errors, but without context
>> it's hard to know what advice to give.
>>
> The 0 for a key is just an example. The code I actually have would be just 
> as meaningful at the end of the day. I could have changed MyClass for
> class Animals(object):
> def __init__(self, name="", type="", age=""):
> self.name=name
> self.type=type
> self.age=age
> 
> dict={'Mouse':[Animals('George','long eared',20)]}
> dict['Mouse'].append(Animals('Benny','hairy',30))
> dict['Cat']=[Animals('Inigo Montoya','spanish',10)]
> 
> and Neil, Bruno has the right idea of what I was trying to do. However, your 
> code came in handy still as I used your code elsewhere.see below.
> 
> def EnterDictionary(FieldsDictionary,key,data):
> for i in range(0,int(data[6:])):
> line=myfile.readline()
> line=line.strip()
> line=line[6:-1]
> if key in FieldsDictionary:
> FieldsDictionary[key].append(FieldClass(*line.split(",")))
> else:
> FieldsDictionary[key]=[FieldClass(*line.split(","))]

May I suggest a couple possible improvements ?

First : you're of course free to use any naming convention you like, and 
it's obviously better to stay consistent, but the canonical Python 
convention is to use all_lower for vars, functions (and methods) and 
modules, and MixedCase for classes.

About the code now:

def EnterDictionary(FieldsDictionary,key,data):
 for i in range(0,int(data[6:])):

1/ Golden rule : avoid the use of "magic numbers". This one stands true 
for any languages !-). The usual solution is to use symbolic constants. 
While Python doesn't have real symbolic constant, the convention is to 
write them ALL_UPPER.

2/ range() can be used with only one argument, which then will be use as 
the upper bound. IOW,
   range(0, X)
is the same as
   range(X)

 line=myfile.readline()

3/ where does this 'myfile' comes from ? (hint : don't use globals when 
you can avoid them)


 line=line.strip()
 line=line[6:-1]

4/ magic numbers again, cf /1. Question : does this 6 has anything to do 
with the other one ? What will happen when the file format will change ?

5/ you can do all this in a single line, adding the split() too:
 args = myfile.readline().strip()[XXX:-1].split(",")

 > if key in FieldsDictionary:
 > FieldsDictionary[key].append(FieldClass(*line.split(",")))
 > else:
 > FieldsDictionary[key]=[FieldClass(*line.split(","))]


If you expect key to most of the times be already in FieldsDictionnary, 
then a try/except block might be a bit faster. If you expect key to not 
be here most of the times, then your solution is right. Note that you 
can also use dict.setdefault(key, default):

# probably bad names but I don't have a clue what they should be
DATA_INDEX_OFFSET = 6
LINE_START = 6
LINE_END = -1

def update_fields_dict(fields_dict, key, data, datafile):
   for i in range(int(data[DATA_INDEX_OFFSET:])):
 args =datafile.readline().strip()[LINE_START:LINE_END].split(",")
 fields_dict.setdefault(key, []).append(FieldClass(*args))

Feel free to take or leave what you consider appropriate here. But by 
all means avoid magic numbers, except possibly for Q&D throw-away 
scripts (and even then...).

HTH

> In future I would ask however, if it's a really stupid question and you feel 
> that the answer can be found either by searching google (because in some 
> cases I don't know what to search for), or in one of the O'reilly books, 
> just say. In either case, if you could refer me to the search term to use or 
> the book to read I'd be grateful.

That's usually what happens then, don't worry.
-- 
http://mail.python.org/mailman/listinfo/python-list


Extending logging module

2007-08-09 Thread jay
Hello,

I've been using the python logging module a lot lately, and I've come
across an instance where I need some new levels.  Specifically, python
does not include ALERT and NOTICE in the default set of logging
levels.  I am wondering how trivial it would be to extend the logging
module to include these 2 levels that are standard with syslog?

My first test was just to use the addLevelName method to add the two
new levels, but syslog ignores them and logs at the next highest
priority, no matter what I use.

Looking further into the code and as a test, I changed the following
to see if this would even work

lib/python2.5/logging/__init__.py
  -> class Logger
  -> add new notice and alert root level functions
  -> new _levelNames for notice and alert
  -> new default level names for notice and alert

lib/python2.5/logging/handlers.py
  -> class SysLogHandler priority_map was changed to include notice
and alert

It actually worked, but this is not the way I would like to handle the
problem.  I would prefer to extend the classes instead.  However, I'm
not too familiar with that, and I had to change things in so many
places, I'm wondering if its even possible?  I don't like changing the
standard libraries, what happens if I have to upgrade python?  My
changes get overwritten.

Can anyone offer some help or suggestions?  Thanks

Jay

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


Re: Issues of state

2007-08-09 Thread Jay Loden
Steve Holden wrote:
> As far as I'm concerned the major issue with trying to have "desktop web 
> apps" compete with true windowed applications is the difficulty of 
> maintaining sensible interactions with the interface. AJAX designs have 
> increased the interaction level at the expense of greater complexity - 
> there is more state to be transferred, and a much higher interaction 
> rate with the server. But the browser is a terrible front-end for AJAX 
> designs because it doesn't record the state changes that take place as a 
> result of requests for updated InnerHTML content, so if the user is 
> unwise enough to press the "back" button she loses all traces of the 
> non-page interactions that have taken place since the page was loaded.
> 
> So "desktop web apps" should ensure that they get displayed in browser 
> windows with minimal user interface decoration. But even then there's 
> always that chance that sophisticated users will use keyboard shortcuts 
> like ALT-left-arrow.
> 
> That, in summary, is why my 2004 PyCon paper[1] was subtitled "The Back 
> Button is Not Your Friend".
> 
> regards
>   Steve
> 
> [1]: http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf

There's been some interesting work done in that area as well:

http://dev2dev.bea.com/pub/a/2006/01/ajax-back-button.html
http://www.isolani.co.uk/blog/javascript/FixingTheBackButtonThatAjaxBroke

In particular, the RSH (Really Simple History) Framework is an open source
solution to the problem:

http://www.onjava.com/pub/a/onjava/2005/10/26/ajax-handling-bookmarks-and-back-button.html

Like most things involving dynamic client side-javascript code and AJAX
technology, it's a lot harder than you'd like it to be to solve the problem, but
in cases where the Back button is really an issue, it's worth the effort.

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


Re: tests

2007-08-09 Thread Jay Loden
Steve Holden wrote:
> This discussion seems to assume that Excel spreadsheets are stored in 
> some canonical form so that two spreads with the same functionality are 
> always identical on disk to the last bit. I very much doubt this is true 
> (consider as an example the file properties that can be set).
> 
> So really you need to define "equality". So far the tests discussed have 
> concentrated on identifying identical files.
> 
> regards
>   Steve

I was wondering myself if the OP was actually interested in binary identical
files, or just duplicated content. If just duplicated content, perhaps this
could be used as a starting point:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440661

and the actual data can be compared

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


Re: Stackless Integration

2007-08-09 Thread Steve Holden
Steve Holden wrote:
> Bruno Desthuilliers wrote:
>> Jean-Paul Calderone a écrit :
>>> On Thu, 09 Aug 2007 09:00:27 -, "Justin T." <[EMAIL PROTECTED]> 
>>> wrote:
 Hi,

 I've been looking at stackless python a little bit, and it's awesome.
 My question is, why hasn't it been integrated into the upstream python
 tree? Does it cause problems with the current C-extensions? It seems
 like if something is fully compatible and better, then it would be
 adopted. However, it hasn't been in what appears to be 7 years of
 existence, so I assume there's a reason.
>>> It's not Pythonic.
>> Hum... Yes ? Really ? Care to argument ?
> 
> Unfortunately such arguments quickly descend to the "yes it is", "no it 
> isn't" level, as there is no objective measure of Pythonicity.
> 
> Twisted [...]
> 
Oops, did I say Twisted? When I last heard Chris Tismer talking about 
Stackless someone in the audience asked him about the prospects of 
incorporating Stackless into the core and he suggested he didn't 
necessarily think of that as a desirable change.

I would like to see it in the core, but integration would not be an easy 
task, and maintenance might be problematic.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Stackless Integration

2007-08-09 Thread Justin T.
On Aug 9, 8:57 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> First, which 'stackless'?  The original continuation-stackless (of about 7
> years ago)?  Or the more current tasklet-stackless (which I think is much
> younger than that)?
>
The current iteration. I can certianly understand Guido's distaste for
continuations.

>
> overcome.  It is just not part of the stdlib.
And I wish it were! It wouldn't be such a pain to get to my developers
then.

> And as far as I know or
> could find in the PEP index, C. Tismer has never submitted a PEP asking
> that it be made so.  Doing so would mean a loss of control, so there is a
> downside as well as the obvious upside of distribution.
That's true. Though, hopefully, the powers that be would allow him to
maintain it while it's in the stdlib. Maybe we should file a PEP for
him... :)

Justin

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


Re: Stackless Integration

2007-08-09 Thread Justin T.

> It's not Pythonic.
>
> Jean-Paul

Ha! I wish there was a way to indicate sarcasm on the net. You almost
got people all riled up!

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


Re: how to get command output using python

2007-08-09 Thread Arnau Sanchez
Steven Harms escribió:

> In python it is quite easy:
> 
> import commands
> status, output = commands.getstatusoutput("my command")

Uhm, this module has a big issue:

(http://docs.python.org/lib/module-commands.html)

8.17 commands -- Utilities for running commands

Availability: Unix.


Any non cross-platform module should be avoided unless absolutely necessary.

Subprocess is the right module to use.

arnau

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


Re: Stackless Integration

2007-08-09 Thread Neil Cerutti
On 2007-08-09, Justin T. <[EMAIL PROTECTED]> wrote:
>
>> It's not Pythonic.
>>
>> Jean-Paul
>
> Ha! I wish there was a way to indicate sarcasm on the net. You
> almost got people all riled up!

Sorry. There's NO WAY to show sarcasm on the net. ;)

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


Puzzled by "is"

2007-08-09 Thread Dick Moores
 >>> () is ()
True
 >>> (1,) is (1,)
False

Why?

Thanks,

Dick Moores

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


Re: Puzzled by "is"

2007-08-09 Thread Jay Loden
Dick Moores wrote:
>  >>> () is ()
> True
>  >>> (1,) is (1,)
> False
> 
> Why?
> 
> Thanks,
> 
> Dick Moores

>From the docs for 'is':

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


Re: Puzzled by "is"

2007-08-09 Thread Bill Scherer
Dick Moores wrote:
>  >>> () is ()
> True
>  >>> (1,) is (1,)
> False
>
> Why?
>   

>>> a = ()
>>> b = ()
>>> c = (1,)
>>> d = (1,)
>>> a is b
True
>>> c is d
False
>>> id(a)
3086553132
>>> id(b)
3086553132
>>> id(c)
3086411340
>>> id(d)
3086390892


There is only one empty tuple.
Does that clear it up for you?

> Thanks,
>
> Dick Moores
>
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by "is"

2007-08-09 Thread Neil Cerutti
On 2007-08-09, Dick Moores <[EMAIL PROTECTED]> wrote:
> >>> () is ()
> True
> >>> (1,) is (1,)
> False
>
> Why?

>From _Python Reference Manual_: 5.2.4 List displays:

  An empty pair of parentheses yields an empty tuple object.
  Since tuples are immutable, the rules for literals apply (i.e.,
  two occurrences of the empty tuple may or may not yield the
  same object). 

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


Re: how to get command output using python

2007-08-09 Thread kyosohma
On Aug 9, 12:01 pm, Arnau Sanchez <[EMAIL PROTECTED]> wrote:
> Steven Harms escribió:
>
> > In python it is quite easy:
>
> > import commands
> > status, output = commands.getstatusoutput("my command")
>
> Uhm, this module has a big issue:
>
> (http://docs.python.org/lib/module-commands.html)
> 
> 8.17 commands -- Utilities for running commands
>
> Availability: Unix.
> 
>
> Any non cross-platform module should be avoided unless absolutely necessary.
>
> Subprocess is the right module to use.
>
> arnau

You forgot to mention that subprocess replaces commands, so in effect,
commands is deprecated anyway.

Mike

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


Re: Puzzled by "is"

2007-08-09 Thread Jay Loden


Jay Loden wrote:
> Dick Moores wrote:
>>  >>> () is ()
>> True
>>  >>> (1,) is (1,)
>> False
>>
>> Why?
>>
>> Thanks,
>>
>> Dick Moores
> 


>From the docs for 'is':

  The operators is and is not test for object identity: x is y is true if
  and only if x and y are the same object. x is not y yields the inverse
  truth value.



So you're actually testing whether or not the identity of the object is the
same, not whether (1,) == (1,):

>>> (1,) == (1,)
True
>>> id((0,)) == id((0,))
False

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


tempfile behavior

2007-08-09 Thread billiejoex
Hi all,
I would like to use tempfile module to generate files having unique
names excepting that I don't want them to be removed after closing.
Does it is possible?

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


how to call file from Jython?

2007-08-09 Thread Naveen kumar
Hi I want to excute a .cmd file on windows through jython.. How can i do that?
   
  I am using following code
   
  import os
   
  os.system("C:/testfile/anotherfolder/Startserver.cmd")
   
  can any body let me know how can excute Startserver.cmd from jython??
   
  thanks,
  Naveen

   
-
Be a better Globetrotter. Get better travel answers from someone who knows.
Yahoo! Answers - Check it out.-- 
http://mail.python.org/mailman/listinfo/python-list

Threaded Design Question

2007-08-09 Thread half . italian
Hi all!  I'm implementing one of my first multithreaded apps, and have
gotten to a point where I think I'm going off track from a standard
idiom.  Wondering if anyone can point me in the right direction.

The script will run as a daemon and watch a given directory for new
files.  Once it determines that a file has finished moving into the
watch folder, it will kick off a process on one of the files.  Several
of these could be running at any given time up to a max number of
threads.

Here's how I have it designed so far.  The main thread starts a
Watch(threading.Thread) class that loops and searches a directory for
files.  It has been passed a Queue.Queue() object (watch_queue), and
as it finds new files in the watch folder, it adds the file name to
the queue.

The main thread then grabs an item off the watch_queue, and kicks off
processing on that file using another class Worker(threading.thread).

My problem is with communicating between the threads as to which files
are currently processing, or are already present in the watch_queue so
that the Watch thread does not continuously add unneeded files to the
watch_queue to be processed.  For example...Watch() finds a file to be
processed and adds it to the queue.  The main thread sees the file on
the queue and pops it off and begins processing.  Now the file has
been removed from the watch_queue, and Watch() thread has no way of
knowing that the other Worker() thread is processing it, and shouldn't
pick it up again.  So it will see the file as new and add it to the
queue again.  PS.. The file is deleted from the watch folder after it
has finished processing, so that's how i'll know which files to
process in the long term.

I made definite progress by creating two queues...watch_queue and
processing_queue, and then used lists within the classes to store the
state of which files are processing/watched.

I think I could pull it off, but it has got very confusing quickly,
trying to keep each thread's list and the queue always in sync with
one another.  The easiset solution I can see is if my threads could
read an item from the queue without removing it from the queue and
only remove it when I tell it to.  Then the Watch() thread could then
just follow what items are on the watch_queue to know what files to
add, and then the Worker() thread could intentionally remove the item
from the watch_queue once it has finished processing it.

Now that I'm writing this out, I see a solution by over-riding or
wrapping Queue.Queue().get() to give me the behavior I mention above.

I've noticed .join() and .task_done(), but I'm not sure of how to use
them properly.  Any suggestions would be greatly appreciated.

~Sean

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


Re: tempfile behavior

2007-08-09 Thread half . italian
On Aug 9, 11:21 am, billiejoex <[EMAIL PROTECTED]> wrote:
> Hi all,
> I would like to use tempfile module to generate files having unique
> names excepting that I don't want them to be removed after closing.
> Does it is possible?

Looks like tempfile.mkstemp() will do what you want.

'''Unlike TemporaryFile(), the user of mkstemp() is responsible for
deleting the temporary file when done with it.'''

~Sean

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


Re: how to get output.

2007-08-09 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> I corrected a typ below.
> 
> On Aug 9, 12:50 pm, [EMAIL PROTECTED] wrote:
>> Hey,
>>
>> I did write the following:
>> but it does not work.
>>
>> import subprocess as sp
>> try:
>> p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE)
>> result = p.communicate()[0]
>> print result
>>  except:
>>  print "error"
>>
>> This throws error.
>> DIR . /AD /B will list out only directories in the current directory.
>>
>> Thanks,
>> Indu
>>
>> On Aug 9, 11:46 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> indu_shreenath schrieb:
 Hey,
 I want to get the output of "DIR /AD /B" command to a varriable using
 python. How can I do this?
>>> Using the subprocess-module.
>>> However, I'm not sure what DIR /AD /B does - but there are many
>>> functions in module os that might deliver what you want without invoking
>>> an external command.
>>> Diez- Hide quoted text -
>> - Show quoted text -
> 
> 
That is better done in python with:

import os
dirs=[d for d in os.listdir(os.curdir) if os.path.isdir(d)]

or

dirs=filter(os.path.isdir, os.listdir(os.curdir))

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


Re: Threaded Design Question

2007-08-09 Thread Justin T.
On Aug 9, 11:25 am, [EMAIL PROTECTED] wrote:
>
> Here's how I have it designed so far.  The main thread starts a
> Watch(threading.Thread) class that loops and searches a directory for
> files.  It has been passed a Queue.Queue() object (watch_queue), and
> as it finds new files in the watch folder, it adds the file name to
> the queue.
>
> The main thread then grabs an item off the watch_queue, and kicks off
> processing on that file using another class Worker(threading.thread).
>
Sounds good.

>
> I made definite progress by creating two queues...watch_queue and
> processing_queue, and then used lists within the classes to store the
> state of which files are processing/watched.
>
This sounds ugly, synchronization is one of those evils of
multithreaded programming that should be avoided if possible. I see a
couple of dirt simple solutions:

1. Have the watch thread move the file into a "Processing" folder that
it doesn't scan
2. Have the watch thread copy the file into a python tempfile object
and push that onto the queue, then delete the real file. This can be
done efficiently (well, more efficiently than new.write(old.read())
with shutil.copyfileobj(old, new)

Both those take very few lines of code, don't require synchronization,
and don't require extending standard classes.

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


Querying Graphics Card Name

2007-08-09 Thread Benjamin Goldenberg
Hello,
I would like to find out the name of the graphics card of the machine
my program is running on. I have looked into the pyopengl module, and
using them to query the card, but it seems like there ought to be a
simpler way to find this out without setting up a glcontext. Does
anyone have any ideas?

Thanks,
Benjamin

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


Re: check if regeular expression has results

2007-08-09 Thread Bruno Desthuilliers
Neil Cerutti a écrit :
> On 2007-08-09, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 
>>Hi,
>>I'm looking for the best way to check if regular expression return
>>true (it's mean - there is a match). for example, i want "if" that
>>check if this regular expression: .*born.*to.* has a match.
>>
>>What's the way to do that simply?
> 
> 
> Newgroups are a poor substitute for the docs. For one thing,
> newsgroups sometimes contain cranky people who say, "RTFM!" The
> docs will never do that.
> 
And for completness, here are the relevant parts of TheFineManual(tm):
http://docs.python.org/lib/module-re.html
http://www.amk.ca/python/howto/regex/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by "is"

2007-08-09 Thread Dick Moores
At 10:46 AM 8/9/2007, Bill Scherer wrote:
>Dick Moores wrote:
> >  >>> () is ()
> > True
> >  >>> (1,) is (1,)
> > False
> >
> > Why?
> >
>
> >>> a = ()
> >>> b = ()
> >>> c = (1,)
> >>> d = (1,)
> >>> a is b
>True
> >>> c is d
>False
> >>> id(a)
>3086553132
> >>> id(b)
>3086553132
> >>> id(c)
>3086411340
> >>> id(d)
>3086390892
>
>
>There is only one empty tuple.
>Does that clear it up for you?

But isn't that the same as saying, "That's just the reality of 
Python; it is what it is."? I want to know why there is only one 
empty tuple, but more than one (1,).

Also,
 >>> [] is []
False

Dick  

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


Re: tempfile behavior

2007-08-09 Thread billiejoex
On 9 Ago, 20:31, [EMAIL PROTECTED] wrote:
> On Aug 9, 11:21 am, billiejoex <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
> > I would like to use tempfile module to generate files having unique
> > names excepting that I don't want them to be removed after closing.
> > Does it is possible?
>
> Looks like tempfile.mkstemp() will do what you want.
>
> '''Unlike TemporaryFile(), the user of mkstemp() is responsible for
> deleting the temporary file when done with it.'''
>
> ~Sean

Thank you, it seems good.
Just another question:

>>> fd, filename = tempfile.mkstemp()
>>> type(fd)


I would expect a file descriptor, not and integer.
How do I have to use it?

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


Re: Puzzled by "is"

2007-08-09 Thread Steve Holden
Dick Moores wrote:
> At 10:46 AM 8/9/2007, Bill Scherer wrote:
>> Dick Moores wrote:
[...]
>> There is only one empty tuple.
>> Does that clear it up for you?
> 
> But isn't that the same as saying, "That's just the reality of 
> Python; it is what it is."? I want to know why there is only one 
> empty tuple, but more than one (1,).
> 
Why? Because.

Seriously, it's just an optimization by the implementers. There is no 
need for more than one empty tuple, since tuples can never be modified 
once created.

But they decided not to create (1, ) in advance. They probably knew that 
hardly anybody would want to create that tuple ;-) [Seriously: if you 
started trying to predict which tuples would be used you would go 
insane, but the empty tuple is the most likely candidate].

> Also,
>  >>> [] is []
> False
> 
In that case it would definitely NOT make sense to have them the same 
list. Python always ensures that the [] constructor creates a new list, 
since that list may be bound to one or more variables and mutated. You 
wouldn't want

   a = []
   b = []
   a.append("boo!")

to change b so it was no longer an empty list. If you wanted a and b to 
reference the same list you would change the second statement to

   b = a

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: tempfile behavior

2007-08-09 Thread Marc 'BlackJack' Rintsch
On Thu, 09 Aug 2007 12:47:10 -0700, billiejoex wrote:

 fd, filename = tempfile.mkstemp()
 type(fd)
> 
> 
> I would expect a file descriptor, not and integer.
> How do I have to use it?

File descriptors are integers.  It's a low level C thing.  Either use the
low level functions in `os` or open the file with the `filename`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by "is"

2007-08-09 Thread John K Masters
On 15:53 Thu 09 Aug , Steve Holden wrote:
> Dick Moores wrote:
> > At 10:46 AM 8/9/2007, Bill Scherer wrote:
> >> Dick Moores wrote:
> [...]
> >> There is only one empty tuple.
> >> Does that clear it up for you?
> > 
> > But isn't that the same as saying, "That's just the reality of 
> > Python; it is what it is."? I want to know why there is only one 
> > empty tuple, but more than one (1,).
> > 
> Why? Because.
> 
> Seriously, it's just an optimization by the implementers. There is no 
> need for more than one empty tuple, since tuples can never be modified 
> once created.
> 
> But they decided not to create (1, ) in advance. They probably knew that 
> hardly anybody would want to create that tuple ;-) [Seriously: if you 
> started trying to predict which tuples would be used you would go 
> insane, but the empty tuple is the most likely candidate].
> 
> > Also,
> >  >>> [] is []
> > False
> > 
> In that case it would definitely NOT make sense to have them the same 
> list. Python always ensures that the [] constructor creates a new list, 
> since that list may be bound to one or more variables and mutated. You 
> wouldn't want
> 
>a = []
>b = []
>a.append("boo!")
> 
> to change b so it was no longer an empty list. If you wanted a and b to 
> reference the same list you would change the second statement to
> 
>b = a
> 
> regards
>   Steve

OK fiddling around with this and reading the docs I tried:-
a = 'qq' #10 q's
b = 'qq' #10 q's
a is b
true
c = 'q' * 10
c
'qq' #10 q's
d = 'q' * 10
d
'qq' #10 q's
c is d
false

So from what I've read "==" tests for equivalence, "is" tests for identity but
that does not explain the behaviour above.

Regards, John
-- 
War is God's way of teaching Americans geography
Ambrose Bierce (1842 - 1914)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by "is"

2007-08-09 Thread kyosohma
On Aug 9, 2:53 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> Dick Moores wrote:
> > At 10:46 AM 8/9/2007, Bill Scherer wrote:
> >> Dick Moores wrote:
> [...]
> >> There is only one empty tuple.
> >> Does that clear it up for you?
>
> > But isn't that the same as saying, "That's just the reality of
> > Python; it is what it is."? I want to know why there is only one
> > empty tuple, but more than one (1,).
>
> Why? Because.
>
> Seriously, it's just an optimization by the implementers. There is no
> need for more than one empty tuple, since tuples can never be modified
> once created.
>
> But they decided not to create (1, ) in advance. They probably knew that
> hardly anybody would want to create that tuple ;-) [Seriously: if you
> started trying to predict which tuples would be used you would go
> insane, but the empty tuple is the most likely candidate].
>
> > Also,
> >  >>> [] is []
> > False
>
> In that case it would definitely NOT make sense to have them the same
> list. Python always ensures that the [] constructor creates a new list,
> since that list may be bound to one or more variables and mutated. You
> wouldn't want
>
>a = []
>b = []
>a.append("boo!")
>
> to change b so it was no longer an empty list. If you wanted a and b to
> reference the same list you would change the second statement to
>
>b = a
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -

Steve,

I thought you'd probably weigh in on this esoteric matter. Very
illuminating, as usual.

Mike

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


Re: Puzzled by "is"

2007-08-09 Thread Neil Cerutti
On 2007-08-09, John K Masters <[EMAIL PROTECTED]> wrote:
> On 15:53 Thu 09 Aug , Steve Holden wrote:
>> Dick Moores wrote:
>> > At 10:46 AM 8/9/2007, Bill Scherer wrote:
>> >> Dick Moores wrote:
>> [...]
>> >> There is only one empty tuple.
>> >> Does that clear it up for you?
>> > 
>> > But isn't that the same as saying, "That's just the reality of 
>> > Python; it is what it is."? I want to know why there is only one 
>> > empty tuple, but more than one (1,).
>> > 
>> Why? Because.
>> 
>> Seriously, it's just an optimization by the implementers. There is no 
>> need for more than one empty tuple, since tuples can never be modified 
>> once created.
>> 
>> But they decided not to create (1, ) in advance. They probably knew that 
>> hardly anybody would want to create that tuple ;-) [Seriously: if you 
>> started trying to predict which tuples would be used you would go 
>> insane, but the empty tuple is the most likely candidate].
>> 
>> > Also,
>> >  >>> [] is []
>> > False
>> > 
>> In that case it would definitely NOT make sense to have them the same 
>> list. Python always ensures that the [] constructor creates a new list, 
>> since that list may be bound to one or more variables and mutated. You 
>> wouldn't want
>> 
>>a = []
>>b = []
>>a.append("boo!")
>> 
>> to change b so it was no longer an empty list. If you wanted a and b to 
>> reference the same list you would change the second statement to
>> 
>>b = a
>> 
>> regards
>>   Steve
>
> OK fiddling around with this and reading the docs I tried:-
> a = 'qq' #10 q's
> b = 'qq' #10 q's

CPython is full of cute little optimizations, and one of them is
that literal strings less than a certain length are 'interned'.
This makes them very fast to compare for equality, and cheaper to
store (maybe?).

> a is b
> true
> c = 'q' * 10
> c
> 'qq' #10 q's
> d = 'q' * 10
> d
> 'qq' #10 q's
> c is d
> false
>
> So from what I've read "==" tests for equivalence, "is" tests
> for identity but that does not explain the behaviour above.

The 10 q's constructed with string arithmetic were not interned,
because they were not literals.

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


Re: how to get command output using python

2007-08-09 Thread Arnau Sanchez
[EMAIL PROTECTED] escribió:

>> Any non cross-platform module should be avoided unless absolutely necessary.
>>
>> Subprocess is the right module to use.
>>
>> arnau
> 
> You forgot to mention that subprocess replaces commands, so in effect,
> commands is deprecated anyway.

It was implicit :-)

Anyway, these modules ("commands", "popen2", ...) are not officially deprecated 
(at least in 2.5), so it's not strange that newcomers sometimes choose 
(wrongly) 
them.

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


Re: Puzzled by "is"

2007-08-09 Thread Steve Holden
[EMAIL PROTECTED] wrote:
[...]
> 
> Steve,
> 
> I thought you'd probably weigh in on this esoteric matter. Very
> illuminating, as usual.
> 
Thank you!

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Puzzled by "is"

2007-08-09 Thread Grzegorz Słodkowicz
>
> Why? Because.
>
> Seriously, it's just an optimization by the implementers. There is no 
> need for more than one empty tuple, since tuples can never be modified 
> once created.
>
> But they decided not to create (1, ) in advance. They probably knew that 
> hardly anybody would want to create that tuple ;-) [Seriously: if you 
> started trying to predict which tuples would be used you would go 
> insane, but the empty tuple is the most likely candidate].
>   
That's just theorisation but I'd rather expect the interpreter simply 
not to create a second tuple while there already is an identical one. 
This could save some memory if the tuple was large (Although by the same 
token comparison of large tuples can be expensive). Admittedly the empty 
tuple is a special case but then 'Special cases aren't special enough to 
break the rules'.

A bit odd.

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


Gotcha I never ran into before

2007-08-09 Thread Brian Cole
I've been programming in Python for about 6 years now. One of the
features I adore the most is the very useful error messages and stack
traces that make it easy to debug. However, today I ran into a
difficult to trace bug because the stack trace was reporting the
problem in the wrong place.

class Delegator(object):
def __init__(self, obj):
self.obj = obj
def __getattr__(self, attr):
return getattr(self.obj, attr)

class SpecializedDelegator(Delegator):
def get_blah(self):
return ["Returning Blah"].upper()
blah = property(fget=get_blah)

print SpecializedDelegator("Doesn't Matter").blah

The stack trace is:
Traceback (most recent call last):
  File "test.py", line 12, in ?
print SpecializedDelegator("Doesn't Matter").blah
  File "test.py", line 5, in __getattr__
return getattr(self.obj, attr)
AttributeError: 'str' object has no attribute 'blah'

Which is correct, but says nothing about the real problem inside the
get_blah method. Is there a good reason that when a property's fget
function throws an AttributeError that it should fall back on
__getattr__? I would think since the attribute was explicitly defined
as a property the property function should be allowed to fully crash
and burn.

Note: This example is broken up into two classes because that is how I
discovered it. Since both classes were in separate files it added to
the agony of debugging this. Luckily I was making a small incremental
change so I could just back up and figure out what went wrong.

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


Re: Puzzled by "is"

2007-08-09 Thread Erik Max Francis
John K Masters wrote:

> OK fiddling around with this and reading the docs I tried:-
> a = 'qq' #10 q's
> b = 'qq' #10 q's
> a is b
> true
> c = 'q' * 10
> c
> 'qq' #10 q's
> d = 'q' * 10
> d
> 'qq' #10 q's
> c is d
> false
> 
> So from what I've read "==" tests for equivalence, "is" tests for identity but
> that does not explain the behaviour above.

Using the `is` test between non-sentinel immutable objects (e.g., 
integers, floats, strings) is _completely pointless_.  Since immutable 
objects cannot be changed, it is up to the interpreter (and thus can 
vary from version to version and implementation to implementation) 
whether or not to "cache" the objects and reuse them, or whether or not 
to create new ones.  You should never be testing such objects for 
identity (`is`); you should only be testing them for equality (`==`).

The only time it makes sense to use the `is` operator with immutable 
objects is when you're dealing with a sentinel object, e.g., `None`, or 
a custom sentinel object (e.g., `mySentinel = object()`), because that 
is the only time you actually _are_ interested in identity.  All other 
times you are not really interested in identity.

Sample code as above is essentially showing unimportant implementation 
details that should never concern you.  Don't use `is`, use `==`.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Chance favors the trained mind.
-- Louis Pasteur
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >