Re: class property not working in python 2.5.1

2009-02-25 Thread Christian Heimes
Dan Barbus schrieb:
> Hi,
> 
> I have a problem with setting a property to a class instance, in
> python 2.5.1. The property is defined through get and set methods, but
> when I set it, the setter doesn't get called. Instead, I believe the
> property in the instance gets replaced with a new object (string).
> 
> I have the following code (stripped down from my program):
> 
> class Model():
> def __init__(self, title = ''):
> self._views, self._title = [], None
> self.setTitle(title)

*snip*

Properties don't work correctly on old style classes. You have to
subclass from object in order to get a new style class.

class Model(object):
pass

Christian

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


class property not working in python 2.5.1

2009-02-25 Thread Dan Barbus
Hi,

I have a problem with setting a property to a class instance, in
python 2.5.1. The property is defined through get and set methods, but
when I set it, the setter doesn't get called. Instead, I believe the
property in the instance gets replaced with a new object (string).

I have the following code (stripped down from my program):

class Model():
def __init__(self, title = ''):
self._views, self._title = [], None
self.setTitle(title)

def addView(self, view):
self._views.append(view)
view.onModelUpdated()

def updateViews(self, trigger = None):
for view in self._views:
view.onModelUpdated(trigger)

def getTitle(self):
return self._title
def setTitle(self, t):
#if self.debug:
if self._title != t:
self._title = t
self.updateViews()
title = property(fget=getTitle, fset=setTitle)

# client code:

class CountUpdatesView():
def __init__(self):
self.updates = 0

def onModelUpdated(self, trigger):
self.updates += 1


m = Model('test')
v = CountUpdatesView()
m.addView(v)   # addView calls into v.onModelUpdated() and
  # v.updates will be 1 after this
m.title = 'new title'# Model.setTitle calls into v.onModelUpdated
()
  # and v.updates should become 2
print m._title# should print 'new title'; instead, prints
'test'

When assigning to m.title, v.updates is not changed, and the last line
prints the original value, passed to the constructor.
Am I missing something?

I noticed that if I put m.setTitle('new title') in the client code,
the code works correctly.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PYTHONPATH on Mac 10.5

2009-02-25 Thread Python Nutter
+1 for site packages and standard shebang, still lets you launch with
python first followed by .py file or  followed by .py file

also for some clues, just open up a terminal in your Mac OS X computer
and check out your exports your PATH will be different depending on
all the software and development environments you may or may not be
using on your Mac, in particular:

declare -x 
PATH="/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin"

declare -x PYTHONSTARTUP="/Users/pythonnutter/.pythonstartup"

for the ultra curious, my custom python startup:

$cat .pythonstartup
# python startup file
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter



On Windows you don't have much control in standard batch files but the
way I keep my Windows box (at work mind you, none at home)
multi-python'd

is I configure the environment for Framework 2.5.4, and all the path
environment variables are configured for the standard directory and
the scripts subdirectory.

in 25's scripts is go26.bat which just pre-pends the 2.6.1 path on the
head of PATH, and of course a go3.bat that pre-pends in 3.0.1

if you want to get fancy, since there is no pop in batch files that I
know of, you could drop a .py script in to read in PATH, pop off two
entries and modify the environment PATH so you fall back down the tree
(might need some list reversing in there to finish the massaging for
pops)

most times I get by with just exiting the terminal session in windows
and a new cmd session will once again take on the defaults for 2.5.4
--
http://mail.python.org/mailman/listinfo/python-list


Re: Queries

2009-02-25 Thread Gary Herron

mmcclaf wrote:

I have to make  some queries for 4 tables I have. The following
relations are:

Classes(class, type, country, numGuns, bore, displacement)
Ships (name, class, launched)
Battles (name, date)
Outcomes (ship, battle, result)

The three queries I'm stuck on are the following:

1. Find the classes that have only one ship as a member of that class
(not all ships are listed in the Ship table)
2. Find the countries that had both battleships and battlecruisers
(those fall under type in Classes)
3. Find those ships that "lived to fight another day"; they were
damaged in one battle, but later fought in another.

The best way for me to understand would be relational algebra for each
of the statements.
  



Sounds like a homework assignment.Good luck with it.



Any help in this would be greatly appreciated.
--
http://mail.python.org/mailman/listinfo/python-list
  


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


Re: XML Parsing

2009-02-25 Thread hrishy
Hi Cliff

Thanks so using elementree is the right way to handle this problem

regards
Hrishy


--- On Wed, 25/2/09, J. Clifford Dyer  wrote:

> From: J. Clifford Dyer 
> Subject: Re: XML Parsing
> To: hris...@yahoo.co.uk
> Cc: python-list@python.org, "Lie Ryan" 
> Date: Wednesday, 25 February, 2009, 12:37 PM
> Probably because you responded an hour after the question
> was posted,
> and in the dead of night.  Newsgroups often move slower
> than that.  But
> now we have posted a solution like that, so all's well
> in the world.  :)
> 
> Cheers,
> Cliff
> 
> 
> On Wed, 2009-02-25 at 08:20 +, hrishy wrote:
> > Hi Lie
> > 
> > I am not a python guy but very interested in the
> langauge and i consider the people on this list to be
> intelligent and was wundering why you people did not suggest
> xpath for this kind of a problem just curious and willing to
> learn.
> > 
> > I am searching for a answer but the question is 
> > why not use xpath to extract xml text from a xml doc ?
> > 
> > regards
> > Hrishy
> > 
> > 
> > --- On Wed, 25/2/09, Lie Ryan
>  wrote:
> > 
> > > From: Lie Ryan 
> > > Subject: Re: XML Parsing
> > > To: python-list@python.org
> > > Date: Wednesday, 25 February, 2009, 7:33 AM
> > > Are you searching for answer or searching for
> another people
> > > that have 
> > > the same answer as you? :)
> > > 
> > > "Many roads lead to Rome" is a very
> famous
> > > quotation...
> > > 
> > > --
> > >
> http://mail.python.org/mailman/listinfo/python-list
> > 
> > 
> >   
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >


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


Re: XML Parsing

2009-02-25 Thread hrishy
Ha the guru himself responding :-)


--- On Wed, 25/2/09, Paul McGuire  wrote:

> From: Paul McGuire 
> Subject: Re: XML Parsing
> To: python-list@python.org
> Date: Wednesday, 25 February, 2009, 2:04 PM
> On Feb 25, 1:17 am, hrishy 
> wrote:
> > Hi
> >
> > Something like this
> >
> 
> >
> > Note i am not a python programmer just a enthusiast
> and i was curious why people on the list didnt suggest a
> code like above
> >
> 
> You just beat the rest of us to it - good example of
> ElementTree for
> parsing XML (and I Iearned the '//' shortcut for
> one or more
> intervening tag levels).
> 
> To the OP: if you are parsing XML, I would look hard at the
> modules
> (esp. ElementTree) that are written explicitly for XML,
> before
> considering using regular expressions.  There are just too
> many
> potential surprises when trying to match XML tags -
> presence/absence/
> order of attributes, namespaces, whitespace inside tags, to
> name a
> few.
> 
> -- Paul
> --
> http://mail.python.org/mailman/listinfo/python-list


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


Re: File Path retrieving problem

2009-02-25 Thread John Machin
On Feb 26, 3:16 pm, music24...@gmail.com wrote:
> On Feb 26, 9:03 am, Steve Holden  wrote:
>
>
>
> > music24...@gmail.com wrote:
> > > On Feb 26, 2:35 am, Emile van Sebille  wrote:
> > >> Peter Otten wrote:
> > >>> Maybe it's about access rights?
> > >>> $ mkdir alpha
> > >>> $ touch alpha/beta
> > >>> $ python -c"import os; print os.path.exists('alpha/beta')"
> > >>> True
> > >>> $ chmod u-x alpha
> > >>> $ python -c"import os; print os.path.exists('alpha/beta')"
> > >>> False
> > >>> $
> > >>> I Don't know how this is handled on Windows...
> > >> Here's one way
>
> > >> Microsoft Windows XP [Version 5.1.2600]
> > >> (C) Copyright 1985-2001 Microsoft Corp.
> > >> C:\>mkdir alpha
> > >> C:\>touch alpha\beta  # cygwin at work here...
>
> > >> C:\>python -c"import os; print os.path.exists('alpha/beta')"
> > >> True
>
> > >> C:\>cacls alpha /E /R "Everyone"
> > >> processed dir: C:\alpha
> > >> C:\>cacls alpha /E /R "Users"
> > >> processed dir: C:\alpha
> > >> C:\>cacls alpha /E /R "Administrators"
> > >> processed dir: C:\alpha
>
> > >> C:\>python -c"import os; print os.path.exists('alpha/beta')"
> > >> False
>
> > > Hi,
>
> > > This is the following code which i have used to retrieve the pathname
> > > of a filename given by the user
>
> > >         filename = self.enText.get() # get the text entered in the
> > > text box
> > >         if os.path.exists(filename): # checking if the filename
> > > exists , had replaced it with os.path.exists(os.path.abspath
> > > (filename))
> > >             print os.path.abspath(filename)
> > >         else:
> > >             print "Not found"
>
> > > actually i need to list all the files/folders with the given filename
> > > alongwith path and store it in an CSV file with index.
>
> > > But i am unable to get even a single filepath correctly.
> > > Whatever filename i enter the output is as : C:\Python25\WorkSpace
> > > \xyz
> > > i.e the name i entered is being appended to my workspace and
> > > displayed.
> > > Guys, i am not able to understand what shall i do here...plz help me
> > > out.
>
> > Look, we aren't psychic. We can't debug code and directories we can't
> > see. Work with us here - give us the information we need to help you.
>
> > The actual code. A directory listing? Any error messages?
>
> > regards
> >  Steve
> > --
> > Steve Holden        +1 571 484 6266   +1 800 494 3119
> > Holden Web LLC              http://www.holdenweb.com/
>
> Hi Steve,
>
> Following is the code which i have written to display a GUI textbox
> and get any name entered by the user and search the path of this
> filename and then list it into an CSV file.
>
> For this i initially created an textbox widget and added an button to
> it.
> Now, i have entered a filename (like NEWS.txt) in the text boz,
> as you can see when i press the button i retrieve the text and then
> search its filepath.
> currently i am printing this filepath on the shell.
>
> from Tkinter import *
> import os
> from os.path import realpath, exists, abspath
> import tkMessageBox
> import Tkinter
> #import filePath
>
> class GUIFrameWork(Frame):
>     """This is the GUI"""
>
>     def __init__(self,master=None):
>         """Initialize yourself"""
>
>         """Initialise the base class"""
>         Frame.__init__(self,master)
>
>         """Set the Window Title"""
>         self.master.title("Enter Text to search")
>
>         """Display the main window"
>         with a little bit of padding"""
>         self.grid(padx=10,pady=10)
>         self.CreateWidgets()
>
>     def CreateWidgets(self):
>
>         self.enText = Entry(self)
>         self.enText.grid(row=0, column=1, columnspan=3)
>
>         """Create the Button, set the text and the
>         command that will be called when the button is clicked"""
>         self.btnDisplay = Button(self, text="Display!",
> command=self.Display)
>         self.btnDisplay.grid(row=0, column=4)
>
>     def Display(self):
>         """Called when btnDisplay is clicked, displays the contents of
> self.enText"""
>         filename = self.enText.get()

Add some more code in here:
   print "filename", repr(filename)
   cwd = os.getcwd()
   print "cwd", cwd
   abspath = os.path.abspath(filename)
   print "abspath", repr(abspath)
   exists = os.path.exists(abspath)
   print "exists", exists
and copy/paste the output into your reply.
Also tell us the name of the folder that the file allegedly exists in,
with a folder listing to prove it.
Also show us the result of using the ATTRIB command on your file, like
in the following examples:

C:\junk>attrib c:\io.sys
   SHR C:\IO.SYS

C:\junk>attrib c:\python26\python.exe
A  C:\python26\python.exe

Again, use copy/paste in your reply.


>         if os.path.exists(os.path.abspath(filename)):
>             print os.path.abspath(filename)
>         else:
>             print "Not found"
>         #tkMessageBox.showinfo("Text", "You typed: %s" %
> os.path.abspath(os.path.dirname(filename)))
>
>         #filepath.mydir(self.en

Re: File Path retrieving problem

2009-02-25 Thread music24by7
On Feb 26, 9:03 am, Steve Holden  wrote:
> music24...@gmail.com wrote:
> > On Feb 26, 2:35 am, Emile van Sebille  wrote:
> >> Peter Otten wrote:
> >>> Maybe it's about access rights?
> >>> $ mkdir alpha
> >>> $ touch alpha/beta
> >>> $ python -c"import os; print os.path.exists('alpha/beta')"
> >>> True
> >>> $ chmod u-x alpha
> >>> $ python -c"import os; print os.path.exists('alpha/beta')"
> >>> False
> >>> $
> >>> I Don't know how this is handled on Windows...
> >> Here's one way
>
> >> Microsoft Windows XP [Version 5.1.2600]
> >> (C) Copyright 1985-2001 Microsoft Corp.
> >> C:\>mkdir alpha
> >> C:\>touch alpha\beta  # cygwin at work here...
>
> >> C:\>python -c"import os; print os.path.exists('alpha/beta')"
> >> True
>
> >> C:\>cacls alpha /E /R "Everyone"
> >> processed dir: C:\alpha
> >> C:\>cacls alpha /E /R "Users"
> >> processed dir: C:\alpha
> >> C:\>cacls alpha /E /R "Administrators"
> >> processed dir: C:\alpha
>
> >> C:\>python -c"import os; print os.path.exists('alpha/beta')"
> >> False
>
> > Hi,
>
> > This is the following code which i have used to retrieve the pathname
> > of a filename given by the user
>
> >         filename = self.enText.get() # get the text entered in the
> > text box
> >         if os.path.exists(filename): # checking if the filename
> > exists , had replaced it with os.path.exists(os.path.abspath
> > (filename))
> >             print os.path.abspath(filename)
> >         else:
> >             print "Not found"
>
> > actually i need to list all the files/folders with the given filename
> > alongwith path and store it in an CSV file with index.
>
> > But i am unable to get even a single filepath correctly.
> > Whatever filename i enter the output is as : C:\Python25\WorkSpace
> > \xyz
> > i.e the name i entered is being appended to my workspace and
> > displayed.
> > Guys, i am not able to understand what shall i do here...plz help me
> > out.
>
> Look, we aren't psychic. We can't debug code and directories we can't
> see. Work with us here - give us the information we need to help you.
>
> The actual code. A directory listing? Any error messages?
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/





Hi Steve,

Following is the code which i have written to display a GUI textbox
and get any name entered by the user and search the path of this
filename and then list it into an CSV file.

For this i initially created an textbox widget and added an button to
it.
Now, i have entered a filename (like NEWS.txt) in the text boz,
as you can see when i press the button i retrieve the text and then
search its filepath.
currently i am printing this filepath on the shell.


from Tkinter import *
import os
from os.path import realpath, exists, abspath
import tkMessageBox
import Tkinter
#import filePath

class GUIFrameWork(Frame):
"""This is the GUI"""

def __init__(self,master=None):
"""Initialize yourself"""

"""Initialise the base class"""
Frame.__init__(self,master)

"""Set the Window Title"""
self.master.title("Enter Text to search")

"""Display the main window"
with a little bit of padding"""
self.grid(padx=10,pady=10)
self.CreateWidgets()

def CreateWidgets(self):

self.enText = Entry(self)
self.enText.grid(row=0, column=1, columnspan=3)



"""Create the Button, set the text and the
command that will be called when the button is clicked"""
self.btnDisplay = Button(self, text="Display!",
command=self.Display)
self.btnDisplay.grid(row=0, column=4)

def Display(self):
"""Called when btnDisplay is clicked, displays the contents of
self.enText"""
filename = self.enText.get()
if os.path.exists(os.path.abspath(filename)):
print os.path.abspath(filename)
else:
print "Not found"
#tkMessageBox.showinfo("Text", "You typed: %s" %
os.path.abspath(os.path.dirname(filename)))

#filepath.mydir(self.enText.get())


if __name__ == "__main__":
guiFrame = GUIFrameWork()
guiFrame.mainloop()





User Input: NEWS.txt
Output: Not Found (though this file is actually present)




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


Queries

2009-02-25 Thread mmcclaf
I have to make  some queries for 4 tables I have. The following
relations are:

Classes(class, type, country, numGuns, bore, displacement)
Ships (name, class, launched)
Battles (name, date)
Outcomes (ship, battle, result)

The three queries I'm stuck on are the following:

1. Find the classes that have only one ship as a member of that class
(not all ships are listed in the Ship table)
2. Find the countries that had both battleships and battlecruisers
(those fall under type in Classes)
3. Find those ships that "lived to fight another day"; they were
damaged in one battle, but later fought in another.

The best way for me to understand would be relational algebra for each
of the statements.

Any help in this would be greatly appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Path retrieving problem

2009-02-25 Thread Steve Holden
music24...@gmail.com wrote:
> On Feb 26, 2:35 am, Emile van Sebille  wrote:
>> Peter Otten wrote:
>>> Maybe it's about access rights?
>>> $ mkdir alpha
>>> $ touch alpha/beta
>>> $ python -c"import os; print os.path.exists('alpha/beta')"
>>> True
>>> $ chmod u-x alpha
>>> $ python -c"import os; print os.path.exists('alpha/beta')"
>>> False
>>> $
>>> I Don't know how this is handled on Windows...
>> Here's one way
>>
>> Microsoft Windows XP [Version 5.1.2600]
>> (C) Copyright 1985-2001 Microsoft Corp.
>> C:\>mkdir alpha
>> C:\>touch alpha\beta  # cygwin at work here...
>>
>> C:\>python -c"import os; print os.path.exists('alpha/beta')"
>> True
>>
>> C:\>cacls alpha /E /R "Everyone"
>> processed dir: C:\alpha
>> C:\>cacls alpha /E /R "Users"
>> processed dir: C:\alpha
>> C:\>cacls alpha /E /R "Administrators"
>> processed dir: C:\alpha
>>
>> C:\>python -c"import os; print os.path.exists('alpha/beta')"
>> False
> 
> Hi,
> 
> This is the following code which i have used to retrieve the pathname
> of a filename given by the user
> 
> filename = self.enText.get() # get the text entered in the
> text box
> if os.path.exists(filename): # checking if the filename
> exists , had replaced it with os.path.exists(os.path.abspath
> (filename))
> print os.path.abspath(filename)
> else:
> print "Not found"
> 
> actually i need to list all the files/folders with the given filename
> alongwith path and store it in an CSV file with index.
> 
> But i am unable to get even a single filepath correctly.
> Whatever filename i enter the output is as : C:\Python25\WorkSpace
> \xyz
> i.e the name i entered is being appended to my workspace and
> displayed.
> Guys, i am not able to understand what shall i do here...plz help me
> out.
> 
Look, we aren't psychic. We can't debug code and directories we can't
see. Work with us here - give us the information we need to help you.

The actual code. A directory listing? Any error messages?

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: File Path retrieving problem

2009-02-25 Thread music24by7
On Feb 26, 2:35 am, Emile van Sebille  wrote:
> Peter Otten wrote:
> > Maybe it's about access rights?
>
> > $ mkdir alpha
> > $ touch alpha/beta
> > $ python -c"import os; print os.path.exists('alpha/beta')"
> > True
> > $ chmod u-x alpha
> > $ python -c"import os; print os.path.exists('alpha/beta')"
> > False
> > $
>
> > I Don't know how this is handled on Windows...
>
> Here's one way
>
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
> C:\>mkdir alpha
> C:\>touch alpha\beta  # cygwin at work here...
>
> C:\>python -c"import os; print os.path.exists('alpha/beta')"
> True
>
> C:\>cacls alpha /E /R "Everyone"
> processed dir: C:\alpha
> C:\>cacls alpha /E /R "Users"
> processed dir: C:\alpha
> C:\>cacls alpha /E /R "Administrators"
> processed dir: C:\alpha
>
> C:\>python -c"import os; print os.path.exists('alpha/beta')"
> False

Hi,

This is the following code which i have used to retrieve the pathname
of a filename given by the user

filename = self.enText.get() # get the text entered in the
text box
if os.path.exists(filename): # checking if the filename
exists , had replaced it with os.path.exists(os.path.abspath
(filename))
print os.path.abspath(filename)
else:
print "Not found"

actually i need to list all the files/folders with the given filename
alongwith path and store it in an CSV file with index.

But i am unable to get even a single filepath correctly.
Whatever filename i enter the output is as : C:\Python25\WorkSpace
\xyz
i.e the name i entered is being appended to my workspace and
displayed.
Guys, i am not able to understand what shall i do here...plz help me
out.


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


Re: Using cPickle

2009-02-25 Thread mmcclaf
Thanks! All fixed!
--
http://mail.python.org/mailman/listinfo/python-list


thread safe to lock on key,val pairs on a dict instead of entire dict?

2009-02-25 Thread birdsong
Dictionaries just store references to objects, right?  So is it thread
safe to lock a specific key/val pair on a dictionary and modify its
val and release the lock?

example snippet:
# assuming d_lock  was initialized long ago in a thread-safe manner
d_lock.acquire()
d = {}
d[1] = (threading.Lock(), [])
d_lock.release()

# test key level locking
for key, data in d.items():
  row_lock, rows = data
  row_lock.acquire()
  rows.append(1)
  row_lock.release()

Of course, I'll have to lock the entire dict when adding keys that
dont exist, but further calls and acquire the key specific lock before
doing any write operations.
--
http://mail.python.org/mailman/listinfo/python-list


Is this the right way to use unicode in a user defined Exception?

2009-02-25 Thread 一首诗
#
class MyError(Exception):
def __init__(self):
self.message = u'Some Chinese:中文'

def __str__(self):
return self.message.encode('utf8')
#

This is an exception that I defined.   I have to pass it to third
party libraries.

As many libraries simply use str(e) to log, if I don't encode it in
__str___, they will fail.

But I am not quite certain if it's the right thing to do.   Shouldn't
every library expect to use unicode everywhere?

Shouldn't they use something like :

log(unicode(e))
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Battleship" style game

2009-02-25 Thread Zvezdan Petkovic

On Feb 25, 2009, at 3:54 PM, Shawn Milochik wrote:

It is true that it would be fewer lines of code with the same
functionality, but it's better practice to have that framework in
place so that any changes made in the future wouldn't break any of the
code accessing my class. Obviously this is a fairly simple game that
has a fixed set of rules, but I'm trying to cultivate good habits, and
I don't think that doing it this way is anti-Pythonic.


Well, they are trying to help you with the best practices.
You offered the code for review and they reviewed it.
Whether you'll accept what they say or deny it is your call, of course.

FWIW, the Pythonic way would be:

>>> class Ship(object):
... def __init__(self, length):
... self._length = length
... @property
... def length(self):
... return self._length
...
>>> s = Ship(5)
>>> s.length
5
>>> # notice how the property is read-only which is what you wanted
>>> s.length = 7
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: can't set attribute
>>> ^D

Using @property decorator makes a read-only property.  If you need a  
read/write property there are several ways to define setter and  
deleter methods with or without decorators.


I hope you see that

x = s.length
s.position = y

is a completely different style than

x = s.get_length()
s.set_position(y)

Most of the people who program in Python prefer the first style above.

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


Re: Python Image Library IOError - cannot find JPEG decoder?

2009-02-25 Thread Zvezdan Petkovic

On Feb 24, 9:34 am, Dario Traverso  wrote:

I've been trying to install the Python Image Library  (PIL) on my Mac
OSX Leopard laptop, but have been running into some difficulties.
...
I've followed all of the installation instructions exactly. The build
summary reported everything was "ok". What could be the problem here.
Libjpeg-6b  is not accessible?
That would be my guess.



It could be something obvious and something you have done, but it's  
worth asking:


1. Do you have the path to fink binaries, such as djpeg,
   in your shell PATH (e.g., /opt/local/bin for MacPorts)?

2. Did you set up the path to the libraries you linked with in the
   environment variable DYLD_LIBRARY_PATH?
   For example, DYLD_LIBRARY_PATH=/opt/local/lib for MacPorts

3. Did you execute your app with this variable available.

   $ env DYLD_LIBRARY_PATH=/opt/local/lib your-app

   Once you confirm what is missing you can write a Python wrapper
   to call your app with the right environment.

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


Re: variables bound in moudules are None when module is not completely imported

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 21:24:33 -0200,  escribió:

On Wed, Feb 25, 2009 at 05:05:28PM -0200, Gabriel Genellina wrote:



I'd try to move all the global stuff in that module into a function,
"init". Importing the module will always succeed - you have to manually
call init() after importing it.


i normally do that anyway and would also have done so here (afaik, it's
best practice anyway), but this is in this case not possible as the
modules in question are not under my control at all. as pep 299 has been
turned down, this can't really be considered a bug of those files.


You might ask the module author for this feature... At least, try to move  
the "registration" at the end, after any code likely to raise exceptions.



anyway, it would just be another workaround around the globals
disappearing.


That makes a strange situation where the module doesn't exist in
sys.modules but its globals are still alive...


is this a known bug?


Not that I know.


i mean from a garbage collection / refcount point
of view, at least everything that is still referenced somewhere should
be preserved.


In older Python versions, an error when importing a module could leave a  
module object in sys.module partially initialized. That's very bad! Now,  
the entry in sys.modules is removed in such cases. Note that functions and  
classes defined inside a module don't have a reference to the module  
itself - their __module__ attribute is a string (although functions *do*  
have a reference to the module namespace, as you have remarked). So the  
entry in sys.modules is likely to be the last and only reference, and when  
it's removed, the module is deleted. This is a very tricky operation and  
at some stage involves setting all globals to None; if not were for any  
external references (like a callback registered somewhere else, as in your  
case) the module plus the functions and classes and objects defined inside  
it plus its global namespace, all of these should disappear, kaput, gone.


You should report it at http://bugs.python.org -- I don't think this is  
likely to be "fixed" now, but at least it's on record. And when someone  
attempts to improve the module destruction sequence, there is a better  
chance this is taken into account too.


--
Gabriel Genellina

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


Re: pep 8 constants

2009-02-25 Thread Rhodri James
On Wed, 25 Feb 2009 08:48:27 -, Bruno Desthuilliers  
 wrote:



Ben Finney a écrit :
(snip - about using ALL_CAPS for pseudo-constants)

Perhaps I'd even
argue for an update to PEP 8 that endorses this as conventional.


+1

I've been a bit surprised last time I checked PEP8 to find out this  
wasn't already the case - I would have sweared it was.


It is.  Aahz added it a few weeks ago.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: reading file to list

2009-02-25 Thread Xah Lee
On Feb 25, 10:18 am, Xah Lee  wrote:
> On Feb 25, 3:34 am, nick_keighley_nos...@hotmail.com wrote:
>
> > the nasty cons then only appears in a single function which
> > you can hide in a library
>
> I think the following answers that.
>
> Q: If you don't like cons, lisp has arrays and hashmaps, too.
>
> A: Suppose there's a lang called gisp. In gisp, there's cons but also
> fons. Fons are just like cons except it has 3 cells with 3 accessors:
> car, cbr, cdr. Now, gisp is a old lang, the fons are deeply rooted in
> the lang. Every some 100 lines of code you'll see a use of fons with
> its extra accessor cbr, or any one of the cbaar, cdabr, cbbar, cbbbar,
> etc. You got annoyed by this. You as a critic, complains that fons is
> bad. But then some gisp fanatics retorts: “If you don't like fons,
> gisp has cons, too!”.
>
> You see, by “having something too”, does not solve the problem of
> pollution. Sure, you can use just cons in gisp, but every lib or
> other's code you encounter, there's a invasion of fons with its cbar,
> cbbar, cbbbar. The problem created by fons does not go away by “having
> cons too”.
>
> above is from
>
> • Fundamental Problems of Lisp
>  http://xahlee.org/UnixResource_dir/writ/lisp_problems.html
>
> -
>
> > I read it. Your point seems to be "cons becomes difficult
> > with deeply nested structures". Could you give an example?
>
> There are few examples in these articles:
>
> • The Concepts and Confusions of Prefix, Infix, Postfix and Fully
> Nested Notations
>  http://xahlee.org/UnixResource_dir/writ/notations.html
>
> the above, 3rd section, gives detail about the problems of fully
> nested syntax. In particular, it shows a source code snippet of
> language with fully nested syntax, but is not lisp, so that lispers
> can get a fresh impression.
>
> • A Ruby Illustration of Lisp Problems
>  http://xahlee.org/UnixResource_dir/writ/lisp_problems_by_ruby.html
>
> the above, is a concrete example of showing how full nesting is
> cumbersome, by constrasting a simple program in Ruby and lisp.
>
> • Why Lisp Do Not Have A Generic Copy-List Function
>  http://xahlee.org/UnixResource_dir/writ/lisp_equal_copy_list.html
>
> the above, shows the cons problem, by looking Kent Pitman's article
> with a different perspective.
>
> A short Plain Text Excerpt of the ruby article cited above follows.
> --
>
> More specifically, 2 fundamental problems of lisp i feel this ruby
> example illustrates well:
>
> • the cons impedes many aspects of lists. e.g. difficult to learn,
> confusing, hard to use, prevent development of coherent list
> manipulation functions.
>
> • nested syntax impedes the functional programing paradigm of function
> chaining, esp when each function has 2 or more arguments (e.g. map).
>
> here's a short summary of the nesting problem:
>
> (map f x) ; 1 level of chaining
> (map g (map f x)) ; 2 levels
> (map h (map g (map f x))) ; 3 levels
>
> compare:
>
> x | f | g | h   > unix pipe
> x // f // g // h   > Mathematica
> h @ g @ f @ x> Mathematica
> x.f.g.h---> various OOP langs, esp Ruby, javascript
> h g f x   ---> some functional langs, Haskell, Ocaml
>
> The way the above works is that each of f, g, h is a lambda themselves
> that maps. (that is, something like “(lambda (y) (map f y))”)
>
> Note, that any of the f, g, h may be complex pure functions (aka
> lambda).  Because in lisp, each lambda itself will in general have
> quite a lot nested parens (which cannot be avoided), so this makes any
> chaining of functions of 2 args, for more than 2 or 3 levels of
> nesting, unusable for practical coding. One must define the functions
> separately and just call their names, or use function composition with
> lambda (which gets complex quickly). One major aspect of this problem
> is that the scope of vars becomes hard to understand in the deep
> nested source code. This is worse in elisp, because emacs is
> dynamically scoped, so you have to avoid using var of same name.


Here's a actual lisp code. I don't consider it readable, due to the
profusion of parens.

(defun lisp-complete-symbol (&optional predicate)
  "Perform completion on Lisp symbol preceding point.
Compare that symbol against the known Lisp symbols.
If no characters can be completed, display a list of possible
completions.
Repeating the command at that point scrolls the list.

When called from a program, optional arg PREDICATE is a predicate
determining which symbols are considered, e.g. `commandp'.
If PREDICATE is nil, the context determines which symbols are
considered.  If the symbol starts just after an open-parenthesis, only
symbols with function definitions are considered.  Otherwise, all
symbols with function definitions, values or properties are
considered."
  (interactive)
  (let ((window (get-buffer-window "*Completions*" 0)))
(if (and (eq last-command this-command)
 window (window-live-p window) (window-buffer window)
 

Re: PYTHONPATH on Mac 10.5

2009-02-25 Thread Philip Semanchuk


On Feb 25, 2009, at 3:20 PM, Vincent Davis wrote:


I have looked around for a good howto setup PYTHONPATH on Mac os x
10.5 Although I get many results I am not sure which is correct. I  
am not
sure if it is different for 10.5 over previous versions. Does anyone  
know of

a well documented set of instructions.

Is there a way to specify a module location or working directory?  
Which is

best? Or should I just add location to PYTHONPATH?



Hi Vincent,
There are different instructions on how to set PYTHONPATH because it  
solves a problem (how to organize one's Python modules) that has more  
than one solution. It's sort of like asking "How should I organize my  
email?" Different strokes for different folks.


Me, I don't use PYTHONPATH at all. Most of the stuff I want to import  
is already available in site-packages. If not, I can add a .pth file  
to site-packages that tells Python where to find the source. You can  
read about .pth files here:

http://docs.python.org/library/site.html



In my python scripts I specify which python I want to use like this
#!/Library/Frameworks/Python.framework/Versions/4.1.30101/bin/python


Yikes! Your scripts won't be too portable then, will they? I'm on OS X  
10.5 and I don't have a directory like that. A common, more portable  
alternative is this:


#!/usr/bin/env python

That relies (obviously) on /usr/bin/env being present which means that  
your scripts won't work on Windows machines, for instance. But it's a  
whole lot more portable than what you've got now. You don't need a  
shebang line at all if you're willing to launch your scripts by typing  
`python foo.py` at the command line. That will merely execute  
whichever python appears first in your path. I used to always use the / 
usr/bin/env shebang line that I described above, but I do so less  
often now. It's one less dependency to deal with.


So, in short, PYTHONPATH doesn't need to be set at all, and you can  
switch the shebang line to this:


#!/usr/bin/env python

Or do away with it entirely.

This isn't a complete answer but has it been at least somewhat helpful?

Cheers
Philip






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


Re: This application has failed to start because the application configuration is incorrect

2009-02-25 Thread Mark Hammond

On 26/02/2009 4:51 AM, Lorenzo wrote:


PS: Mark, this could be added to a kind of "Deployment" entry in
py2exe wiki, it would be useful.


IIRC, I've never edited the py2exe wiki (despite appearances to the 
contrary sometimes, I don't formally maintain that package!).


But that is the cool thing about Wiki's - *anyone* can add such 
information ;)


Cheers,

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


logging.Handler not working with QThreads

2009-02-25 Thread Lukas Hetzenecker
Hello,

I created a QTextEdit where I wanted to display log messages.
A logging.Handler should do this job.

It worked with one thread well, but when I start a QThread the text on all 
widgets is removed and I get many errors in my konsole:

X Error: RenderBadGlyphSet (invalid GlyphSet parameter) 177
  Extension:152 (RENDER)
  Minor opcode: 25 (RenderCompositeGlyphs32)
  Resource id:  0x0
X Error: RenderBadGlyphSet (invalid GlyphSet parameter) 177
  Extension:152 (RENDER)
  Minor opcode: 25 (RenderCompositeGlyphs32)
  Resource id:  0x0
X Error: RenderBadGlyphSet (invalid GlyphSet parameter) 177
  Extension:152 (RENDER)
  Minor opcode: 25 (RenderCompositeGlyphs32)
  Resource id:  0x0

.. and so on

I attatched a small example to this mail.

Could anybody tell me what I'm doing wrong?
Thanks for you help,
Lukas


from PyQt4.QtCore import *
from PyQt4.QtGui import *
import logging

class QtStreamHandler(logging.Handler):
def __init__(self,  parent,  main):
logging.Handler.__init__(self)
self.parent = parent
self.main = main

self.textWidget = parent
self.formater = logging.Formatter("%(message)s")

def createLock(self):
self.mutex = QMutex()

def acquire(self):
self.mutex.lock()

def release(self):
self.mutex.unlock()

def emit(self,record):
self.textWidget.appendPlainText(self.formater.format(record))
self.textWidget.moveCursor(QTextCursor.StartOfLine)
self.textWidget.ensureCursorVisible()

class Log(QDialog):
def __init__(self, parent, main):
super(Log,  self).__init__(parent)

self.parent = parent
self.main = main

self.layout = QVBoxLayout(self)
self.logEdit = QPlainTextEdit(self)
self.logEdit.setLineWrapMode(QPlainTextEdit.NoWrap)
self.logEdit.setReadOnly(True)
self.button = QPushButton(self)
self.button.setText("Message")
self.layout.addWidget(self.logEdit)
self.layout.addWidget(self.button)

self.connect(self.button, SIGNAL("clicked()"), self.message)

self.show()

def message(self):
   self.main.log.error("Log window")

class MainWindow(QDialog):
   def __init__(self, parent, main):
  super(MainWindow, self).__init__()

  self.parent = parent
  self.main = main

  self.layout = QVBoxLayout(self)
  self.check = QCheckBox(self)
  self.check.setText("Foobar")
  self.combo = QComboBox(self)
  self.combo.addItem("")
  self.combo.addItem("")
  self.button = QPushButton(self)
  self.button.setText("Start Thread")
  self.button2 = QPushButton(self)
  self.button2.setText("Message")
  self.layout.addWidget(self.check)
  self.layout.addWidget(self.combo)
  self.layout.addWidget(self.button)
  self.layout.addWidget(self.button2)

  self.connect(self.button, SIGNAL("clicked()"), self.startThread)
  self.connect(self.button2, SIGNAL("clicked()"), self.message)

  self.show()

   def startThread(self):
  self.thread = Thread(self, self.main)
  self.connect(self.thread, SIGNAL("finished()"), lambda : self.main.log.error("Thread finished"))
  self.thread.start()

   def message(self):
  self.main.log.error("Main window")

class Thread(QThread):
   def __init__(self, parent, main):
  super(Thread, self).__init__(parent)
  self.log = main.log

   def run(self):
  self.log.info("Thread...")

class Main(QObject):
   def __init__(self):
  super(Main,  self).__init__()
  logger = logging.getLogger("series60-remote")
  logger.setLevel(logging.DEBUG)
  self.logWindow = Log(None,  self)
  dialogHandler = QtStreamHandler(self.logWindow.logEdit,  self)
  logger.addHandler(dialogHandler)
  self.logWindow.show()
  self.log = logger
  self.window = MainWindow(None, self)

app = QApplication([])
main = Main()
app.exec_()
--
http://mail.python.org/mailman/listinfo/python-list


Re: variables bound in moudules are None when module is not completely imported

2009-02-25 Thread chrysn
On Wed, Feb 25, 2009 at 05:05:28PM -0200, Gabriel Genellina wrote:
> I'd try to move all the global stuff in that module into a function,  
> "init". Importing the module will always succeed - you have to manually  
> call init() after importing it.

i normally do that anyway and would also have done so here (afaik, it's
best practice anyway), but this is in this case not possible as the
modules in question are not under my control at all. as pep 299 has been
turned down, this can't really be considered a bug of those files.

anyway, it would just be another workaround around the globals
disappearing.

> That makes a strange situation where the module doesn't exist in  
> sys.modules but its globals are still alive...

is this a known bug? i mean from a garbage collection / refcount point
of view, at least everything that is still referenced somewhere should
be preserved.

thanks
chrysn

-- 
To use raw power is to make yourself infinitely vulnerable to greater powers.
  -- Bene Gesserit axiom


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: python sql query in django

2009-02-25 Thread Diez B. Roggisch


for a introduction to the multitude of query-options. I doubt that your 
rather simple m:n-relationship is covered there.


s/is/isn't/

Diez

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


Re: python sql query in django

2009-02-25 Thread Diez B. Roggisch

I think Django is fabulous for the admin-interface, a simple text
search and template inheritance.  I will use Django for all of those.
What I'm not getting an answer to and cannot find an example of is a
complex search, where I have to retrieve data from multiple tables,
combine the data, remove the duplicates, etc between a web page and
the database.  The code that started this thread is only a small piece
of the complex data retrieval I need to do.  PHP is great for writing
complex SQL queries right in the HTML template and I know exactly what
it is doing.


First of all, mixing technologies without need is most of the times a 
bad idea - so if it is really the case that you can't solve all of your 
issues in django, you shouldn't use it at all, but solve them in PHP.



But to be honest - I doubt that django isn't capable of solving your 
problem.


See

http://docs.djangoproject.com/en/dev/topics/db/queries/#topics-db-queries

for a introduction to the multitude of query-options. I doubt that your 
rather simple m:n-relationship is covered there.



I myself use SQLAlchemy, and that can for sure query and filter those 
relationships.


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


Re: variable length tuple assignment

2009-02-25 Thread Steven D'Aprano
Tim Chase wrote:

> As an aside, as of the last time I read the PEP[1] on this, I
> believe it exhausts (or attempts to exhaust) any iterator.  IMHO,
> I think this exhausting is a bad idea because it prevents things like
> 
>def numbers(start=0):
>  i = start
>  while True:
>yield i
>i += 1
> 
>CONST_A, CONST_B, CONST_C, *rest = numbers()
> 
> which will hang in current Py3.0 until you blow a stack or
> overrun your heap somewhere because it will try to exhaust the
> infinite loop.  

But what else can it do? Do you expect Python to read your mind and
magically know when you intend to use rest and when you're intending to
just throw it away?

Perhaps Python could do that, via static analysis -- if rest is never used
again, don't bother exhausting the iterator. But that will lead to
differences in iterators that have side-effects. It will also have a subtle
difference in behaviour here:

it = xrange(5)  # for example
a, b, c, *rest = it
L = list(it)  # L is now [3, 4]

versus

a, b, c, *rest = xrange(5)
parrot(rest)
L = list(it)  # L is now []


> It also changes the type from iter() to list() 
> for the remaining content (not as grevious).

But that's what unpacking does. It would be a major semantic change for 

x, *s = some_iterator

to make s an alias of some_iterator. And why would you want it to? If you
do, just do this:

x, s = some_iterator.next(), some_iterator



-- 
Steven

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


Re: "Battleship" style game

2009-02-25 Thread Jean-Paul Calderone

On Wed, 25 Feb 2009 15:54:46 -0500, Shawn Milochik  wrote:

On Wed, Feb 25, 2009 at 3:15 PM, Diez B. Roggisch  wrote:


Not really. The point about properties is that you *can* make attribute
access trigger getter or setter code.

But not that you do unless there is an actual reason for that. The way you
do it now is simply introducing clutter, without benefit. Your class would
be half the current size - without loss of functionality.



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



It is true that it would be fewer lines of code with the same
functionality, but it's better practice to have that framework in
place so that any changes made in the future wouldn't break any of the
code accessing my class. Obviously this is a fairly simple game that
has a fixed set of rules, but I'm trying to cultivate good habits, and
I don't think that doing it this way is anti-Pythonic.

Unless, of course, anything I said is wrong, which is always possible.
If I'm missing a bigger-picture idea, I'd like to know about it.


Much better practice would be writing unit tests for the behavior you
want.  This is a vastly greater measure of protection against future
maintenance introducing bugs than the restrictions you're adding to
your implementation.  So if you're looking for good habits to pick up,
start with unit testing.  Your test.py files show you're at least
thinking about testing, but you should take a look at something like
the `unittest´ module in the standard library and take things to the
next level.

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


Re: [Tutor] Accessing callers context from callee method

2009-02-25 Thread mobiledreamers
i found the solution
This is my first attempt at memcaching html page using cheetah
since cheetah render needs locals() i use getCallerInfo() to get the
locals() and send to memcached
let me know if it is possible to better do this
*notice getCallerInfo
*

*utils.py*
@log_time_func
def renderpage(key, htmlfile, deleteafter=3600):
from globaldb import mc
try:page = mc.get(key)
except:
page=None
clogger.info('except error mc.get '+ key)
if not page:
clogger.info(key+ ' rendering cheetah page')
terms = getCallerInfo(1)
#print terms
page = str(web.render(htmlfile, asTemplate=True, terms=terms))
try:mc.set(key, page, deleteafter)
except:
clogger.info('except error mc.set '+ key)
return page

@log_time_func
@memcachethis
def mcrenderpage(key, htmlfile, deleteafter=3600):
terms = getCallerInfo(2)
#print terms
return str(web.render(htmlfile, asTemplate=True, terms=terms))

def getCallerInfo(decorators=0):
'''returns locals of caller using frame.optional pass number of
decorators\nFrom Dig deep into python internals
http://www.devx.com/opensource/Article/31593/1954'
''
f = sys._getframe(2+decorators)
args = inspect.getargvalues(f)
return args[3]

*Usage*
key=facebookstuff.APP_NAME+'newstart'+str(uid)
return utils.renderpage(key, 'pick.html')



-- 
Bidegg worlds best auction site
http://bidegg.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Image Library IOError - cannot find JPEG decoder?

2009-02-25 Thread OdarR
On 24 fév, 18:34, Dario Traverso  wrote:
> I've been trying to install the Python Image Library  (PIL) on my Mac  
> OSX Leopard laptop, but have been running into some difficulties.
>
> I've built the library, using the included setup.py  script. The build  
> summary checks out ok, and sounds the option libraries to all be  
> found. I grabbed both libjpeg and freetype2  using  fink.

I did'nt build it, maybe you don't want too.
I used the PIL package for Python 2.5 listed here:
http://pythonmac.org/packages/py25-fat/index.html


hth,
Olivier
--
http://mail.python.org/mailman/listinfo/python-list


Re: python sql query in django

2009-02-25 Thread Bruno Desthuilliers

May a écrit :

On Feb 24, 10:36 am, "Diez B. Roggisch"  wrote:

Thanks for all your suggestions.  From what I've experienced in Django
and now that I know a little more about how Python functions, I will
probably use a combination of PHP and Django, instead of trying to get
Python to do the web portion of my project.  Thanks again!

That sounds like the worst idea. Django's ORM is good when used from
within django, because of all the additional goodies like the admin
interface.

But if you are going to do the webfrontend using PHP, what part is left
for django? If it's only the ORM (for whatever you still use that
anyway), there are better alternatives - SQLAlchemy, and SQLObject, for
Python. They are more powerful and not interwoven with django.

If you are going to hand-code the interface in PHP, I fail to see though
why you don't do that in Django directly. You are not forced to use the
Admin-interface.

Diez


Hello Diez,

I think Django is fabulous for the admin-interface, a simple text
search and template inheritance. 


And I think you really don't get what Django is good for.


I will use Django for all of those.
What I'm not getting an answer to and cannot find an example of is a
complex search, where I have to retrieve data from multiple tables,
combine the data, remove the duplicates, etc 


Django's ORM is mostly a wrapper above the db-api. It's intended to make 
most common db access a no-brainer, not to replace full-blown SQL for 
complex things. Now the good news is that you *still* can drop to a 
lower raw-sql level - the one you'd get using either PHP or Python's 
db-api - for more complex things. IOW, PHP won't buy you anything here.



 The code that started this thread is only a small piece
of the complex data retrieval I need to do.


The "code that started this thread" is a total no-brainer using Django 
(as you would know by now if you had reposted your question on django's 
group - or even just read the FineManual, where this use case is fully 
documented), and doesn't even require going down to raw sql.



 PHP is great for writing
complex SQL queries right in the HTML template


What the  a complex SQL query has to do in a template anyway ??? 
Sorry, but what you're saying here is that PHP is great for writing 
unmaintainable spaghetti code. FWIW, even PHP coders are trying to get 
out of this kind of mess nowadays.


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


Re: "Battleship" style game

2009-02-25 Thread Grant Edwards
On 2009-02-25, Diez B. Roggisch  wrote:

> Don't waste time coding for a future you can't even pretend to
> know. Do what is needed to solve the actual problem.

Premature obfuscation is even worse than premature optimization.

-- 
Grant Edwards   grante Yow! Well, O.K.
  at   I'll compromise with my
   visi.comprinciples because of
   EXISTENTIAL DESPAIR!
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Path retrieving problem

2009-02-25 Thread Emile van Sebille

Peter Otten wrote:

Maybe it's about access rights?

$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$

I Don't know how this is handled on Windows...



Here's one way

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>mkdir alpha
C:\>touch alpha\beta  # cygwin at work here...

C:\>python -c"import os; print os.path.exists('alpha/beta')"
True

C:\>cacls alpha /E /R "Everyone"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Users"
processed dir: C:\alpha
C:\>cacls alpha /E /R "Administrators"
processed dir: C:\alpha

C:\>python -c"import os; print os.path.exists('alpha/beta')"
False

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


Re: "Battleship" style game

2009-02-25 Thread Diez B. Roggisch

Shawn Milochik schrieb:

On Wed, Feb 25, 2009 at 3:15 PM, Diez B. Roggisch  wrote:


Not really. The point about properties is that you *can* make attribute
access trigger getter or setter code.

But not that you do unless there is an actual reason for that. The way you
do it now is simply introducing clutter, without benefit. Your class would
be half the current size - without loss of functionality.



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



It is true that it would be fewer lines of code with the same
functionality, but it's better practice to have that framework in
place so that any changes made in the future wouldn't break any of the
code accessing my class. Obviously this is a fairly simple game that
has a fixed set of rules, but I'm trying to cultivate good habits, and
I don't think that doing it this way is anti-Pythonic.

Unless, of course, anything I said is wrong, which is always possible.
If I'm missing a bigger-picture idea, I'd like to know about it.


You miss that Java has no properties, and thus forces prorgammers to 
wrap all attribute-access into getter/setters - just in case one wants 
something other than pure attribute access in some distant future to come.


In Python this is not needed. If something starts as an attribute, and 
then evolves so that it needs more complex logic when being accessed, 
you introduce a property of the same name.



Don't waste time coding for a future you can't even pretend to know. Do 
what is needed to solve the actual problem.



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


Re: "Battleship" style game

2009-02-25 Thread J. Cliff Dyer
On Wed, 2009-02-25 at 15:54 -0500, Shawn Milochik wrote:
> On Wed, Feb 25, 2009 at 3:15 PM, Diez B. Roggisch  wrote:
> 
> > Not really. The point about properties is that you *can* make attribute
> > access trigger getter or setter code.
> >
> > But not that you do unless there is an actual reason for that. The way you
> > do it now is simply introducing clutter, without benefit. Your class would
> > be half the current size - without loss of functionality.
> >
> >
> >
> > Diez
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> 
> It is true that it would be fewer lines of code with the same
> functionality, but it's better practice to have that framework in
> place so that any changes made in the future wouldn't break any of the
> code accessing my class. Obviously this is a fairly simple game that
> has a fixed set of rules, but I'm trying to cultivate good habits, and
> I don't think that doing it this way is anti-Pythonic.
> 
> Unless, of course, anything I said is wrong, which is always possible.
> If I'm missing a bigger-picture idea, I'd like to know about it.
> 

The piece you're missing is exactly why properties are so cool.

They take what looks like attribute access from the client side, and
pass it through a method.  So while you can add any sort of changes you
want to make can be made without breaking any client code.  To them, it
still looks like attribute access.

class Foo(object):
a = 4

class Bar(object):
def __init__(self):
self._a = 4

def _get_a(self):
return self._a

def _set_a(self, value):
if not value % 2:
self._a = value
a = property(_get_a, _set_a)

>>> foo = Foo()
>>> foo.a
4
>>> foo.a = 5
>>> foo.a
5
>>> bar = Bar()
>>> bar.a
4
>>> bar.a = 5
>>> bar.a
4
>>> bar.a = 6
>>> bar.a
6

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

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


Re: "Battleship" style game

2009-02-25 Thread Steve Holden
Shawn Milochik wrote:
> On Wed, Feb 25, 2009 at 3:15 PM, Diez B. Roggisch  wrote:
> 
>> Not really. The point about properties is that you *can* make attribute
>> access trigger getter or setter code.
>>
>> But not that you do unless there is an actual reason for that. The way you
>> do it now is simply introducing clutter, without benefit. Your class would
>> be half the current size - without loss of functionality.
>>
>>
>>
>> Diez
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> 
> It is true that it would be fewer lines of code with the same
> functionality, but it's better practice to have that framework in
> place so that any changes made in the future wouldn't break any of the
> code accessing my class. Obviously this is a fairly simple game that
> has a fixed set of rules, but I'm trying to cultivate good habits, and
> I don't think that doing it this way is anti-Pythonic.
> 
> Unless, of course, anything I said is wrong, which is always possible.
> If I'm missing a bigger-picture idea, I'd like to know about it.
> 
The point of using property() is that you can start out using attribute
access on its own (which is the standard Python way to do things:
getters and setters are seen by most as redundant code).

Once you need programmed access on read and/or write, leave the client
code (the code that accesses the attributes) as it is, but turn the
attributes into properties so that the functions are invoked
automatically on attribute-style access.

So I believe what Diez was saying is that by using properties in your
existing code you are getting the worst of both worlds - unnecessarily
complex objects, and code that uses those objects by calling methods
when it could be accessing attributes (or properties - depending on the
implementation). At least this is true of your Ship test code.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: "Battleship" style game

2009-02-25 Thread Shawn Milochik
On Wed, Feb 25, 2009 at 3:15 PM, Diez B. Roggisch  wrote:

> Not really. The point about properties is that you *can* make attribute
> access trigger getter or setter code.
>
> But not that you do unless there is an actual reason for that. The way you
> do it now is simply introducing clutter, without benefit. Your class would
> be half the current size - without loss of functionality.
>
>
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>

It is true that it would be fewer lines of code with the same
functionality, but it's better practice to have that framework in
place so that any changes made in the future wouldn't break any of the
code accessing my class. Obviously this is a fairly simple game that
has a fixed set of rules, but I'm trying to cultivate good habits, and
I don't think that doing it this way is anti-Pythonic.

Unless, of course, anything I said is wrong, which is always possible.
If I'm missing a bigger-picture idea, I'd like to know about it.

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


Re: Python Image Library IOError - cannot find JPEG decoder?

2009-02-25 Thread Irmen de Jong

wongobongo wrote:

On Feb 24, 9:34 am, Dario Traverso  wrote:
I've been trying to install the Python Image Library  (PIL) on my Mac  
OSX Leopard laptop, but have been running into some difficulties.


I've built the library, using the included setup.py  script. The build  
summary checks out ok, and sounds the option libraries to all be  
found. I grabbed both libjpeg and freetype2  using  fink.




I did a similar thing, but not using Fink, on my mac (running osx 10.4)
I documented the procedure I had to take to get it to work:
http://www.razorvine.net/frog/user/irmen/article/2008-08-02/127

It's in Dutch but you can probably figure it out.
I guess since you were on 10.5 that you have to adapt the
'DEPLOMENT_TARGET' variable in a suitable manner.

Hope it helps,

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


PYTHONPATH on Mac 10.5

2009-02-25 Thread Vincent Davis
I have looked around for a good howto setup PYTHONPATH on Mac os x
10.5 Although I get many results I am not sure which is correct. I am not
sure if it is different for 10.5 over previous versions. Does anyone know of
a well documented set of instructions.
In my python scripts I specify which python I want to use like this
#!/Library/Frameworks/Python.framework/Versions/4.1.30101/bin/python

Is there a way to specify a module location or working directory? Which is
best? Or should I just add location to PYTHONPATH?


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


Re: Python dictionary size/entry limit?

2009-02-25 Thread Martin v. Löwis
>> On a 32-bit system, the dictionary can have up to 2**31 slots,
>> meaning that the maximum number of keys is slightly smaller
>> (about 2**30).
> 
> Which, in practice, means that the size is limited by the available memory.

Right. Each slot takes 12 bytes, so the storage for the slots alone
would consume all available address space.

>From that point of view, you can't possibly have more than 314M slots
in a 32-bit address space (roughly 2**28).

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


Re: "Battleship" style game

2009-02-25 Thread Diez B. Roggisch

Shawn Milochik schrieb:

Thanks. I wasn't aware of the property() function, but I read up on
it. I modified the Vessels.py file, but not the board file (except
where necessary to handle the changes made to Vessels. Is this better?

http://shawnmilo.com/ships/ships2/



Not really. The point about properties is that you *can* make attribute 
access trigger getter or setter code.


But not that you do unless there is an actual reason for that. The way 
you do it now is simply introducing clutter, without benefit. Your class 
would be half the current size - without loss of functionality.




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


Re: Free Python Training: Washington, DC (3/3-5)

2009-02-25 Thread Steve Holden
Alan G Isaac wrote:
> Great idea, but if you do it again, a bit
> more lead time would be helpful.
> 
Appreciate that. Last-minute idea.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: coding style - try, except

2009-02-25 Thread RGK


I'm glad I asked :)

Thanks all who posted for your replies, the else-statement is a nice 
option.


Python again comes through to deal with those pesky feelings that 
something could be better :)


Ross.



Chris Rebert wrote:


Yes. try-except-*else*.

try:
do_something_1()
do_something_2()
except:
print "Houston, we have a problem"
else: #runs only if no exception was thrown
do_something_3()
do_something_4()
et_cetera()

Cheers,
Chris


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


Re: Free Python Training: Washington, DC (3/3-5)

2009-02-25 Thread Alan G Isaac

Great idea, but if you do it again, a bit
more lead time would be helpful.

Cheers,
Alan Isaac
--
http://mail.python.org/mailman/listinfo/python-list


Re: variables bound in moudules are None when module is not completely imported

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 16:48:16 -0200,  escribió:


update: i've found one, but this only works if the exception is raised
at a point determined by the outside.

to explain why this is applicable: in the examples, i used `1/0` to
raise a zero division exception inside the module whose scope i want to
preserve. in my practical application, the exception is thrown by a
function that was previously prepared by the outside module and monkey
patched to where the inner module is expected to call a method from (in
my case, the gtk main loop).

now if the function raising the exception saves both
`sys._getframe().f_back.f_globals` and a .copy() of that dictionary, the
original dictionary can later (when the exception is caught and the
module's globals are all None) be .update()d with the copy, and the
original module globals are restored.


That makes a strange situation where the module doesn't exist in  
sys.modules but its globals are still alive...



as said, this is just a workaround -- the original question still
remains open.


I'd try to move all the global stuff in that module into a function,  
"init". Importing the module will always succeed - you have to manually  
call init() after importing it.


--
Gabriel Genellina

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 16:19:35 -0200, Thorsten Kampe  
 escribió:

* Tim Golden (Wed, 25 Feb 2009 17:27:07 +)

Thorsten Kampe wrote:
> * Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)
>> En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe

[...]
>>> And I wonder why you would think the header contains Unicode  
characters
>>> when it says "us-ascii" ("=?us-ascii?Q?"). I think there is a  
tendency

>>> to label everything "Unicode" someone does not understand.
>> And I wonder why you would think the header does *not* contain  
Unicode

>> characters when it says "us-ascii"?.
>
> Basically because it didn't contain any Unicode characters (anything
> outside the ASCII range).

And I imagine that Gabriel's point was -- and my point certainly
is -- that Unicode includes all the characters *inside* the
ASCII range.


I know that this was Gabriel's point. And my point was that Gabriel's
point was pointless. If you call any text (or character) "Unicode" then
the word "Unicode" is generalized to an extent where it doesn't mean
anything at all anymore and becomes a buzz word.


If it's text, it should use Unicode. Maybe not now, but in a few years, it  
will be totally unacceptable not to properly use Unicode to process  
textual data.



With the same reason you could call ASCII an Unicode encoding (which it
isn't) because all ASCII characters are Unicode characters (code
points). Only encodings that cover the full Unicode range can reasonably
be called Unicode encodings.


Not at all. ASCII is as valid as character encoding ("coded character set"  
as the Unicode guys like to say) as ISO 10646 (which covers the whole  
range).



The OP just saw some "weird characters" in the email subject and thought
"I know. It looks weird. Must be Unicode". But it wasn't. It was good
ole ASCII - only Quoted Printable encoded.


Good f*cked ASCII is Unicode too.

--
Gabriel Genellina

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


Re: variables bound in moudules are None when module is not completely imported

2009-02-25 Thread chrysn
On Tue, Feb 24, 2009 at 03:27:19PM +0100, chr...@fsfe.org wrote:
> * is there a workaround?
> * especially, is there a workaround that works w/o rewriting the
>   modules that raise the exceptions? (otherwise, wrapping all the
>   stuff called in the __name__=="__main__" wrapper into a main()
>   function and then calling that would trivially solve that)

update: i've found one, but this only works if the exception is raised
at a point determined by the outside.

to explain why this is applicable: in the examples, i used `1/0` to
raise a zero division exception inside the module whose scope i want to
preserve. in my practical application, the exception is thrown by a
function that was previously prepared by the outside module and monkey
patched to where the inner module is expected to call a method from (in
my case, the gtk main loop).

now if the function raising the exception saves both
`sys._getframe().f_back.f_globals` and a .copy() of that dictionary, the
original dictionary can later (when the exception is caught and the
module's globals are all None) be .update()d with the copy, and the
original module globals are restored.

as said, this is just a workaround -- the original question still
remains open.

regards
chrysn

-- 
To use raw power is to make yourself infinitely vulnerable to greater powers.
  -- Bene Gesserit axiom


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Battleship" style game

2009-02-25 Thread Shawn Milochik
Thanks. I wasn't aware of the property() function, but I read up on
it. I modified the Vessels.py file, but not the board file (except
where necessary to handle the changes made to Vessels. Is this better?

http://shawnmilo.com/ships/ships2/
--
http://mail.python.org/mailman/listinfo/python-list


Re: coding style - try, except

2009-02-25 Thread Christian Heimes
RGK wrote:
> Any input appreciated :)

How about:

import logging

try:
   # run your function
   some_function()
except Exception:
   # except only the exceptions you *really* want to catch
   # at most you should except "Exception" since it doesn't
   # catch KeyboardInterrupt and SystemExit
   logging.exception("An error has occured")
   # logging is preferred over a simple print because it
   # also prints out a nice traceback
else:
   # the else block is reached when no exception has occured
   some_other()
finally:
   # the finally block is *always* executed at least
   # use it to clean up some resources
   some_cleanup_code()

Christian

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


Re: coding style - try, except

2009-02-25 Thread Scott David Daniels

RGK wrote:
I'm still learning, so eager to see if there is some community wisdom 
about use of the try/except structures in this situation

  try:
do something 1
do something 2
do something 3
do something 4
...
do something 25
  except:
print "Oops something didn't work"

The risky things are just 1 & 2, and the others are not of concern, but 
are dependent on 1 & 2.  The alternative is to do:


  wentOkay = True
  try:
do something 1
do something 2
  except:
print "Oops something didn't work"
wentOkay = False
  if wentOkay:
do something 3
do something 4
 ...
do something 25
Which seems a bit verbose, but likely the better approach.  Is there 
some other option I should be considering?

What's wrong with:
try:
do something 1
do something 2
except (AttributeError, ValueError), why: # Don't use bare except
print "Oops something didn't work: %s" % why
else:
do something 3
do something 4
...
do something 25
--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 15:44:18 -0200,  escribió:


Tab is not mentioned in RFC 2822 except to say that it is a valid
whitespace character.  Header folding (insertion of ) can
occur most places whitespace appears, and is defined in section
2.2.3 thusly: [...]
So, the whitespace characters are supposed to be left unchanged
after unfolding.


Yep, there is an old bug report sleeping in the tracker about this...

--
Gabriel Genellina

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Thorsten Kampe
* Tim Golden (Wed, 25 Feb 2009 17:27:07 +)
> Thorsten Kampe wrote:
> > * Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)
> >> En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe  
[...]
> >>> And I wonder why you would think the header contains Unicode characters
> >>> when it says "us-ascii" ("=?us-ascii?Q?"). I think there is a tendency
> >>> to label everything "Unicode" someone does not understand.
> >> And I wonder why you would think the header does *not* contain Unicode  
> >> characters when it says "us-ascii"?.
> > 
> > Basically because it didn't contain any Unicode characters (anything 
> > outside the ASCII range).
> 
> And I imagine that Gabriel's point was -- and my point certainly
> is -- that Unicode includes all the characters *inside* the
> ASCII range.

I know that this was Gabriel's point. And my point was that Gabriel's 
point was pointless. If you call any text (or character) "Unicode" then 
the word "Unicode" is generalized to an extent where it doesn't mean 
anything at all anymore and becomes a buzz word.

With the same reason you could call ASCII an Unicode encoding (which it 
isn't) because all ASCII characters are Unicode characters (code 
points). Only encodings that cover the full Unicode range can reasonably 
be called Unicode encodings.

The OP just saw some "weird characters" in the email subject and thought 
"I know. It looks weird. Must be Unicode". But it wasn't. It was good 
ole ASCII - only Quoted Printable encoded.


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


Re: reading file to list

2009-02-25 Thread Xah Lee
On Feb 25, 3:34 am, nick_keighley_nos...@hotmail.com wrote:
> the nasty cons then only appears in a single function which
> you can hide in a library

I think the following answers that.

Q: If you don't like cons, lisp has arrays and hashmaps, too.

A: Suppose there's a lang called gisp. In gisp, there's cons but also
fons. Fons are just like cons except it has 3 cells with 3 accessors:
car, cbr, cdr. Now, gisp is a old lang, the fons are deeply rooted in
the lang. Every some 100 lines of code you'll see a use of fons with
its extra accessor cbr, or any one of the cbaar, cdabr, cbbar, cbbbar,
etc. You got annoyed by this. You as a critic, complains that fons is
bad. But then some gisp fanatics retorts: “If you don't like fons,
gisp has cons, too!”.

You see, by “having something too”, does not solve the problem of
pollution. Sure, you can use just cons in gisp, but every lib or
other's code you encounter, there's a invasion of fons with its cbar,
cbbar, cbbbar. The problem created by fons does not go away by “having
cons too”.

above is from

• Fundamental Problems of Lisp
  http://xahlee.org/UnixResource_dir/writ/lisp_problems.html

-

> I read it. Your point seems to be "cons becomes difficult
> with deeply nested structures". Could you give an example?

There are few examples in these articles:

• The Concepts and Confusions of Prefix, Infix, Postfix and Fully
Nested Notations
  http://xahlee.org/UnixResource_dir/writ/notations.html

the above, 3rd section, gives detail about the problems of fully
nested syntax. In particular, it shows a source code snippet of
language with fully nested syntax, but is not lisp, so that lispers
can get a fresh impression.

• A Ruby Illustration of Lisp Problems
  http://xahlee.org/UnixResource_dir/writ/lisp_problems_by_ruby.html

the above, is a concrete example of showing how full nesting is
cumbersome, by constrasting a simple program in Ruby and lisp.

• Why Lisp Do Not Have A Generic Copy-List Function
  http://xahlee.org/UnixResource_dir/writ/lisp_equal_copy_list.html

the above, shows the cons problem, by looking Kent Pitman's article
with a different perspective.

A short Plain Text Excerpt of the ruby article cited above follows.
--

More specifically, 2 fundamental problems of lisp i feel this ruby
example illustrates well:

• the cons impedes many aspects of lists. e.g. difficult to learn,
confusing, hard to use, prevent development of coherent list
manipulation functions.

• nested syntax impedes the functional programing paradigm of function
chaining, esp when each function has 2 or more arguments (e.g. map).

here's a short summary of the nesting problem:

(map f x) ; 1 level of chaining
(map g (map f x)) ; 2 levels
(map h (map g (map f x))) ; 3 levels

compare:

x | f | g | h   > unix pipe
x // f // g // h   > Mathematica
h @ g @ f @ x> Mathematica
x.f.g.h---> various OOP langs, esp Ruby, javascript
h g f x   ---> some functional langs, Haskell, Ocaml

The way the above works is that each of f, g, h is a lambda themselves
that maps. (that is, something like “(lambda (y) (map f y))”)

Note, that any of the f, g, h may be complex pure functions (aka
lambda).  Because in lisp, each lambda itself will in general have
quite a lot nested parens (which cannot be avoided), so this makes any
chaining of functions of 2 args, for more than 2 or 3 levels of
nesting, unusable for practical coding. One must define the functions
separately and just call their names, or use function composition with
lambda (which gets complex quickly). One major aspect of this problem
is that the scope of vars becomes hard to understand in the deep
nested source code. This is worse in elisp, because emacs is
dynamically scoped, so you have to avoid using var of same name.

 Xah
∑http://xahlee.org/

☄

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


Re: coding style - try, except

2009-02-25 Thread Peter Otten
Steve Holden wrote:

> RGK wrote:
>> 
>> I'm still learning, so eager to see if there is some community wisdom
>> about use of the try/except structures in this situation.
>> 
>> I find myself with some potentially risky stuff and wrap it in a
>> try/except structure with good functional results, though my code leaves
>> me a bit uneasy. Maybe it's just esoteric, but your input is appreciated.
>> 
>> Consider
>> 
>>   try:
>> do something 1
>> do something 2
>> do something 3
>> do something 4
>> ...
>> do something 25
>> 
>>   except:
>> print "Oops something didn't work"

If you don't want a specific treatment for errors anticipated in 1 and 2
there's no need for try...except at this level at all. Just pass control up
the stack.

>> The risky things are just 1 & 2, and the others are not of concern, but
>> are dependent on 1 & 2.  The alternative is to do:
>> 
>>   wentOkay = True
>>   try:
>> do something 1
>> do something 2
>> 
>>   except:
>> print "Oops something didn't work"
>> wentOkay = False
>> 
>>   if wentOkay:
>> do something 3
>> do something 4
>>  ...
>> do something 25
>> 
>> 
>> Which seems a bit verbose, but likely the better approach.  Is there
>> some other option I should be considering?
>> 
>> Any input appreciated :)
>> 
> The first form is far preferable: it expresses the logic directly and
> clearly, and is much easier to read than the second, which I personally
> find somewhat contorted.

How about

try:
# do something that may fail in a way you anticipate
do something 1
do something 2
except SpecificError:
deal with the problem or reraise
else:
# no errors above
do something 3...25

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


Re: coding style - try, except

2009-02-25 Thread Chris Rebert
On Wed, Feb 25, 2009 at 9:36 AM, RGK  wrote:
>
> I'm still learning, so eager to see if there is some community wisdom about
> use of the try/except structures in this situation.
>
> I find myself with some potentially risky stuff and wrap it in a try/except
> structure with good functional results, though my code leaves me a bit
> uneasy. Maybe it's just esoteric, but your input is appreciated.
>
> Consider
>
>  try:
>    do something 1
>    do something 2
>    do something 3
>    do something 4
>    ...
>    do something 25
>
>  except:
>    print "Oops something didn't work"
>
>
> The risky things are just 1 & 2, and the others are not of concern, but are
> dependent on 1 & 2.  The alternative is to do:
>
>  wentOkay = True
>  try:
>    do something 1
>    do something 2
>
>  except:
>    print "Oops something didn't work"
>    wentOkay = False
>
>  if wentOkay:
>    do something 3
>    do something 4
>     ...
>    do something 25
>
>
> Which seems a bit verbose, but likely the better approach.  Is there some
> other option I should be considering?

Yes. try-except-*else*.

try:
do_something_1()
do_something_2()
except:
print "Houston, we have a problem"
else: #runs only if no exception was thrown
do_something_3()
do_something_4()
et_cetera()

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Duncan Grisby
In article ,
David Cournapeau   wrote:

[...]
>It is very unlikely the problem is in glibc - I would check your code
>carefully first :) On Linux, the following are useful:

You are right that it is extremely unlikely that the bug is in glibc.
However, it is not impossible. Several of my colleagues and I spent
months trying to track down a bug where Python would occasionally
crash with a segfault while iterating through large lists. Of course
the problem only ever happened on customer sites, and not in our lab.
I eventually tracked it down to a bug in glibc's realloc()
implementation, where once in a blue moon it would fail to copy all
the data into the newly-allocated buffer.

It turned out to be a bug that had been found before, but had been
closed as invalid a few months earlier:

  http://sources.redhat.com/bugzilla/show_bug.cgi?id=5743

The fix had then been applied about a week before I found it myself.

I'm not sure that particular fix has found it into any of the major
Linux distributions yet.

Cheers,

Duncan.

-- 
 -- Duncan Grisby --
  -- dun...@grisby.org --
   -- http://www.grisby.org --
--
http://mail.python.org/mailman/listinfo/python-list


Re: This application has failed to start because the application configuration is incorrect

2009-02-25 Thread Lorenzo
On 17 feb, 19:44, Mark Hammond  wrote:
> On 18/02/2009 5:49 AM, Sam Clark wrote:
>
> > I am receiving the message "Thisapplicationhasfailedtostartbecause
> > theapplicationconfiguration is incorrect" when I attempt to run a
> > compiled Python program on another machine. I have used py2exe on both a
> > 2.6.1 and a 2.6.0 version of the .py and .pyw files. Everything works
> > great on the machine where Python 2.6 is loaded, but fails on machines
> > where I copy the .exe to the machine. I'm a beginner at python
> > programming. In fact this is my first packaged program. Any thoughts at
> > a beginners level would be helpful.
>
> This will be due to the C runtime library not being installed correctly
> on the target machine.  

I had the same issue. After looking some "patch" solutions of putting
manually some dlls on the dist folder, I realized that you can fix it
by installing one of these packages, see which one fits your system:
x86
http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en

x64
http://www.microsoft.com/downloads/details.aspx?familyid=BA9257CA-337F-4B40-8C14-157CFDFFEE4E&displaylang=en

PS: Mark, this could be added to a kind of "Deployment" entry in
py2exe wiki, it would be useful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: coding style - try, except

2009-02-25 Thread Steve Holden
RGK wrote:
> 
> I'm still learning, so eager to see if there is some community wisdom
> about use of the try/except structures in this situation.
> 
> I find myself with some potentially risky stuff and wrap it in a
> try/except structure with good functional results, though my code leaves
> me a bit uneasy. Maybe it's just esoteric, but your input is appreciated.
> 
> Consider
> 
>   try:
> do something 1
> do something 2
> do something 3
> do something 4
> ...
> do something 25
> 
>   except:
> print "Oops something didn't work"
> 
> 
> The risky things are just 1 & 2, and the others are not of concern, but
> are dependent on 1 & 2.  The alternative is to do:
> 
>   wentOkay = True
>   try:
> do something 1
> do something 2
> 
>   except:
> print "Oops something didn't work"
> wentOkay = False
> 
>   if wentOkay:
> do something 3
> do something 4
>  ...
> do something 25
> 
> 
> Which seems a bit verbose, but likely the better approach.  Is there
> some other option I should be considering?
> 
> Any input appreciated :)
> 
The first form is far preferable: it expresses the logic directly and
clearly, and is much easier to read than the second, which I personally
find somewhat contorted.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Steve Holden
rdmur...@bitdance.com wrote:
[...]
> 
>The process of moving from this folded multiple-line representation
>of a header field to its single line representation is called
>"unfolding". Unfolding is accomplished by simply removing any CRLF
>that is immediately followed by WSP.  Each header field should be
>treated in its unfolded form for further syntactic and semantic
>evaluation.
> 
> So, the whitespace characters are supposed to be left unchanged
> after unfolding.
> 
That would certainly appear to be the case. Thanks.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread rdmurray
Steve Holden  wrote:
> rdmur...@bitdance.com wrote:
> > Steve Holden  wrote:
> > from email.header import decode_header
> > print
> >> decode_header("=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=")
> >> [('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
> >> Records', 'us-ascii')]
> > 
> > It is interesting that decode_header does what I would consider to be
> > the right thing (from a pragmatic standpoint) with that particular bit
> > of Microsoft not-quite-standards-compliant brain-damage; but, removing
> > the tab is not in fact standards compliant if I'm reading the RFC
> > correctly.
> > 
> You'd need to quote me chapter and verse on that. I understood that the
> tab simply indicated continuation, but it's a *long* time since I read
> the RFCs.

Tab is not mentioned in RFC 2822 except to say that it is a valid
whitespace character.  Header folding (insertion of ) can
occur most places whitespace appears, and is defined in section
2.2.3 thusly:

   Each header field is logically a single line of characters comprising
   the field name, the colon, and the field body.  For convenience
   however, and to deal with the 998/78 character limitations per line,
   the field body portion of a header field can be split into a multiple
   line representation; this is called "folding".  The general rule is
   that wherever this standard allows for folding white space (not
   simply WSP characters), a CRLF may be inserted before any WSP.  For
   example, the header field:

   Subject: This is a test

   can be represented as:

   Subject: This
is a test

   [irrelevant note elided]

   The process of moving from this folded multiple-line representation
   of a header field to its single line representation is called
   "unfolding". Unfolding is accomplished by simply removing any CRLF
   that is immediately followed by WSP.  Each header field should be
   treated in its unfolded form for further syntactic and semantic
   evaluation.

So, the whitespace characters are supposed to be left unchanged
after unfolding.

--David

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


coding style - try, except

2009-02-25 Thread RGK


I'm still learning, so eager to see if there is some community wisdom 
about use of the try/except structures in this situation.


I find myself with some potentially risky stuff and wrap it in a 
try/except structure with good functional results, though my code leaves 
me a bit uneasy. Maybe it's just esoteric, but your input is appreciated.


Consider

  try:
do something 1
do something 2
do something 3
do something 4
...
do something 25

  except:
print "Oops something didn't work"


The risky things are just 1 & 2, and the others are not of concern, but 
are dependent on 1 & 2.  The alternative is to do:


  wentOkay = True
  try:
do something 1
do something 2

  except:
print "Oops something didn't work"
wentOkay = False

  if wentOkay:
do something 3
do something 4
 ...
do something 25


Which seems a bit verbose, but likely the better approach.  Is there 
some other option I should be considering?


Any input appreciated :)

Ross.

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 15:01:08 -0200, Thorsten Kampe  
 escribió:

* Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)

En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe
 escribió:
> * Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)
>> Thanks, RDM, for stating the right approach.
>> Thanks, Steve, for teaching by example.
>>
>> I wonder why the email.message_from_string() method doesn't call
>> email.header.decode_header() automatically.
>
> And I wonder why you would think the header contains Unicode  
characters

> when it says "us-ascii" ("=?us-ascii?Q?"). I think there is a tendency
> to label everything "Unicode" someone does not understand.

And I wonder why you would think the header does *not* contain Unicode
characters when it says "us-ascii"?.


Basically because it didn't contain any Unicode characters (anything
outside the ASCII range).


I think you have to revise your definition of "Unicode".

--
Gabriel Genellina

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Tim Golden

Thorsten Kampe wrote:

* Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)
En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe  
 escribió:

* Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)

Thanks, RDM, for stating the right approach.
Thanks, Steve, for teaching by example.

I wonder why the email.message_from_string() method doesn't call
email.header.decode_header() automatically.

And I wonder why you would think the header contains Unicode characters
when it says "us-ascii" ("=?us-ascii?Q?"). I think there is a tendency
to label everything "Unicode" someone does not understand.
And I wonder why you would think the header does *not* contain Unicode  
characters when it says "us-ascii"?.


Basically because it didn't contain any Unicode characters (anything 
outside the ASCII range).


And I imagine that Gabriel's point was -- and my point certainly
is -- that Unicode includes all the characters *inside* the
ASCII range.


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


Re: File Path retrieving problem

2009-02-25 Thread Peter Otten
Steve Holden wrote:

> What, you are saying that
> 
> os.path.exists(filename)
> 
> is returning false when the file exists? I find that hard to believe.
> 
> Please display some evidence so I can understand this.

Maybe it's about access rights?

$ mkdir alpha
$ touch alpha/beta
$ python -c"import os; print os.path.exists('alpha/beta')"
True
$ chmod u-x alpha
$ python -c"import os; print os.path.exists('alpha/beta')"
False
$

I Don't know how this is handled on Windows...

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


Re: "Battleship" style game

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 14:50:18 -0200, Shawn Milochik   
escribió:
On Wed, Feb 25, 2009 at 11:38 AM, Marco Mariani   
wrote:


Yes it's in Python alright, but it's not Pythonese yet. You could try
avoiding the getter/setter stuff, and camelCase method naming, things  
like

that, for a start.


What do you mean avoiding the getter/setter stuff? If I understand
correctly, you're saying to directly access the attributes, which I
specifically want to avoid because I may want to enforce some rules
(such as not changing a ship length after it's created).


I think Marco Mariani was suggesting something like this:

class Ship(object):

def __init__(self, length):
self._length = length

def get_length(self):
return self._length
length = property(get_length)  # a read only property

--
Gabriel Genellina

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


Re: "Battleship" style game

2009-02-25 Thread Steve Holden
Shawn Milochik wrote:
> On Wed, Feb 25, 2009 at 11:38 AM, Marco Mariani  wrote:
>> Yes it's in Python alright, but it's not Pythonese yet. You could try
>> avoiding the getter/setter stuff, and camelCase method naming, things like
>> that, for a start.
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> 
> 
> What do you mean avoiding the getter/setter stuff? If I understand
> correctly, you're saying to directly access the attributes, which I
> specifically want to avoid because I may want to enforce some rules
> (such as not changing a ship length after it's created).
> 
If you wanted to enforce those restrictions you could just turn
attributes into properties.

> The camel-case thing I get -- I use that and this_type quite a bit,
> probably because of the inconsistency of the languages I use
> regularly, and standards at work and conventions in my hobby
> programming.

PEP 008 is the usual style recommendation.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Thorsten Kampe
* Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)
> En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe  
>  escribió:
> > * Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)
> >> Thanks, RDM, for stating the right approach.
> >> Thanks, Steve, for teaching by example.
> >>
> >> I wonder why the email.message_from_string() method doesn't call
> >> email.header.decode_header() automatically.
> >
> > And I wonder why you would think the header contains Unicode characters
> > when it says "us-ascii" ("=?us-ascii?Q?"). I think there is a tendency
> > to label everything "Unicode" someone does not understand.
> 
> And I wonder why you would think the header does *not* contain Unicode  
> characters when it says "us-ascii"?.

Basically because it didn't contain any Unicode characters (anything 
outside the ASCII range).

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


Re: File Path retrieving problem

2009-02-25 Thread Steve Holden
music24...@gmail.com wrote:
> On Feb 25, 8:57 pm, Steve Holden  wrote:
>> music24...@gmail.com wrote:
>>> Hi all,
>>> I am new to Python, i have installed python 2.5.4 and it is my
>>> requirement.
>>> I need to retrieve the path of filename in python.
>>> I have found some API's to get this:
>>> from os.path import realpath
>>> print realpath("NEWS.txt")  # here NEWS.txt exists and it shows the
>>> path of the file as C:\Python25\WorkSpace\NEWS.txt
>>> print realpath("abc.txt") # here abc.txt does not exist but still it
>>> shows C:\Python25\WorkSpace\abc.txt
>>> can anybody tell the reason why
>>> Now took some safety measures:
>>> found = lexists(realpath(filename))
>>> if found == 0:
>>> print "Not Found"
>>> else:
>>> print realpath(filename)
>>> i have given the filename as "NEWS.txt" and "abc.txt" but i am always
>>> getting the output as "Not Found"
>>> Can anyone please tell me where am i doing wrong
>> It seems pretty apparent that lexists() nevert returns a true result.
>>
>> Why not just
>>
>> if os.path.exists(filename):
>> print os.path.realpath(filename)
>> else:
>> print "Not found"
>>
>>> also any suggestions to retrieve the filepath from a given filename is
>>> highly appreciated.
>> Well, realpath returns the path of the file targeted after any symbolic
>> links have been evaluated, which may or may not be what you want. Have
>> you looked at os.path.abspath?
>>
>> regards
>>  Steve
>> --
>> Steve Holden+1 571 484 6266   +1 800 494 3119
>> Holden Web LLC  http://www.holdenweb.com/
> 
> 
> 
> Hi Steve,
> 
> I have tried your suggested code and also replaced os.path.realpath
> with os.path.abspath but still getting the same result.
> I want to know is there any workaround for retrieving the filepaths
> given only filename
> 
What, you are saying that

  os.path.exists(filename)

is returning false when the file exists? I find that hard to believe.

Please display some evidence so I can understand this.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: "Battleship" style game

2009-02-25 Thread Shawn Milochik
On Wed, Feb 25, 2009 at 11:38 AM, Marco Mariani  wrote:
>
> Yes it's in Python alright, but it's not Pythonese yet. You could try
> avoiding the getter/setter stuff, and camelCase method naming, things like
> that, for a start.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


What do you mean avoiding the getter/setter stuff? If I understand
correctly, you're saying to directly access the attributes, which I
specifically want to avoid because I may want to enforce some rules
(such as not changing a ship length after it's created).

The camel-case thing I get -- I use that and this_type quite a bit,
probably because of the inconsistency of the languages I use
regularly, and standards at work and conventions in my hobby
programming.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Battleship" style game

2009-02-25 Thread Marco Mariani

Shawn Milochik wrote:

> I'm not claiming it's bulletproof, but it works. I just kind of came 
up with all the

methods off of the top of my head, so if anyone has any suggestions
for more elegant or efficient code, please let me know.


Yes it's in Python alright, but it's not Pythonese yet. You could try 
avoiding the getter/setter stuff, and camelCase method naming, things 
like that, for a start.


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


"Battleship" style game

2009-02-25 Thread Shawn Milochik
I started learning Java for fun, and the first project assignment in
the book is to create a game like "Battleship." So, of course, I wrote
it in Python first, just for fun. I haven't had the time to look up
all the Java syntax.

So, here it is, fully functional. I thought I'd throw it out there and
see if anyone would like to offer any useful tips. I'm not claiming
it's bulletproof, but it works. I just kind of came up with all the
methods off of the top of my head, so if anyone has any suggestions
for more elegant or efficient code, please let me know.

http://shawnmilo.com/ships/

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 14:07:30 -0200, Seth  escribió:


This is not my code and I am fairly new to Python.  I did not know how
much it would take to convert pyserial to 3.0. Someone more
knowledgeable than me could do it better and faster.  I just want to
see if I could help get it to work.


The last commit to pyserial repository was 8 days ago, so it's not like an  
abandoned project.

Have you contacted the author?

That said, Python 3.0 is still very recent and doesn't have a big set of  
3rd party libraries as earlier versions. Maybe you should stick to 2.6 or  
even 2.5 for a while.


--
Gabriel Genellina

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


Re: File Path retrieving problem

2009-02-25 Thread music24by7
On Feb 25, 8:57 pm, Steve Holden  wrote:
> music24...@gmail.com wrote:
> > Hi all,
>
> > I am new to Python, i have installed python 2.5.4 and it is my
> > requirement.
>
> > I need to retrieve the path of filename in python.
>
> > I have found some API's to get this:
>
> > from os.path import realpath
> > print realpath("NEWS.txt")  # here NEWS.txt exists and it shows the
> > path of the file as C:\Python25\WorkSpace\NEWS.txt
> > print realpath("abc.txt") # here abc.txt does not exist but still it
> > shows C:\Python25\WorkSpace\abc.txt
>
> > can anybody tell the reason why
>
> > Now took some safety measures:
>
> > found = lexists(realpath(filename))
> >         if found == 0:
> >             print "Not Found"
> >         else:
> >             print realpath(filename)
>
> > i have given the filename as "NEWS.txt" and "abc.txt" but i am always
> > getting the output as "Not Found"
>
> > Can anyone please tell me where am i doing wrong
>
> It seems pretty apparent that lexists() nevert returns a true result.
>
> Why not just
>
> if os.path.exists(filename):
>     print os.path.realpath(filename)
> else:
>     print "Not found"
>
> > also any suggestions to retrieve the filepath from a given filename is
> > highly appreciated.
>
> Well, realpath returns the path of the file targeted after any symbolic
> links have been evaluated, which may or may not be what you want. Have
> you looked at os.path.abspath?
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/



Hi Steve,

I have tried your suggested code and also replaced os.path.realpath
with os.path.abspath but still getting the same result.
I want to know is there any workaround for retrieving the filepaths
given only filename

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


Re: How to convert image into numpy.ndarray

2009-02-25 Thread Christian Meesters
On Wed, 25 Feb 2009 07:52:03 -0800, anti-suho wrote:

> In scipy module, there is a function named misc.lena which can return an
> array of numpy.ndarray type. If you use this array as parameter of
> matplotlib.pyplot.imshow and then call the matplotlib.pyplot.imshow
> function, an image will be shown. The shown image is generated by the
> numpy.ndarray array.
> 
> How to convert an arbitrary image into an array of numpy.ndarray type?
Well, arbitrary ...

But this may serve as a starting point:

from scipy.misc import fromimage
import Image #PIL
my_array = fromimage(Image.open(_file_name_))

Of course, you should perform the appropriate error checking, too. ;-)

HTH
Christian


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


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 13:51:20 -0200, Christian Meesters   
escribió:



I have a problem using my software on my 64bit laptop, after an update
of my system. The same code still runs on 32bit Intel, but on my laptop
I provoke the crash in the title. The crash is caused - as narrowed
down by me - by returning a static PyObject from a C-extension
function.


I think you got all the reference counts wrong, specially dummy1, dummy2
and r.

Might be a good point, but can you give me a hint where to look
specifically?


  /* parse the input arguments r & vectors */
  if (!PyArg_ParseTuple(args, "OO", &r, &py_vectors))
return NULL;
  ...

  for (i=0; i < vsize; i++) {
...
dummy_2 = PyList_GetItem(dummy_1, 0);
...
  }
  ...

  /* copy all items from pofr to py_pofr to be returned */
  if (!(py_pofr = PyList_New(0)))  return NULL;
  for (i=0; i < rlen; i++) {
dummy_1 = Py_BuildValue("i", pofr[i]);
if (!dummy_1) return NULL;
PyList_Append(py_pofr, dummy_1);
Py_CLEAR(dummy_1);
  }

  /* reference counters to zero */
  Py_CLEAR(dummy_1);
  Py_CLEAR(dummy_2);
  Py_CLEAR(r);


r is an argument, a borrowed reference; you can't Py_CLEAR it.
dummy_1 is decremented inside the loop, and again three lines below.
dummy_2 is used far above the final Py_CLEAR, and it comes from  
PyList_GetItem, which returns a borrowed reference - you can't decrement  
it either.
Also there are several "return NULL" that don't decrement active objects  
(like "if (!dummy_1)..." above)


Getting the reference count right is critical: if you err by +1, the  
object will never be destroyed (leaking memory). If you err by -1, the  
object will be still in use after it was destroyed.


--
Gabriel Genellina

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Seth
This is not my code and I am fairly new to Python.  I did not know how
much it would take to convert pyserial to 3.0. Someone more
knowledgeable than me could do it better and faster.  I just want to
see if I could help get it to work.

I was wrong, it seems that if type(port) in (str, bytes): or isinstance
(port, str) works just fine for setting the ports.

The issue now is reading and writing the data.

I got the read() to kind of work with:
bytes(buf[:n]) replacing str(buf[:n])

but with readline() it seems to be missing the '\n' because it just
runs indefinitely( I can see the \n if I read enough bytes with read()


write seems to be related to a win32 issue.  win32file.WriteFile does
not like anything I convert it to:
str gives the buffer error
bytes gives a "string argument without an encoding" error

Sorry for the confusion, I just want to be able to use all Py3k on
this project that I am working on and pyserial has not been converted
so I just started messing around with it.

Thanks for the help.

Seth




On Feb 25, 10:16 am, Christian Heimes  wrote:
> Seth wrote:
> > I tried all three ways you guys listed nothing seems to convert the
> > string to bytes.
>
> > It may have to do with the makeDeviceName function, but I can't find
> > where that is defined.
>
> > Any thoughts??
>
> > Here is the whole block of code:
>
> > if type(port) in (str, bytes):       #strings are taken directly
> > Originally:     if type(port) in [type(''), type(u'')]
> >                 self.portstr = port
> >             else:
> >                 self.portstr = self.makeDeviceName(port)
>
> str and bytes are two totally unrelated things in Python 3.0. You can no
> longer treat them equally like str and unicode in Python 2.x. Your could
> should not work under Python 3.0 anyway. u'' is invalid in 3.x.
>
> Also please don't use ugly type checks like type(something) == type('').
> Starting with Python 2.2 you should use isinstance, for example
> isinstance(number, (int, long)).
>
> Christian

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe  
 escribió:



* Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)

Thanks, RDM, for stating the right approach.
Thanks, Steve, for teaching by example.

I wonder why the email.message_from_string() method doesn't call
email.header.decode_header() automatically.


And I wonder why you would think the header contains Unicode characters
when it says "us-ascii" ("=?us-ascii?Q?"). I think there is a tendency
to label everything "Unicode" someone does not understand.


And I wonder why you would think the header does *not* contain Unicode  
characters when it says "us-ascii"?. I think there is a tendency here  
too...


--
Gabriel Genellina

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


Re: File Path retrieving problem

2009-02-25 Thread Steve Holden
music24...@gmail.com wrote:
> Hi all,
> 
> I am new to Python, i have installed python 2.5.4 and it is my
> requirement.
> 
> I need to retrieve the path of filename in python.
> 
> I have found some API's to get this:
> 
> from os.path import realpath
> print realpath("NEWS.txt")  # here NEWS.txt exists and it shows the
> path of the file as C:\Python25\WorkSpace\NEWS.txt
> print realpath("abc.txt") # here abc.txt does not exist but still it
> shows C:\Python25\WorkSpace\abc.txt
> 
> can anybody tell the reason why
> 
> 
> Now took some safety measures:
> 
> found = lexists(realpath(filename))
> if found == 0:
> print "Not Found"
> else:
> print realpath(filename)
> 
> i have given the filename as "NEWS.txt" and "abc.txt" but i am always
> getting the output as "Not Found"
> 
> 
> Can anyone please tell me where am i doing wrong
> 
It seems pretty apparent that lexists() nevert returns a true result.

Why not just

if os.path.exists(filename):
print os.path.realpath(filename)
else:
print "Not found"

> also any suggestions to retrieve the filepath from a given filename is
> highly appreciated.
> 
Well, realpath returns the path of the file targeted after any symbolic
links have been evaluated, which may or may not be what you want. Have
you looked at os.path.abspath?

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


How to convert image into numpy.ndarray

2009-02-25 Thread anti-suho
In scipy module, there is a function named misc.lena which can return
an array of numpy.ndarray type. If you use this array as parameter of
matplotlib.pyplot.imshow and then call the matplotlib.pyplot.imshow
function, an image will be shown. The shown image is generated by the
numpy.ndarray array.

How to convert an arbitrary image into an array of numpy.ndarray type?
--
http://mail.python.org/mailman/listinfo/python-list


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Christian Meesters
Hi,

>> I have a problem using my software on my 64bit laptop, after an update
>> of my system. The same code still runs on 32bit Intel, but on my laptop
>> I provoke the crash in the title. The crash is caused - as narrowed
>> down by me - by returning a static PyObject from a C-extension
>> function.
> 
> I think you got all the reference counts wrong, specially dummy1, dummy2
> and r.
Might be a good point, but can you give me a hint where to look 
specifically?
> 
> (BTW, when you know the size, it's better to use PyList_New(size) +
> PyList_SET_ITEM instead of PyList_New(0) + PyList_Append)
Just rewrote that section.

Thank you.
Christian
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie : this works in one direction but get the error on the return path

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 13:31:25 -0200, Gary Wood  escribió:

Start looking at the error:


Traceback (most recent call last):
  File "E:/python/handson/backAndForth4.py", line 97, in 
main()
  File "E:/python/handson/backAndForth4.py", line 90, in main
moveAllOnLine(faceList, -dx, dy, stepsAcross/2, wait)
  File "E:/python/handson/backAndForth4.py", line 21, in moveAllOnLine
for i in range(repetitions):
TypeError: 'float' object cannot be interpreted as an integer


It's rather understandable - you have a float object where Python is  
expecting an integer.

Where? The traceback says it all:


  File "E:/python/handson/backAndForth4.py", line 21, in moveAllOnLine
for i in range(repetitions):


Ok, so repetitions should be an integer, but it isn't. Where does it come  
from? It's an argument to moveAllOnLine, and was called from main (see the  
line above that in the traceback). Now we look near that line:



for i in range(2):
moveAllOnLine(faceList, dx, 0, stepsAcross, wait)
moveAllOnLine(faceList, -dx, dy, stepsAcross/2, wait)
moveAllOnLine(faceList, -dx, -dy, stepsAcross//2, wait)


Don't you see something suspicious...?


--
Gabriel Genellina

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Thorsten Kampe
* Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)
> Thanks, RDM, for stating the right approach.
> Thanks, Steve, for teaching by example.
> 
> I wonder why the email.message_from_string() method doesn't call
> email.header.decode_header() automatically.

And I wonder why you would think the header contains Unicode characters 
when it says "us-ascii" ("=?us-ascii?Q?"). I think there is a tendency 
to label everything "Unicode" someone does not understand.

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


File Path retrieving problem

2009-02-25 Thread music24by7
Hi all,

I am new to Python, i have installed python 2.5.4 and it is my
requirement.

I need to retrieve the path of filename in python.

I have found some API's to get this:

from os.path import realpath
print realpath("NEWS.txt")  # here NEWS.txt exists and it shows the
path of the file as C:\Python25\WorkSpace\NEWS.txt
print realpath("abc.txt") # here abc.txt does not exist but still it
shows C:\Python25\WorkSpace\abc.txt

can anybody tell the reason why


Now took some safety measures:

found = lexists(realpath(filename))
if found == 0:
print "Not Found"
else:
print realpath(filename)

i have given the filename as "NEWS.txt" and "abc.txt" but i am always
getting the output as "Not Found"


Can anyone please tell me where am i doing wrong

also any suggestions to retrieve the filepath from a given filename is
highly appreciated.

Thanks in advance.


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


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Christian Meesters
Thanks David!

It's still not debugged, but indeed: I get a bunch of warnings. And this 
already showed me that there are more potential problems than my first 
guess indicated. Alas, for my specific problem I cannot work with ints 
chars and doubles. I need to have unsigned longs at some points.

Well, I'll sort it out.

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


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 10:40:23 -0200, Christian Meesters   
escribió:



I have a problem using my software on my 64bit laptop, after an update of
my system. The same code still runs on 32bit Intel, but on my laptop I
provoke the crash in the title. The crash is caused - as narrowed down by
me - by returning a static PyObject from a C-extension function.


I think you got all the reference counts wrong, specially dummy1, dummy2  
and r.


(BTW, when you know the size, it's better to use PyList_New(size) +  
PyList_SET_ITEM instead of PyList_New(0) + PyList_Append)


--
Gabriel Genellina

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


Newbie : this works in one direction but get the error on the return path

2009-02-25 Thread Gary Wood
'''Test animation of a group of objects making a face.
Combine the face elements in a function, and use it twice.
Have an extra level of repetition in the animation.
'''

from graphics import *
import time

def moveAll(shapeList, dx, dy):
''' Move all shapes in shapeList by (dx, dy).'''
for shape in shapeList: 
shape.move(dx, dy)


def moveAllOnLine(shapeList, dx, dy, repetitions, delay):
'''Animate the shapes in shapeList along a line.
Move by (dx, dy) each time.
Repeat the specified number of repetitions.
Have the specified delay (in seconds) after each repeat.
'''
for i in range(repetitions):
moveAll(shapeList, dx, dy)
time.sleep(delay)


def makeFace(center, win):
'''display face centered at center in window win.
Return a list of the shapes in the face.
'''

head = Circle(center, 25)
head.setFill("yellow")
head.draw(win)

eye1Center = center.clone()  #face positions are relative to the center
eye1Center.move(-10, 5)  #locate further points in relation to others
eye1 = Circle(eye1Center, 5)
eye1.setFill('blue')
eye1.draw(win)

eye2End1 = eye1Center.clone()
eye2End1.move(15, 0)
eye2End2 = eye2End1.clone()
eye2End2.move(10, 0)

eye2 = Line(eye2End1, eye2End2)
eye2.setWidth(3)
eye2.draw(win)

noseTop = center.clone()
noseTop.move(0,0)
noseLeft = noseTop.clone()
noseLeft.move(-2,-2)
noseRight = noseLeft.clone()
noseRight.move(5,0)
nose = Polygon(noseTop,noseLeft,noseRight)
nose.draw(win)


mouthCorner1 = center.clone()
mouthCorner1.move(-10, -10)
mouthCorner2 = mouthCorner1.clone()
mouthCorner2.move(20, -5)

mouth = Oval(mouthCorner1, mouthCorner2)
mouth.setFill("red")
mouth.draw(win)

return [head, eye1, eye2,nose, mouth]

def main():
winWidth = 300
winHeight = 300
win = GraphWin('Back and Forth', winWidth, winHeight)
win.setCoords(0, 0, winWidth, winHeight)  #make right side up coordinates!

rect = Rectangle(Point(200, 90), Point(220, 100))
rect.setFill("blue")
rect.draw(win)

faceList = makeFace(Point(40, 100), win)
faceList2 = makeFace(Point(150,125), win)

stepsAcross = 40
dx = 5
dy = 3
wait = .1
for i in range(2):
moveAllOnLine(faceList, dx, 0, stepsAcross, wait)
moveAllOnLine(faceList, -dx, dy, stepsAcross/2, wait)
moveAllOnLine(faceList, -dx, -dy, stepsAcross//2, wait) 

Text(Point(winWidth/2, 20), 'Click anywhere to quit.').draw(win)
win.getMouse()
win.close()

main()


Traceback (most recent call last):
  File "E:/python/handson/backAndForth4.py", line 97, in 
main()
  File "E:/python/handson/backAndForth4.py", line 90, in main
moveAllOnLine(faceList, -dx, dy, stepsAcross/2, wait)
  File "E:/python/handson/backAndForth4.py", line 21, in moveAllOnLine
for i in range(repetitions):
TypeError: 'float' object cannot be interpreted as an integer
>>> --
http://mail.python.org/mailman/listinfo/python-list


File Path retrieving problem

2009-02-25 Thread Sudhir Kakumanu
Hi all,

I am new to Python, i have installed python 2.5.4 and it is my requirement.

I need to retrieve the path of filename in python.

I have found some API's to get this:

from os.path import realpath
print realpath("NEWS.txt")  # here NEWS.txt exists and it shows the path of
the file as C:\Python25\WorkSpace\NEWS.txt
print realpath("abc.txt") # here abc.txt does not exist but still it shows
C:\Python25\WorkSpace\abc.txt

can anybody tell the reason why


Now took some safety measures:

found = lexists(realpath(filename))
if found == 0:
print "Not Found"
else:
print realpath(filename)

i have given the filename as "NEWS.txt" and "abc.txt" but i am always
getting the output as "Not Found"


Can anyone please tell me where am i doing wrong

also any suggestions to retrieve the filepath from a given filename is
highly appreciated.

Thanks in advance.


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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Steve Holden
rdmur...@bitdance.com wrote:
> Steve Holden  wrote:
> from email.header import decode_header
> print
>> decode_header("=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=")
>> [('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
>> Records', 'us-ascii')]
> 
> It is interesting that decode_header does what I would consider to be
> the right thing (from a pragmatic standpoint) with that particular bit
> of Microsoft not-quite-standards-compliant brain-damage; but, removing
> the tab is not in fact standards compliant if I'm reading the RFC
> correctly.
> 
You'd need to quote me chapter and verse on that. I understood that the
tab simply indicated continuation, but it's a *long* time since I read
the RFCs.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Roy H. Han
Cool, it works!

Thanks, RDM, for stating the right approach.
Thanks, Steve, for teaching by example.

I wonder why the email.message_from_string() method doesn't call
email.header.decode_header() automatically.


On Wed, Feb 25, 2009 at 9:50 AM,   wrote:
> Steve Holden  wrote:
>> >>> from email.header import decode_header
>> >>> print
>> decode_header("=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=")
>> [('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
>> Records', 'us-ascii')]
>> >>>
>
> It is interesting that decode_header does what I would consider to be
> the right thing (from a pragmatic standpoint) with that particular bit
> of Microsoft not-quite-standards-compliant brain-damage; but, removing
> the tab is not in fact standards compliant if I'm reading the RFC
> correctly.
>
> --RDM
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert PySerial to python 3.0

2009-02-25 Thread Christian Heimes
Seth wrote:
> I tried all three ways you guys listed nothing seems to convert the
> string to bytes.
> 
> It may have to do with the makeDeviceName function, but I can't find
> where that is defined.
> 
> Any thoughts??
> 
> Here is the whole block of code:
> 
> if type(port) in (str, bytes):   #strings are taken directly
> Originally: if type(port) in [type(''), type(u'')]
> self.portstr = port
> else:
> self.portstr = self.makeDeviceName(port)

str and bytes are two totally unrelated things in Python 3.0. You can no
longer treat them equally like str and unicode in Python 2.x. Your could
should not work under Python 3.0 anyway. u'' is invalid in 3.x.

Also please don't use ugly type checks like type(something) == type('').
Starting with Python 2.2 you should use isinstance, for example
isinstance(number, (int, long)).

Christian

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


Re: Lambda function

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 12:42:32 -0200, Albert Hopkins  
 escribió:

On Wed, 2009-02-25 at 17:56 +0530, aditya saurabh wrote:



I defined two functions - lets say
fa = lambda x: 2*x
fb = lambda x: 3*x
Now I would like to use fa*fb in terms of x
is there a way?
Thanks in advance


I'm not sure what "use fa*fb in terms of x" means.

But if you mean fa(x) * fb(x) then it's just:

fa(x) * fb(x)


I think he wants function composition, fb(fa(x)):

def compose(*funcs):
  def composed(x, funcs=funcs):
for f in reversed(funcs):
  x = f(x)
return x
  return composed

def square(x): return x**2
def plus1(x): return x+1
# same as plus1 = lambda x: x+1 but I like the def syntax

y = compose(square, plus1) # y=(x+1)**2
y(3) # -> 16

(or is it fa(fb(x))?)

--
Gabriel Genellina

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Seth
I tried all three ways you guys listed nothing seems to convert the
string to bytes.

It may have to do with the makeDeviceName function, but I can't find
where that is defined.

Any thoughts??

Here is the whole block of code:

if type(port) in (str, bytes):   #strings are taken directly
Originally: if type(port) in [type(''), type(u'')]
self.portstr = port
else:
self.portstr = self.makeDeviceName(port)



On Feb 25, 8:47 am, Christian Heimes  wrote:
> Seth wrote:
> > I implemented "if isinstance(port, str): " that seems to work for now.
>
> > Currently I am running into:
>
> > err, n = win32file.WriteFile(self.hComPort, data,
> > self._overlappedWrite)
> > TypeError: expected an object with a buffer interface
>
> Unicode objects (in Py3k: str) don't implement the buffer interface. You
> have to apply a bytes or bytearray instance.
>
> Christian

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread rdmurray
Steve Holden  wrote:
> >>> from email.header import decode_header
> >>> print
> decode_header("=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=")
> [('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
> Records', 'us-ascii')]
> >>>

It is interesting that decode_header does what I would consider to be
the right thing (from a pragmatic standpoint) with that particular bit
of Microsoft not-quite-standards-compliant brain-damage; but, removing
the tab is not in fact standards compliant if I'm reading the RFC
correctly.

--RDM

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


Re: Extending Python Questions .....

2009-02-25 Thread Ben
On Feb 24, 11:31 am, Nick Craig-Wood  wrote:
> Ben  wrote:
> >  No, It uses the the S-lang for video, and input control. However, SLAG
> >  is more of an abstract layer on top of that.
>
> >  It has a Structures that contains menus and screens (menumodule /
> >  screenmodule). One LOADS them up with parameters.  such as creating
> >  a new menu is like:
>
> >  OpenMenu( Company name, SubSystem, this program name, mode, bottom
> >  status display) - Create initial menu structure Addtomenu(Menu
> >  Block Set name, DISPLAY line, ID, type of program, password ID ) -
> >  add to / update MENU blocks.  runMenu() - Displays the whole create
> >  menu structure.
>
> >  The Menu structure is done in pull downs and scrollable blocks in a
> >  TUI (text User Interface) and using the S-lang screen library is
> >  fully mouseable.
>
> >  The screen module works mych the same way, but with the abiltity to
> >  open and close and work within "Sub Screens".
>
> >  For those who do not know, S-lang is a interpreted language much
> >  like Python. However, there is s direth of library modules. The
> >  original S-lang started out as library of screen of keyboard
> >  modules, but has been expanded
>
> >  My SLAG project does not care in reality WHICH or what language, it
> >  is simply handling menu and screen control.
>
> So do you want to embed python into your code?
>
> I'm still not clear what you are trying to achieve with python, though
> I have a better idea what SLAG is now!
>
> --
> Nick Craig-Wood  --http://www.craig-wood.com/nick

Actually no, I want to EXTEND python using the lower levels of S-lang
screen modules.

My Modules are written in C and are a frame work for building pull-
down menus and data entry screens.

Very nice for writing business applications. Think along the lines of
FoxPro and/or the
"Screen" section in Cobol and you have a pretty good idea of what i
have done.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda function

2009-02-25 Thread Albert Hopkins
On Wed, 2009-02-25 at 17:56 +0530, aditya saurabh wrote:
> I defined two functions - lets say
> fa = lambda x: 2*x
> fb = lambda x: 3*x
> Now I would like to use fa*fb in terms of x
> is there a way?
> Thanks in advance

I'm not sure what "use fa*fb in terms of x" means.

But if you mean fa(x) * fb(x) then it's just:

fa(x) * fb(x)

-a

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


Re: Python dictionary size/entry limit?

2009-02-25 Thread Stefan Behnel
Martin v. Löwis wrote:
> intellimi...@gmail.com wrote:
>> Is there a limit to the size or number of entries that a single 
>> dictionary can possess?
> 
> On a 32-bit system, the dictionary can have up to 2**31 slots,
> meaning that the maximum number of keys is slightly smaller
> (about 2**30).

Which, in practice, means that the size is limited by the available memory.

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


Re: Free Python Training: Washington, DC (3/3-5)

2009-02-25 Thread Aahz
In article ,
Steve Holden   wrote:
>
>Not a joke, but a genuine offer extended to anyone who has already
>contributed to some open source project. See my blog for full details,
>and please pass this on to non-Python programmers who are interested in
>learning the language.
>
>  http://holdenweb.blogspot.com/2009/02/free-python-training.html

Fixed the Subject: line for you.  ;-)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Steve Holden
Roy H. Han wrote:
> On Wed, Feb 25, 2009 at 8:39 AM,   wrote:
[Top-posting corrected]
>> John Machin  wrote:
>>> On Feb 25, 11:07=A0am, "Roy H. Han" 
>>> wrote:
 Dear python-list,

 I'm having some trouble decoding an email header using the standard
 imaplib.IMAP4 class and email.message_from_string method.

 In particular, email.message_from_string() does not seem to properly
 decode unicode characters in the subject.

 How do I decode unicode characters in the subject?
>>> You don't. You can't. You decode str objects into unicode objects. You
>>> encode unicode objects into str objects. If your input is not a str
>>> object, you have a problem.
>> I can't speak for the OP, but I had a similar (and possibly
>> identical-in-intent) question.  Suppose you have a Subject line that
>> looks like this:
>>
>>Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
>> =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
>>
>> How do you get the email module to decode that into unicode?  The same
>> question applies to the other header lines, and the answer is it isn't
>> easy, and I had to read and reread the docs and experiment for a while
>> to figure it out.  I understand there's going to be a sprint on the
>> email module at pycon, maybe some of this will get improved then.
>>
>> Here's the final version of my test program.  The third to last line is
>> one I thought ought to work given that Header has a __unicode__ method.
>> The final line is the one that did work (note the kludge to turn None
>> into 'ascii'...IMO 'ascii' is what deocde_header _should_ be returning,
>> and this code shows why!)
>>
>> ---
>> from email import message_from_string
>> from email.header import Header, decode_header
>>
>> x = message_from_string("""\
>> To: test
>> Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
>> =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
>>
>> this is a test.
>> """)
>>
>> print x
>> print ""
>> for key, header in x.items():
>>print key, 'type', type(header)
>>print key+":", unicode(Header(header)).decode('utf-8')
>>print key+":", decode_header(header)
>>print key+":", ''.join([s.decode(t or 'ascii') for (s, t) in 
>> decode_header(header)]).encode('utf-8')
>> ---
>>
>>
>>From nobody Wed Feb 25 08:35:29 2009
>>To: test
>>Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=
>>=?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
>>
>>this is a test.
>>
>>
>>To type 
>>To: test
>>To: [('test', None)]
>>To: test
>>Subject type 
>>Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
>> =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
>>Subject: [("'u' Obselete type", None), ("-- it is identical to 'd'. (7)", 
>> 'iso-8859-1')]
>>Subject: 'u' Obselete type-- it is identical to 'd'. (7)
>>
>>
> Thanks for writing back, RDM and John Machin.  Tomorrow I'll try the
> code you suggested, RDM.  It looks quite helpful and I'll report the
> results.
> 
> In the meantime, John asked for more data.  The sender's email client
> is Microsoft Outlook 11.  The recipient email client is Lotus Notes.
> 
> 
> 
> Actual Subject
> =?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=
> 
> Expected Subject
> Inteum C/SR User Tip: Quick Access to Recently Opened Inteum C/SR Records
> 
> X-Mailer
> Microsoft Office Outlook 11
> 
> X-MimeOLE
> Produced By Microsoft MimeOLE V6.00.2900.5579
> 
>>> from email.header import decode_header
>>> print
decode_header("=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=")
[('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
Records', 'us-ascii')]
>>>

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Roy H. Han
Thanks for writing back, RDM and John Machin.  Tomorrow I'll try the
code you suggested, RDM.  It looks quite helpful and I'll report the
results.

In the meantime, John asked for more data.  The sender's email client
is Microsoft Outlook 11.  The recipient email client is Lotus Notes.



Actual Subject
=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=

Expected Subject
Inteum C/SR User Tip: Quick Access to Recently Opened Inteum C/SR Records

X-Mailer
Microsoft Office Outlook 11

X-MimeOLE
Produced By Microsoft MimeOLE V6.00.2900.5579



RHH



On Wed, Feb 25, 2009 at 8:39 AM,   wrote:
> John Machin  wrote:
>> On Feb 25, 11:07=A0am, "Roy H. Han" 
>> wrote:
>> > Dear python-list,
>> >
>> > I'm having some trouble decoding an email header using the standard
>> > imaplib.IMAP4 class and email.message_from_string method.
>> >
>> > In particular, email.message_from_string() does not seem to properly
>> > decode unicode characters in the subject.
>> >
>> > How do I decode unicode characters in the subject?
>>
>> You don't. You can't. You decode str objects into unicode objects. You
>> encode unicode objects into str objects. If your input is not a str
>> object, you have a problem.
>
> I can't speak for the OP, but I had a similar (and possibly
> identical-in-intent) question.  Suppose you have a Subject line that
> looks like this:
>
>    Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
> =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
>
> How do you get the email module to decode that into unicode?  The same
> question applies to the other header lines, and the answer is it isn't
> easy, and I had to read and reread the docs and experiment for a while
> to figure it out.  I understand there's going to be a sprint on the
> email module at pycon, maybe some of this will get improved then.
>
> Here's the final version of my test program.  The third to last line is
> one I thought ought to work given that Header has a __unicode__ method.
> The final line is the one that did work (note the kludge to turn None
> into 'ascii'...IMO 'ascii' is what deocde_header _should_ be returning,
> and this code shows why!)
>
> ---
> from email import message_from_string
> from email.header import Header, decode_header
>
> x = message_from_string("""\
> To: test
> Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
> =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
>
> this is a test.
> """)
>
> print x
> print ""
> for key, header in x.items():
>    print key, 'type', type(header)
>    print key+":", unicode(Header(header)).decode('utf-8')
>    print key+":", decode_header(header)
>    print key+":", ''.join([s.decode(t or 'ascii') for (s, t) in 
> decode_header(header)]).encode('utf-8')
> ---
>
>
>    From nobody Wed Feb 25 08:35:29 2009
>    To: test
>    Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=
>            =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
>
>    this is a test.
>
>    
>    To type 
>    To: test
>    To: [('test', None)]
>    To: test
>    Subject type 
>    Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
> =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
>    Subject: [("'u' Obselete type", None), ("-- it is identical to 'd'. (7)", 
> 'iso-8859-1')]
>    Subject: 'u' Obselete type-- it is identical to 'd'. (7)
>
>
> --RDM
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: XML Parsing

2009-02-25 Thread Paul McGuire
On Feb 25, 1:17 am, hrishy  wrote:
> Hi
>
> Something like this
>

>
> Note i am not a python programmer just a enthusiast and i was curious why 
> people on the list didnt suggest a code like above
>

You just beat the rest of us to it - good example of ElementTree for
parsing XML (and I Iearned the '//' shortcut for one or more
intervening tag levels).

To the OP: if you are parsing XML, I would look hard at the modules
(esp. ElementTree) that are written explicitly for XML, before
considering using regular expressions.  There are just too many
potential surprises when trying to match XML tags - presence/absence/
order of attributes, namespaces, whitespace inside tags, to name a
few.

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


Re: Forwarding keyword arguments from one function to another

2009-02-25 Thread Ravi
Thnak you all.

> In the future, explain "didn't work".
> Wrong output? give actual (copy and paste) and expected.
> Error message? give traceback (copy and paste).

I will be careful.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >