Re: How do I say "two classes up in the inheritance chain" in python?

2009-01-27 Thread Duncan Booth
Daniel Fetchinson  wrote:

> 
> class child1( parent1 ):
> def meth( self ):
> # do something c
> super( parent1, self ).meth( ) # I want to invoke meth on
> grandparent 

So just call:
grandparent.meth(self)

If you want to ignore the inheritance hierarchy then go ahead and ignore 
it. Only use super if you want to respect your parents. :)

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse with numpy.array?

2009-01-27 Thread Johan Ekh
Thanks,
James I will try your suggestion!
Robert, what mean with "interactively" is that i would like to create an
array in the ipython shell, e.g. with m_i = array([1.0, 2.0, 3.0]) or
by reading a file with values etc., and then execute my program with "myprog
-m m_i" and thus pass the array "m_i" to my program.

This is just an example. I would like to pass several arrays. My program
will be wrapped inside a loop and the arrays are updated
in each loop.

I have never heard of the "argparse" library. Do you think that it would be
better to use that in my case?

Best regards,
Johan

On Tue, Jan 27, 2009 at 7:12 AM, Robert Kern  wrote:

> On 2009-01-27 00:01, Johan Ekh wrote:
>
>> Thank you James,
>> but I just can't optparse to accept an array, only integers, floats ans
>> strings.
>>
>> My code looks like this
>>
>> from optparse import OptionParser
>> parser = OptionParser()
>> parser.add_option('-t', '--dt', action='store', type='float',
>> dest='dt_i', default=0.1, help='time increment where lsoda saves results')
>> parser.add_option('-T', '--tstop', action='store', type='float',
>> dest='tstop_i', default=1.0, help='duration of the solution')
>> parser.add_option('-m', '--mass_vector', action='store', type='float',
>> dest='m_i', default=[1.0, 1.0], help='vector with lumped masses')
>> op, args = parser.parse_args(sys.argv[1:])
>>
>> I want this to work for m_i = array([1.0, 2.0, 3.0]) but the optparse
>> complains that m_i is not a float.
>>
>
> Well, yes, because you declared that --mass_vector was type='float'. You
> will need to subclass OptionParser in order to parse something that is not
> one of the included types. Yes, it is a bit cumbersome; it's one of the
> reasons I usually use the third-party argparse library instead. You only
> need to supply a parsing function rather than subclass.
>
> I'm afraid I don't really understand what you want when you say that you
> want to create an array interactively. Can you show me an example command
> line that you want to parse? Keep in mind that in many shells, ()[]
> characters are specially handled by the shell and are not convenient for
> users.
>
> BTW, I am subscribed to the list. You do not need to Cc me.
>
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless
> enigma
>  that is made terrible by our own mad attempt to interpret it as though it
> had
>  an underlying truth."
>  -- Umberto Eco
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I say "two classes up in the inheritance chain" in python?

2009-01-27 Thread Ben Finney
Daniel Fetchinson  writes:

> The meth methods in child1 and child2 are the same, except that in
> the last super call, one is referring to parent1, the other is
> referring to parent2.

It's important to learn that, in a language with multiple inheritance,
“superclass of this instance” is *not* the same concept as “parent
of this class”. The class you're coding may end up at any arbitrary
point in a resolution chain, despite what the class inherits from.

It's also important to be aware of the hairiness of Python's ‘super’
http://www.artima.com/weblogs/viewpost.jsp?thread=236275>.

-- 
 \“No matter how cynical you become, it's never enough to keep |
  `\up.” —Jane Wagner, via Lily Tomlin |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I say "two classes up in the inheritance chain" in python?

2009-01-27 Thread Bruno Desthuilliers

Daniel Fetchinson a écrit :

I have two classes that both inherit from two other classes which both
inherit from a single class. The two children have two almost
identical methods:

class grandparent( object ):
def meth( self ):
# do something

class parent1( grandparent ):
def meth( self ):
# do something p1
super( parent1, self ).meth( )

class parent2( grandparent ):
def meth( self ):
# do something p2
super( parent2, self ).meth( )

class child1( parent1 ):
def meth( self ):
# do something c
super( parent1, self ).meth( ) # I want to invoke meth on grandparent


If so, it might be better to explicitly call grandparent.meth (passing 
self as first argument). But this is an obvious design smell IMHO. What 
you have is :


def meth(self):
do_something_more_or_less_specific
call_granparent

Looks like a candidate for a template method. Since you don't have hand 
on Grandparent, the simplest would be to add an additional base class, ie:



class Abstract(Grandparent):
def do_something(self):
raise NotImplementedError

def meth(self):
self.do_something()
super(Abstract, self).meth()


class Parent1(Abstract):
def do_something(self):
   # do something p1

class Parent2(Abstract):
def do_something(self):
   # do something p2


Now you're problem is to factor out do_something() for Child1 and 
Child2. The solution is quite simple : just define it outside the class 
statements, and adds it afterward:


def do_something_children(self):
   # code here

class Child1(Parent1):
# code here

Child1.do_something = do_something_children

class Child2(Parent2):
# code here

Child2.do_something = do_something_children


HTH

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


Re: Counting number of objects

2009-01-27 Thread Kottiyath
Thank you everyone for your very helpful comments and suggestions. I
have interacted in other newsgroups, but this is the most helpful of
them all.

As per the comments, I have now decided to go with the weakref
mechanism - as per Andreas suggestion, functionally it looks correct
that the person should not know the total number of people.
So, in a higher level class, have a weakref list which contains a
reference to each person. Total count will be len(list) at any time.

Now, I couldnt find a weakref list - so I am using WeakKeyDictionary
with the value as None - since len(dict) also should give me the data
any time.

I have another question here. In the documentation, it is mentioned
that -
Note: Caution: Because a WeakKeyDictionary is built on top of a Python
dictionary, it must not change size when iterating over it. This can
be difficult to ensure for a WeakKeyDictionary because actions
performed by the program during iteration may cause items in the
dictionary to vanish "by magic" (as a side effect of garbage
collection).

Now, the only two operations that I am doing are ->
__init__:
  d = weakref.WeakKeyDictionary()

method y:
  x = aa()
  d[x] = None

method z:
  total = len(d)

I believe that all the commands which I perform on WeakKeyDictionary
here - (adding a new element) & (len(d)) - are atomic - or atleast
nothing that can cause any worry as per the Note given above. Can
anyone let me know whether my assumption is correct or not?

Reason: My code has many many number of threads which interact with
each other in myraid ways - so I do want to decrease the number of
locks as much as possible. Especially I do not want to block other
threads just for getting the count.
--
http://mail.python.org/mailman/listinfo/python-list


How to get text from a surface

2009-01-27 Thread gopal mishra
Hi,

 

I am loading an image into pygame. i am trying to get the text from the 

surface. I used pyTesser to read the text from a surface/image but if the 

font size of the text is less then 16, it doesn't give me back the 

correct text from the surface.

Is there any other way to get the text from the pygame surface.

 

Thanks,

Gopal

 

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


Re: I'm a python addict !

2009-01-27 Thread Bruno Desthuilliers

Paul McGuire a écrit :

On Jan 26, 10:54 am, "J. Cliff Dyer"  wrote:

On Fri, 2009-01-23 at 20:25 -0800, Paul McGuire wrote:

Want to change the type/behavior of an object from class A to class
B?  How about this:
aobj = A()
aobj.__class__ = B
Try *that* in as simple-looking C++ or Java!

Wow.  That looks very powerful and fun.  But scary.  Any thoughts on how
you would use that in a way that wouldn't unleash sulphurous code
smells?



This technique is perfect for implementing the GoF State pattern.


Except when it is not !-)

I tried twice to use this trick in "real life" code, and in both cases, 
it ended up being much more complicated than implementing the state 
pattern the canonical way. Not to say that it's hopeless - just that 
there's the usual difference between theory and practice.


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


Re: unittest, order of test execution

2009-01-27 Thread Yinon Ehrlich

> But I was wondering, *should* this test be separated into two unit
> tests, one for each function? On the face of it, it looks that's how it
> should be done.
>
> This, however, raises the question: what's the order of test execution
> in the unittest? And how to pass values between unit tests? Should I
> modify 'self' in unit test?

It's OK to run some tests in the same function.
When one of the asserts fails, following the traceback will lead you
straight to your problem.

The order of test execution is done by default by sorting the test
functions alphabetically.
You may disable the sort by setting self.sortTestMethodsUsing to None.
The simplest way to pass values between tests is to use the class it
(self).

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-27 Thread Bruno Desthuilliers

Russ P. a écrit :

On Jan 26, 1:07 am, Bruno Desthuilliers  wrote:


No. I can change the *team's* code. Please *read*. "team's ownership",
ok ? Or do I have to spell it out loud ? TEAM'S OWNERSHIP. Uh. You get
the message, now ?


Team ownership doesn't necessarily mean that you can just change code
at will. 


Nope, but it surely means that I'm *not* changing "someone else's" code.


In industry, teams usually have a leader that you need to
check with before you can change an interface.


This is totally unrelated.


Would you give all those developers your password to get into the
system? No? Wait a minute ... you mean you wouldn't "trust" them with
your password? But what about "openness"? Are you some sort of fascist
or what?

Goodwin point. You loose. Good bye again, Mr P.


You missed the point once again. In asking if you are a "fascist," I
was *parodying* your attitude that languages with enforced access
restrictions are for "fascists" who don't trust their co-workers or
employees. [I don't recall if you actually used that word


I did not, and you should know better.


or if it was
someone else, but you did use "B&D", which carries the same general
impression.]


Can't you tell the difference, really ?


So I parodied your hyperbole,


Still not. But it's interesting to note that you consider everyone 
disagreeing with you as basically the same person.

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


Re: unittest, order of test execution

2009-01-27 Thread Yinon Ehrlich
On Jan 27, 11:33 am, Yinon Ehrlich  wrote:
> > But I was wondering, *should* this test be separated into two unit
> > tests, one for each function? On the face of it, it looks that's how it
> > should be done.
>
> > This, however, raises the question: what's the order of test execution
> > in the unittest? And how to pass values between unit tests? Should I
> > modify 'self' in unit test?
>
> It's OK to run some tests in the same function.
> When one of the asserts fails, following the traceback will lead you
> straight to your problem.
>
> The order of test execution is done by default by sorting the test
> functions alphabetically.
> You may disable the sort by setting self.sortTestMethodsUsing to None.
see: 
http://docs.python.org/library/unittest.html#unittest.TestLoader.sortTestMethodsUsing
> The simplest way to pass values between tests is to use the class it
> (self).
>
>   Yinon

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


Calling Python-tk code from C/C++

2009-01-27 Thread Rajorshi Biswas
Hello all, This is my first post to this mailing list. Our requirement is to 
invoke a Tkinter python panel from a C++ GUI app where both GUI windows would 
run in 2 separate threads. We have written a sample PyQt application which 
calls this Tk panel using something like this:class 
TkPanel(threading.Thread):def run(self): # call showPaneldef showPanel():# 
create window = Tk.Tk() window.mainloop()def start():t = TkPanel()t.start()Now 
we call this from our main python code:def startPanel(self): import tkPanel 
tkPanel.start() # this calls tkwindow.mainloop() in a separate thread.This 
works absolutely fine when the invoking app is Python. However, we are having 
problems when the invoking app is in C/C++ and we use a similar logic.My 
question boils down to this: If I have code in C++ that has to invoke a 
Pythontk panel such that the panel runs in its own thread, what is the best 
approach?I tried studying the GIL and acquiring releasing/locks, but I must be 
doing something wrong. An
 y help would be greatly appreciated!Thanks!Rajhttp://www.rajorshi.net/blogDear 
pythonlist! Get Yourself a cool, short @in.com Email ID now!
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse question

2009-01-27 Thread Thorsten Kampe
* Pat (Mon, 26 Jan 2009 20:02:59 -0500)
> Up until today, I never needed to pass any arguments to a Python
> program.
> [...]
> getopt resolved my immediate need, but I would like to know how one 
> could use optparse to extract out the options from something like "dir 
> /s /b".

If you actually read the documentation (it's right at the top) you knew 
that this is not possible:
"There are many different syntaxes for options; the traditional Unix 
syntax is a hyphen (“-“) followed by a single letter [...] The GNU 
project introduced "--" [...] These are the only two option syntaxes 
provided by optparse.
Some other option syntaxes that the world has seen include:
[...]
a slash followed by a letter, or a few letters, or a word, e.g. "/f", 
"/file"

These option syntaxes are not supported by optparse, and they never will 
be. This is deliberate: [...] the last only makes sense if you’re 
exclusively targeting VMS, MS-DOS, and/or Windows."

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


socket.unbind or socket.unlisten? - socket.error: (48, 'Address already in use')

2009-01-27 Thread Laszlo Nagy
I have a program that uses socket.bind() and socket.listen() frequently. 
After that program stops, it is not able to bind() again for a while:


File "/home/gandalf/Python/Lib/orb/accesspoints/srvtcp.py", line 27, in 
__init__

   self.serversocket.bind((self.listen_address,self.port))
 File "", line 1, in bind
socket.error: (48, 'Address already in use')


The problem with this, is that this server program SOMETIMES need to be 
restarted very quickly. I tried to find the solution in the socket 
module. But there is no "socket.unbind" or "socket.unlisten". How can I 
tell the OS that I do not want to listen on that address anymore, so 
other programs can bind on it immediatelly?


(Yes I know that I can use setsockopt to allow listening multiple 
sockets on the same address, but this is NOT what I need...)


Thanks,

  Laszlo

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


Re: Iterating through a file significantly slower when file has big buffer

2009-01-27 Thread Roger Binns
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

pyt...@bdurham.com wrote:
> The following tests were run on a Windows XP system using Python 2.6.1

Unless you changed the defaults, the Windows XP system cache size is
10MB.  When you use a larger read size, chances are it is blowing out
that cache and causes metadata (file block locations) to have to be
reread on your next read.

You are also funnelling all the data through your CPU cache with a
similar effect although it will be less noticeable.

To change XP cache sizes, see:

 http://marc.info/?l=sqlite-users&m=116743785223905&w=2
 http://support.microsoft.com/kb/895932
 http://www.techspot.com/tweaks/memory-winxp/

Roger
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkl+4SkACgkQmOOfHg372QRgcACfVOdUWQGyj8xtNvHob/CtcM8g
JsEAoKt/xI36iR5RuQOfZDMz2ze4L3Ia
=DrDw
-END PGP SIGNATURE-

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


Re: USB in python

2009-01-27 Thread Lie Ryan
On Mon, 26 Jan 2009 11:08:48 -0600, Unknown wrote:

> On 2009-01-26, Lie Ryan  wrote:
> 
>> How about (a crazy idea) using the audio jack out? (DISCLAIMER: Little
>> Hardware Experience). High pitched sound (or anything in sound-ology
>> that means high voltage) means the device is on and low pitched sound
>> off.
> 
>  1) Pitch has nothing to do with voltage.  A high-pitch sound
> and a low pitch sound can have the exact same voltage.
> 
>  2) The OP's device requires quite a bit of power.  There is
> almost no power available from the line-out jack, and the voltage is
> limited to about 1V.  If his sound card has a power-amp (none do
> these days), he might be able to get a usable amount of power.
> 
>> The device will need an additional transistor to separate low voltage
>> from the high voltage.
> 
> He'll need more than a transistor.  He needs a power supply, some sort
> of rectifier/detector, and a comparitor. It would be more interesting to
> use notch filters to detect different frequencies so that you could have
> multiple output "bits".

>From the little I know on electronics, a simple, single transistor would 
(almost) immediately switch from on-to-off-to-on depending on the voltage 
of the control pin (I think it was the middle pin). I was suggesting this 
simplistic hack because as far as I comprehend the OP's need, he only 
need on-off switch instead of a complex multiple output bits.

>> I don't know how much power can be pulled from jack out,
> 
> Almost none, and what's there is very low voltage.

That's why the power is taken from USB port.

>> but for a home brewn device it is still feasible to draw power from USB
>> and signal from jack out.
> 
> It would probably be easier to buy a USB-parallel port chip. Then he's
> got power from the USB bus and something like 14 parallel I/O pins he
> can control.  Alternatively A USB-serial chip will provide 2 outputs and
> 4 inputs.

The idea was made on the basis that a USB microcontroller is not used. 
Getting power from USB should be much easier than getting data while the 
jack out can provide simple on-off signal.

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


Re: practical limits of urlopen()

2009-01-27 Thread Lie Ryan
On Sat, 24 Jan 2009 09:17:10 -0800, webcomm wrote:

> Hi,
> 
> Am I going to have problems if I use urlopen() in a loop to get data
> from 3000+ URLs?  There will be about 2KB of data on average at each
> URL.  I will probably run the script about twice per day.  Data from
> each URL will be saved to my database.
> 
> I'm asking because I've never opened that many URLs before in a loop.
> I'm just wondering if it will be particularly taxing for my server. Is
> it very uncommon to get data from so many URLs in a script?  I guess
> search spiders do it, so I should be able to as well?

urllib doesn't have any limits, what might limit your program is your 
connection speed and the hardware where the server and downloader is on. 
Getting 3000 URLs is about 6MBs, a piece of cake for a sufficiently 
modern machine on a decent internet connection (the real calculation 
isn't that simple though, there is also some cost associated with sending 
and processing HTML headers).

Google indexes millions of pages per day, but they also have one of the 
most advanced server farm in the world.

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


C-Python API problem

2009-01-27 Thread Rajorshi Biswas
Hi, I was trying out the sample program to load a python script from C in the 
Python tutorial at http://docs.python.org/extending/embedding.html (Section: 
Pure Embedding).Usage: call pythonfile funcname [args] When running this 
script, I can run things like the following:call mytest foobut not any function 
which calls a Tk function:call mytest teekay Here is my mytest.py module:def 
foo():print "func"def teekay():import Tkinterr=Tkinter.Tkr()I get the following 
error in the latter case:Traceback (most recent call last):...import Tkinter 
...import tkinter # If this fails your Python may not be configured for 
TkImportError: 
/software/lib/Linuxx86/python2.6/lib/python2.6/libdynload/tkinter.so: undefined 
symbol: PyTrueStructCall failedObviously, trying this from within a Python 
shell works fine.Any clues?Thanks,RajRajhttp://www.rajorshi.net/blogDear 
pythonlist ! Get Yourself a cool, short @in.com Email ID now!
--
http://mail.python.org/mailman/listinfo/python-list


OpenGL in TK

2009-01-27 Thread Almar Klein
Hi list!

I am using pyOpenGL to do some 3D rendering. For now I am
quite happy with the GLCanvas of wx, but I may want to publish
some stuff later, and it would be nice if people would not need wx.

I found that there used to be a TK widget called Togl, but it is not
(anymore?) included in the TK package that comes with Python.

Have others been able to use Togl, or any other OpenGL widget in
TK?


Thanks for any help,
  Almar


PS: I use python 2.5.2 on windows
--
http://mail.python.org/mailman/listinfo/python-list


Re: Plugin system, RuntimeWarning: Parent module 'ext_abc' not found while handling absolute import

2009-01-27 Thread Gabriel Genellina

En Mon, 26 Jan 2009 17:06:20 -0200, Torsten Mohr 
escribió:


So mymodule is actually a package. Packages should *not* appear in
sys.path.


Oh, how does it find modules then?  I thought that would be PYTHONPATH or
sys.path ?


The directory CONTAINING file "foo.py" must be in sys.path if you want to
import foo.

The directory CONTAINING package "bar" must be in sys.path if you want to
import bar.

There were some threds on this topic last month, see this by example:
http://groups.google.com/group/comp.lang.python/t/ed47d8e31ca3d411/

--
Gabriel Genellina

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


Class behaving like a static class

2009-01-27 Thread gu

Hi to all,
i have a module (a single .py file, actually), with a class called 
HashedDir.


when i import the file and instanciate 2 instances of that class, when i 
check the object's fields they're always the same, even if the two 
objects should be different.


Eg:

h1 = HashedDir('someValue')
print h1.value # someValue
h2 = HashedDir('someOtherValue')
print h1.value # someOtherValue
print h2.value # someOtherValue

Any idea?
Thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: USB in python

2009-01-27 Thread Muriel de Souza Godoi
Some people got success in Arduindo using an older mobile cable which works
as USB/Serial converters.
So you can read and write data as a serial port using pyserial.

On Tue, Jan 27, 2009 at 8:31 AM, Lie Ryan  wrote:

> On Mon, 26 Jan 2009 11:08:48 -0600, Unknown wrote:
>
> > On 2009-01-26, Lie Ryan  wrote:
> >
> >> How about (a crazy idea) using the audio jack out? (DISCLAIMER: Little
> >> Hardware Experience). High pitched sound (or anything in sound-ology
> >> that means high voltage) means the device is on and low pitched sound
> >> off.
> >
> >  1) Pitch has nothing to do with voltage.  A high-pitch sound
> > and a low pitch sound can have the exact same voltage.
> >
> >  2) The OP's device requires quite a bit of power.  There is
> > almost no power available from the line-out jack, and the voltage is
> > limited to about 1V.  If his sound card has a power-amp (none do
> > these days), he might be able to get a usable amount of power.
> >
> >> The device will need an additional transistor to separate low voltage
> >> from the high voltage.
> >
> > He'll need more than a transistor.  He needs a power supply, some sort
> > of rectifier/detector, and a comparitor. It would be more interesting to
> > use notch filters to detect different frequencies so that you could have
> > multiple output "bits".
>
> >From the little I know on electronics, a simple, single transistor would
> (almost) immediately switch from on-to-off-to-on depending on the voltage
> of the control pin (I think it was the middle pin). I was suggesting this
> simplistic hack because as far as I comprehend the OP's need, he only
> need on-off switch instead of a complex multiple output bits.
>
> >> I don't know how much power can be pulled from jack out,
> >
> > Almost none, and what's there is very low voltage.
>
> That's why the power is taken from USB port.
>
> >> but for a home brewn device it is still feasible to draw power from USB
> >> and signal from jack out.
> >
> > It would probably be easier to buy a USB-parallel port chip. Then he's
> > got power from the USB bus and something like 14 parallel I/O pins he
> > can control.  Alternatively A USB-serial chip will provide 2 outputs and
> > 4 inputs.
>
> The idea was made on the basis that a USB microcontroller is not used.
> Getting power from USB should be much easier than getting data while the
> jack out can provide simple on-off signal.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Msc. Muriel de Souza Godoi
Computation Department
State University of Maringá
Brazil
--
http://mail.python.org/mailman/listinfo/python-list


Re: Process crash with no reason

2009-01-27 Thread gil . shinar
On Jan 26, 8:40 pm, Philip Semanchuk  wrote:
> On Jan 26, 2009, at 1:13 PM, gil.shi...@gmail.com wrote:
>
> > Hi All,
>
> > I'm running a program that is acting as a nice interface to sybase'
> > replication server. The program is using the cherrypy web service for
> > the GUI. The process is crashing every few days with no reason. In the
> > log I can see INFO and DEBUG (No ERROR) log lines and I do not get any
> > TraceBack python's message. This program is running on solaris 9
> > machine.
> > Where can I see or what can I do in order to find out what causes the
> > process to crash?
> > I have tried simulating a "traceBack" message and I could see this
> > traceback message in one of the log files I'm using. When the process
> > crashes without my help, I don't have a clue.
> > Let me know if you need any other info
>
> Although Python isn't immune to fatal errors like you describe, I'd  
> immediately suspect a 3rd-party module instead, esp. one written in C  
> or C++. Are you using anything like that?

No I do not.
Is there a way to monitor who had "killed" my process?

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


Re: Class behaving like a static class

2009-01-27 Thread Bruno Desthuilliers

gu a écrit :

Hi to all,
i have a module (a single .py file, actually), with a class called 
HashedDir.


when i import the file and instanciate 2 instances of that class, when i 
check the object's fields they're always the same, even if the two 
objects should be different.


Eg:

h1 = HashedDir('someValue')
print h1.value # someValue
h2 = HashedDir('someOtherValue')
print h1.value # someOtherValue
print h2.value # someOtherValue

Any idea?


Yes : post the relevant code - or at least the minimal code that 
reproduces the unexpected behaviour.


There are quite a couple gotchas regarding class-vs-instance-attributes 
and default-params, but none of them matches what you have here - at 
least if 'value' is an attribute set on 'self' from within the 
initializer. So either the above snippet is made up and you're in fact 
having this problem with mutable attributes (like 'value' is a list and 
you're appending to it) or there's something else in your code.

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


Re: Process crash with no reason

2009-01-27 Thread Tim Golden

gil.shi...@gmail.com wrote:

On Jan 26, 8:40 pm, Philip Semanchuk  wrote:

On Jan 26, 2009, at 1:13 PM, gil.shi...@gmail.com wrote:


Hi All,
I'm running a program that is acting as a nice interface to sybase'
replication server. The program is using the cherrypy web service for
the GUI. The process is crashing every few days with no reason. In the
log I can see INFO and DEBUG (No ERROR) log lines and I do not get any
TraceBack python's message. This program is running on solaris 9
machine.
Where can I see or what can I do in order to find out what causes the
process to crash?
I have tried simulating a "traceBack" message and I could see this
traceback message in one of the log files I'm using. When the process
crashes without my help, I don't have a clue.
Let me know if you need any other info
Although Python isn't immune to fatal errors like you describe, I'd  
immediately suspect a 3rd-party module instead, esp. one written in C  
or C++. Are you using anything like that?


No I do not.


Then how are you interacting with Sybase?

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


Re: socket.unbind or socket.unlisten? - socket.error: (48, 'Addressalready in use')

2009-01-27 Thread Hendrik van Rooyen
"Laszlo Nagy"  wrote:

> I have a program that uses socket.bind() and socket.listen() frequently. 
> After that program stops, it is not able to bind() again for a while:
> 

 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

This does the trick for me.

- Hendrik


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


Re: unable to print Unicode characters in Python 3

2009-01-27 Thread Giampaolo Rodola'
On 26 Gen, 19:16, jefm  wrote:
> Hi,
> while checking out Python 3, I read that all text strings are now
> natively Unicode.
> In the Python language reference (http://docs.python.org/3.0/reference/
> lexical_analysis.html) I read that I can show Unicode character in
> several ways.
> "\u" supposedly allows me to specify the Unicode character by hex
> number and the format  "\N{name}" allows me to specify by Unicode
> name.
> Neither seem to work for me.
> What am I doing wrong ?
>
> Please see error output below where I am trying to show the EURO sign
> (http://www.fileformat.info/info/unicode/char/20ac/index.htm):
>
> Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> print('\u20ac')
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "c:\python30\lib\io.py", line 1491, in write
>     b = encoder.encode(s)
>   File "c:\python30\lib\encodings\cp437.py", line 19, in encode
>     return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in
> position 0: character maps to 
>
> >>> print ("\N{EURO SIGN}")
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "c:\python30\lib\io.py", line 1491, in write
>     b = encoder.encode(s)
>   File "c:\python30\lib\encodings\cp437.py", line 19, in encode
>     return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in
> position 0: character maps to 

I have this same issue on Windows.
Note that on Python 2.6 it works:

Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print unicode('\u20ac')
\u20ac

This is pretty serious, IMHO, since breaks any Windows software
priting unicode to stdout.
I've filed an issue on the Python bug tracker:
http://bugs.python.org/issue5081


--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse question

2009-01-27 Thread Pat




If you mean with "/" as the option designator instead of "-": there
doesn't appear to be a documented way of doing it. You would have to
do some social engineering on the users to get them used to doing "dir
-s -b". In any case I thought the number of Windows users who know how
to fire up a Command Prompt window was diminishingly small ... you
actually have users who know how to use commands like "dir /s /b"?



I used dir /s /b as a trivial Windows example.  I use Windows for 
personal use but Ubuntu for work and programming.


Personally, I use dir /s /b all the time on Windows since the /b option 
finds files *much* faster; maybe 10x or 100x faster but I didn't get out 
a stopwatch.

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


Re: optparse question

2009-01-27 Thread Pat

Thorsten Kampe wrote:

* Pat (Mon, 26 Jan 2009 20:02:59 -0500)

Up until today, I never needed to pass any arguments to a Python
program.
[...]
getopt resolved my immediate need, but I would like to know how one 
could use optparse to extract out the options from something like "dir 
/s /b".


If you actually read the documentation (it's right at the top) you knew 
that this is not possible:
"There are many different syntaxes for options; the traditional Unix 
syntax is a hyphen (“-“) followed by a single letter [...] The GNU 
project introduced "--" [...] These are the only two option syntaxes 
provided by optparse.

Some other option syntaxes that the world has seen include:
[...]
a slash followed by a letter, or a few letters, or a word, e.g. "/f", 
"/file"


These option syntaxes are not supported by optparse, and they never will 
be. This is deliberate: [...] the last only makes sense if you’re 
exclusively targeting VMS, MS-DOS, and/or Windows."


Thorsten


Sigh.  I used dir /s /b as a simple Windows command with a flag (it 
could have been dir /s) because it was the first thing that popped into 
my mind.


I had no idea people were going to get so upset that I used a Windows 
example and go off on a tear.

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


Re: unable to print Unicode characters in Python 3

2009-01-27 Thread Denis Kasak
On Tue, Jan 27, 2009 at 1:52 PM, Giampaolo Rodola'  wrote:
> I have this same issue on Windows.
> Note that on Python 2.6 it works:
>
> Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 print unicode('\u20ac')
> \u20ac

Shouldn't this be

print unicode(u'\u20ac')

on 2.6? Without the 'u' prefix, 2.6 will just encode it as a normal
(byte) string and escape the backslash. In Python 3.0 you don't need
to do this because all strings are "unicode" to start with. I suspect
you will see the same error with 2.6 on Windows once you correct this.

(note to Giampaolo: sorry, resending this because I accidentally
selected "reply" instead of "reply to all")

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


Re: unable to print Unicode characters in Python 3

2009-01-27 Thread Stephen Hansen
>
> Note that on Python 2.6 it works:
>
> Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> print unicode('\u20ac')
> \u20ac
>

Note that in Python 2.6 it expressly *does not* work, by your own example.
Although I think the example is wrong and that you need to print u'\u20ac'
in 2.6 unless you are importing unicode_literals from __future__; otherwise
'\u20ac' is an ASCII string of 6 characters.

"Works" would result, I'd think, in a unicode character being actually
written to stdout: that is not happening. Instead a backslash pattern of
ASCII characters meant to represent a Unicode character that -can't- be
written to that stream are being written to stdout. The two aren't even kind
of the same: but this is hardly something Python has a lot of control
over... Windows software printing unicode to stdout was always a bit broken.
IF you set the code page you could print some -- and IF you changed the font
on the command prompt to a /non/-default font you could actually display
others -- but it really is sort of a sucky situation, Unicode in Console
windows on Windows.

I really don't know how Python could do it better here: between the default
code page on Windows being completely lame, the default font not supporting
Unicode really... ISTM that having cross-platform apps which output unicode
(really UTF8 probably) to stdout are just not really doable. But if you
really want to you can always rebind sys.stdout with an error mode of
"backslashreplace" or "xmlcharrefreplace" (which I do in one situation where
I have a subprocess that has to output 'unicode' to a parent process)
instead of 'strict'.

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


Re: optparse question

2009-01-27 Thread John Machin
On Jan 28, 12:06 am, Pat  wrote:
> Thorsten Kampe wrote:
> > * Pat (Mon, 26 Jan 2009 20:02:59 -0500)
> >> Up until today, I never needed to pass any arguments to a Python
> >> program.
> >> [...]
> >> getopt resolved my immediate need, but I would like to know how one
> >> could use optparse to extract out the options from something like "dir
> >> /s /b".
>
> > If you actually read the documentation (it's right at the top) you knew
> > that this is not possible:
> > "There are many different syntaxes for options; the traditional Unix
> > syntax is a hyphen (“-“) followed by a single letter [...] The GNU
> > project introduced "--" [...] These are the only two option syntaxes
> > provided by optparse.
> > Some other option syntaxes that the world has seen include:
> > [...]
> > a slash followed by a letter, or a few letters, or a word, e.g. "/f",
> > "/file"
>
> > These option syntaxes are not supported by optparse, and they never will
> > be. This is deliberate: [...] the last only makes sense if you’re
> > exclusively targeting VMS, MS-DOS, and/or Windows."
>
> > Thorsten
>
> Sigh.  I used dir /s /b as a simple Windows command with a flag (it
> could have been dir /s) because it was the first thing that popped into
> my mind.
>
> I had no idea people were going to get so upset that I used a Windows
> example and go off on a tear.

Nobody is upset, and nobody has "gone off on a tear". The point about
the "Windows example" is that the docs say in a close-to-screamingly-
obvious manner that /options are not supported, no matter what
religion uses them. It was not, and still is not, apparent what you
really wanted. We're all patiently waiting for you to rephrase the
question(s).
--
http://mail.python.org/mailman/listinfo/python-list


Re: socket.unbind or socket.unlisten? - socket.error: (48, 'Address already in use')

2009-01-27 Thread Jean-Paul Calderone

On Tue, 27 Jan 2009 10:49:03 +0100, Laszlo Nagy  wrote:
I have a program that uses socket.bind() and socket.listen() frequently. 
After that program stops, it is not able to bind() again for a while:


File "/home/gandalf/Python/Lib/orb/accesspoints/srvtcp.py", line 27, in 
__init__

   self.serversocket.bind((self.listen_address,self.port))
 File "", line 1, in bind
socket.error: (48, 'Address already in use')


The problem with this, is that this server program SOMETIMES need to be 
restarted very quickly. I tried to find the solution in the socket module. 
But there is no "socket.unbind" or "socket.unlisten". How can I tell the OS 
that I do not want to listen on that address anymore, so other programs can 
bind on it immediatelly?


(Yes I know that I can use setsockopt to allow listening multiple sockets on 
the same address, but this is NOT what I need...)


Actually, SO_REUSEADDR is probably just what you want.  Since I can't see
your code and I don't know under what situations it fails, I can only guess
at the problem, but my guess is that you have connections from the first run
of your app left in the TIME_WAIT state and they are preventing you from
binding to the address again in the second run of your app.  Setting the
SO_REUSEADDR flag on POSIX fixes this problem (don't set it on Windows,
though).

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


Re: unable to print Unicode characters in Python 3

2009-01-27 Thread John Machin
On Jan 27, 11:52 pm, "Giampaolo Rodola'"  wrote:
> On 26 Gen, 19:16, jefm  wrote:
>
>
>
> > Hi,
> > while checking out Python 3, I read that all text strings are now
> > natively Unicode.
> > In the Python language reference (http://docs.python.org/3.0/reference/
> > lexical_analysis.html) I read that I can show Unicode character in
> > several ways.
> > "\u" supposedly allows me to specify the Unicode character by hex
> > number and the format  "\N{name}" allows me to specify by Unicode
> > name.
> > Neither seem to work for me.
> > What am I doing wrong ?
>
> > Please see error output below where I am trying to show the EURO sign
> > (http://www.fileformat.info/info/unicode/char/20ac/index.htm):
>
> > Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
> > (Intel)] on win32
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > print('\u20ac')
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "c:\python30\lib\io.py", line 1491, in write
> >     b = encoder.encode(s)
> >   File "c:\python30\lib\encodings\cp437.py", line 19, in encode
> >     return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> > UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in
> > position 0: character maps to 
>
> > >>> print ("\N{EURO SIGN}")
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "c:\python30\lib\io.py", line 1491, in write
> >     b = encoder.encode(s)
> >   File "c:\python30\lib\encodings\cp437.py", line 19, in encode
> >     return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> > UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in
> > position 0: character maps to 
>
> I have this same issue on Windows.
> Note that on Python 2.6 it works:
>
> Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> print unicode('\u20ac')
>
> \u20ac
>
> This is pretty serious, IMHO, since breaks any Windows software
> priting unicode to stdout.
> I've filed an issue on the Python bug tracker:http://bugs.python.org/issue5081

Hello hello -- (1) that's *not* attempting to print Unicode. Look at
your own output ... "\u20ac"" was printed, not a euro character!!!
With 2.X for *any* X:
>>> guff ='\u20ac'
>>> type(guff)

>>> len(guff)
6

(2) Printing Unicode to a Windows console has never *worked*; that's
why this thread was pursuing the faint ray of hope offered by cp65001.


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


A Twisted Design Decision

2009-01-27 Thread koranthala
Twisted, being twisted in its behavior is causing quite a lot of
confusion in design decisions.

I will put forward a comparison of reactor and non-reactor patterns.
The code is not exact - whatever is shown is the gist of it.

For example, a message handler - in a usual scenario:
class messageHandler:
   def run():
 msg = self.get_next_msg()
 if not msg.send():
 self.handle_failure()

To handle parallel execution, we will have to use threads, but the
code flow is similar.

How do we do the same in a reactor pattern (Twisted)?
msg.send will cause a deferred to be raised - the failure, if it
happens will happen much later.
i.e. other than sending messageHandler object in msg.send(), I cannot
see any mechanism of running handle_failure.

In Twisted:
class messageHandler:
   def run():
 msg = self.get_next_msg()
 msg.send(self):

class msgClass:
def send(o):
d = deferred.addCallBack(success_handler, o).addErrBack
(failure_handler, o)

def failure_handler(o):
o.handle_failure()

Basically, what I find is that a lot of functional encapsulation is
now lost by following reactor pattern. handle_failure is
messageHandlers code and makes for pretty viewing if called from
inside messageHandler itself. But, due to the twisted nature of
reactor pattern, the msg Class - who is functionally a lower class to
messageHandler invoking messageHandler's code.

Is there a way to solve this in a more beautiful way? Am I missing
something here?

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


Re: A Twisted Design Decision

2009-01-27 Thread Jean-Paul Calderone

On Tue, 27 Jan 2009 05:46:25 -0800 (PST), koranthala  
wrote:

Twisted, being twisted in its behavior is causing quite a lot of
confusion in design decisions.


I'm not sure I agree with your premise. ;)


I will put forward a comparison of reactor and non-reactor patterns.
The code is not exact - whatever is shown is the gist of it.

For example, a message handler - in a usual scenario:
class messageHandler:
  def run():
msg = self.get_next_msg()
if not msg.send():
self.handle_failure()

To handle parallel execution, we will have to use threads, but the
code flow is similar.

How do we do the same in a reactor pattern (Twisted)?
msg.send will cause a deferred to be raised - the failure, if it
happens will happen much later.
i.e. other than sending messageHandler object in msg.send(), I cannot
see any mechanism of running handle_failure.

In Twisted:
class messageHandler:
  def run():
msg = self.get_next_msg()
msg.send(self):

class msgClass:
   def send(o):
   d = deferred.addCallBack(success_handler, o).addErrBack
(failure_handler, o)

   def failure_handler(o):
   o.handle_failure()


This doesn't look like a correct or faithful translation of the original.
Here are two possibilities.  First:

   class messageHandler:
   def run():
   msg = self.get_next_msg()
   d = msg.send()
   def cbSendFailed(result):
   if not result:
   self.handle_failure()
   d.addErrback(cbSendFailed)
   return d

Next:

   class messageHandler:
   @inlineCallbacks
   def run():
   msg = self.get_next_msg()
   if not (yield msg.send()):
   self.handle_failure()

These are both just straight translations from your version so as to
be able to handle a Deferred from `msg.send´.


Basically, what I find is that a lot of functional encapsulation is
now lost by following reactor pattern. handle_failure is
messageHandlers code and makes for pretty viewing if called from
inside messageHandler itself. But, due to the twisted nature of
reactor pattern, the msg Class - who is functionally a lower class to
messageHandler invoking messageHandler's code.


You don't need to lose anything.  I don't know what your motivation was
for re-arranging the code when you wrote the Twisted version, but it doesn't
appear to have been necessary.


Is there a way to solve this in a more beautiful way? Am I missing
something here?



Hope this helps,

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


Re: print formating for matrix/table

2009-01-27 Thread Alan G Isaac

You could try SimpleTable:
http://code.google.com/p/econpy/source/browse/trunk/utilities/text.py

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


Python-URL! - weekly Python news and links (Jan 27)

2009-01-27 Thread Gabriel Genellina
QOTW:  "Whatever sufficiently sophisticated topic was ... initially
discussed it ends all up in a request for removing reference counting
and the GIL." - Kay Schluehr
http://groups.google.com/group/comp.lang.python/msg/6a152ff76cf313ff


Looking for a different kind of (editor|environment|interfase) like
TextCalc for Python:
http://groups.google.com/group/comp.lang.python/t/195ebd77f9e191e2/

Inheritance, encapsulation, and hungarian notation:
http://groups.google.com/group/comp.lang.python/t/e6fc603109b42b62/

True, False, None, and the "==" and "is" operators:
http://groups.google.com/group/comp.lang.python/t/21cc0e59bb59c7f1/

Mixing True/False and ints can confuse:
http://groups.google.com/group/comp.lang.python/t/3185626fca2feb9b/

A short (but very interesting) essay on names, expressions, variables,
and binding, by Mark Wooding:
http://groups.google.com/group/comp.lang.python/t/3efb017e757bf3d9/

Using the struct module to handle variable-sized data types:
http://groups.google.com/group/comp.lang.python/t/de5d94ffd953eaba/

Experienced Pythonistas give advice on improving programming skills:
http://groups.google.com/group/comp.lang.python/t/4929f2681088730d/

Kaspersky mentions Python as vector for handset infection:
http://www.theregister.co.uk/2009/01/22/symbian_trojan/

Running Python code on the client side from a web app:
http://groups.google.com/group/comp.lang.python/t/e8131fc8a29db75c/

A new Counter class (similar to bag/multiset in other languages) was
added to the collections module:
http://groups.google.com/group/comp.lang.python/t/debefb159cd0752d/

The longest thread until now, started previous week. Now discussing
enforced data hiding and the Scada language, team management, and who
knows what (I gave up!)
http://groups.google.com/group/comp.lang.python/t/68bc54bca830c46/

Another very long thread: RPython and PyPy advantages, the GIL,
concurrency issues on modern CPU architectures, and removing the
GIL (again!):
http://groups.google.com/group/comp.lang.python/t/d8f15fad0638bca/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful 

Re: Doc for extended call syntax; was: Re: unzip array of arrays?

2009-01-27 Thread Bryan Olson

Mark Wooding wrote:

Steve Holden writes:


No, you aren't mistaken. Looking at the "*" symbol in the 2.6
documentation index it lists only two references. The first is the
language manual's explanation of its use in the def statement, the
second is a transitory reference to its use in function calls, but
that's in the tutorial where it is not likely to get much attention.


There's a full description of it in 5.4.3 in the Language Reference, but
apparently not indexed.


So I guess this means I can duck out of writing up a lecture on my own 
understanding of Python's extended call syntax. Great.


I think I grock the extended call syntax, and when the question came up 
I was surprised not to be able to find where I learned it. Mark, where 
exactly does one look to see this "full description"?



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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-27 Thread Luis Zarrabeitia
On Tuesday 27 January 2009 04:39:02 am Bruno Desthuilliers wrote:
> Still not. But it's interesting to note that you consider everyone
> disagreeing with you as basically the same person.

Hehe. At the beginning of this thread, I also thought that Russ P. and Paul 
Robin were the same person. I have serious problems with names.

[My apologies to both of you, if I said something that made you notice my 
confusion].

P.S: Just to be clear, I'm neither Russ P. nor Paul Robin :D

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: is None vs. == None

2009-01-27 Thread J. Cliff Dyer

On Fri, 2009-01-23 at 19:31 -0500, Benjamin Kaplan wrote:
> 
> 
> On Fri, Jan 23, 2009 at 7:28 PM, Gary Herron
>  wrote:
> Steven D'Aprano wrote:
> > On Fri, 23 Jan 2009 14:58:34 -0500, Gerald Britton wrote:
> >
> >
> >> Hi -- Some time ago I ran across a comment recommending
> using  is
> >> None instead of  == None (also  is not None,
> etc.)
> >>
> >
> > That entirely depends on whether you wish to test for
> something which
> > *is* None or something with *equals* None. Those two things
> have
> > different meanings.
> >
> 
> 
> Actually, for None, those two things *are* the same.   If
> something
> *equals* None, it also *is* None.  This is a consequence of
> the fact
> that there is only ever one value of None anywhere in the
> system.
> 
> Not if someone decided to be a PITA.
>  
> >>> class A(object) :
> ...def __eq__(self, other) :
> ...   return other is None 
> ... 
> >>> a = A()
> >>> a == None
> True
> >>> a is None
> False
> 
> 

or slightly less PITAish:

class EqualThing(object):
def __eq__(self, other):
return True

Could be a useful sentinel value in some cases.


> 
> 
> > I wonder, do newbies actually get the impression from
> somewhere that "is"
> > is a synonym for "=="?
> >
> 
> 
> Yes.  Such questions pop up regularly, and are usually dealt
> with quickly.
> 
> >
> >
> >
> >> My own
> >> testing indicates that the former beats the latter by about
> 30% on
> >> average.  Not a log for a single instruction but it can add
> up in large
> >> projects.
> >>
> >
> > If you have a "large" project where the time taken to do
> comparisons to
> > None is a significant portion of the total time, I'd be very
> surprised.
> >
> > var is None is a micro-optimization, but that's not why we
> do it. We do
> > it because usually the correct test is whether var *is* None
> and not
> > merely equal to None. Any random object might happen to
> equal None
> > (admittedly most objects don't), but only None is None.
> >
> >
> You don't have that quite right.  The only way something can
> *equal*
> None is if it *is* None.
> None is not a value an object can have, but rather it is a
> (singleton)
> object that can be referenced.  Setting something *equal* to
> None is
> accomplished by making it refer to the single None object, at
> which
> point it *is* None.
> 
> Gary Herron
> 
> >
> >
> 
> --
> 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: Process crash with no reason

2009-01-27 Thread Philip Semanchuk


On Jan 27, 2009, at 7:00 AM, gil.shi...@gmail.com wrote:


On Jan 26, 8:40 pm, Philip Semanchuk  wrote:

On Jan 26, 2009, at 1:13 PM, gil.shi...@gmail.com wrote:


Hi All,



I'm running a program that is acting as a nice interface to sybase'
replication server. The program is using the cherrypy web service  
for
the GUI. The process is crashing every few days with no reason. In  
the
log I can see INFO and DEBUG (No ERROR) log lines and I do not get  
any

TraceBack python's message. This program is running on solaris 9
machine.
Where can I see or what can I do in order to find out what causes  
the

process to crash?
I have tried simulating a "traceBack" message and I could see this
traceback message in one of the log files I'm using. When the  
process

crashes without my help, I don't have a clue.
Let me know if you need any other info


Although Python isn't immune to fatal errors like you describe, I'd
immediately suspect a 3rd-party module instead, esp. one written in C
or C++. Are you using anything like that?


No I do not.


But you're using CherryPy, aren't you? And as Tim Golden pointed out,  
you're probably using another 3rd party lib to talk to Sybase. ISTR  
that CherryPy is written in pure Python but if you have a database  
adapter lib it probably isn't.




Is there a way to monitor who had "killed" my process?


That's more of a Solaris question than a Python one, and I don't know  
much about Solaris. Is there a system log where Solaris records when &  
why it has killed errant processes?





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


How many followers of comp.lang.python

2009-01-27 Thread rantingrick
I curious of how many are "really" out there. I have been watching the
list for some time but basically see the same 10 or so people
answering questions.

Reply to this message so we can see how many exists here

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


Re: How many followers of comp.lang.python

2009-01-27 Thread Mike Driscoll
On Jan 27, 9:07 am, rantingrick  wrote:
> I curious of how many are "really" out there. I have been watching the
> list for some time but basically see the same 10 or so people
> answering questions.
>
> Reply to this message so we can see how many exists here
>
> Thanks

I'm not sure how you arrived at that low number. If you go to the main
page on the Google Groups version, you'll count at least 20 on page
1:

http://groups.google.com/group/comp.lang.python/topics

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


Re: How many followers of comp.lang.python

2009-01-27 Thread rantingrick

I also looked at Guido's profile and he has not posted a message here
since 2000. WOW! I know he way ahead of "us" here but why has he not
drooped in for a chat with the python community? Matz(the creator of
Ruby), is a regular at comp.lang.ruby.

This makes me wonder if Guido thinks comp.lang.python is a dead Parrot
(but there could be other reasons?)
--
http://mail.python.org/mailman/listinfo/python-list


creating a pattern using a previous match and a count of the number of '('s in it

2009-01-27 Thread me

I'm new to regexs and trying to get a list of all my C++ methods with balanced 
parenthesis as follows.


#find all c++ method prototypes with a '::' in the middle 
#upto and including the 1st closing parenthesis
pattern_upto_1st_closed_parenth  = re.compile('\w+::\w+\([^)]*\)') 
match_upto_1st_closed_parenth= 
re.findall(pattern_upto_1st_closed_parenth,txt)
num_of_protos = len(match_upto_1st_closed_parenth)

for i in range (0,num_of_protos-1):  
   num_of_open_parenths = match_upto_1st_closed_parenth[i].count('(')
   
   #expand the pattern to get all of the prototype 
   #ie upto the last closed parenthesis
   #saying something like
   pattern = re.compile(\
'match_upto_1st_closed_parenth[i]+\ 
(([^)]*\)){num_of_open_parenths-1}'\
   )
   #
   #HELP!! I'm not sure how to incorporate:
   #1 'match_upto_1st_closed_parenth[i]' into the above extended pattern???
   #2 the count 'num_of_open_parenths' instead of a literal ???
   #




#===
#if I could do it this sort of this would appear to offer the neatest solution
pattern_upto_last_balanced_parenthesis  = re.compile('

(\w+::\w+\([^)]*\))\

([^)]*\)){\1.count('(')-1}  
')  

#===

Should I be using regexs to do this?

I've only put \ line extensions to separate the pattern components to assist 
readability

Thx


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


Re: Process crash with no reason

2009-01-27 Thread gil . shinar
On Jan 27, 2:10 pm, Tim Golden  wrote:
> gil.shi...@gmail.com wrote:
> > On Jan 26, 8:40 pm, Philip Semanchuk  wrote:
> >> On Jan 26, 2009, at 1:13 PM, gil.shi...@gmail.com wrote:
>
> >>> Hi All,
> >>> I'm running a program that is acting as a nice interface to sybase'
> >>> replication server. The program is using the cherrypy web service for
> >>> the GUI. The process is crashing every few days with no reason. In the
> >>> log I can see INFO and DEBUG (No ERROR) log lines and I do not get any
> >>> TraceBack python's message. This program is running on solaris 9
> >>> machine.
> >>> Where can I see or what can I do in order to find out what causes the
> >>> process to crash?
> >>> I have tried simulating a "traceBack" message and I could see this
> >>> traceback message in one of the log files I'm using. When the process
> >>> crashes without my help, I don't have a clue.
> >>> Let me know if you need any other info
> >> Although Python isn't immune to fatal errors like you describe, I'd  
> >> immediately suspect a 3rd-party module instead, esp. one written in C  
> >> or C++. Are you using anything like that?
>
> > No I do not.
>
> Then how are you interacting with Sybase?
>
> TJG

I'm using python's functions to run sybase sql commands.

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


Re: Why GIL? (was Re: what's the point of rpython?)

2009-01-27 Thread Bryan Olson

Paul Rubin wrote:

Bryan Olson  writes:

An object's __dict__ slot is *not* mutable; thus we could gain some
efficiency by protecting the object and its dict with the same lock. I
do not see a major win in Mr. Banks' point that we do not need to lock
the object, just its dict.


If the dict contents don't change often, maybe we could use an
STM-like approach to eliminate locks when reading.  That would of
course require rework to just about every C function that accesses
Python objects.


I'm a fan of lock-free data structure and software transactional memory, 
but I'm also a realist. Heck, I'm one of this group's outspoken 
advocates of threaded architectures. Theoretical breakthroughs will 
happen, but in real world of today, threads are great but GIL-less 
Python is a loser.


Wherever Python is going, let's recognize that a scripting language that 
rocks is better than any other kind of language that sucks.



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


Re: Process crash with no reason

2009-01-27 Thread gil . shinar
On Jan 27, 5:00 pm, Philip Semanchuk  wrote:
> On Jan 27, 2009, at 7:00 AM, gil.shi...@gmail.com wrote:
>
>
>
> > On Jan 26, 8:40 pm, Philip Semanchuk  wrote:
> >> On Jan 26, 2009, at 1:13 PM, gil.shi...@gmail.com wrote:
>
> >>> Hi All,
>
> >>> I'm running a program that is acting as a nice interface to sybase'
> >>> replication server. The program is using the cherrypy web service  
> >>> for
> >>> the GUI. The process is crashing every few days with no reason. In  
> >>> the
> >>> log I can see INFO and DEBUG (No ERROR) log lines and I do not get  
> >>> any
> >>> TraceBack python's message. This program is running on solaris 9
> >>> machine.
> >>> Where can I see or what can I do in order to find out what causes  
> >>> the
> >>> process to crash?
> >>> I have tried simulating a "traceBack" message and I could see this
> >>> traceback message in one of the log files I'm using. When the  
> >>> process
> >>> crashes without my help, I don't have a clue.
> >>> Let me know if you need any other info
>
> >> Although Python isn't immune to fatal errors like you describe, I'd
> >> immediately suspect a 3rd-party module instead, esp. one written in C
> >> or C++. Are you using anything like that?
>
> > No I do not.
>
> But you're using CherryPy, aren't you? And as Tim Golden pointed out,  
> you're probably using another 3rd party lib to talk to Sybase. ISTR  
> that CherryPy is written in pure Python but if you have a database  
> adapter lib it probably isn't.
>
> > Is there a way to monitor who had "killed" my process?
>
> That's more of a Solaris question than a Python one, and I don't know  
> much about Solaris. Is there a system log where Solaris records when &  
> why it has killed errant processes?

Yes I am using CherryPy. One of the developers I'm working with thinks
it is a cherrypy issue. Our python process has nothing to do if
cherrypy is stuck or down. But still, it is strange that there are no
leftovers from the crashed process.
Solaris has system logs that has nothing in them about this process.

Any other suggestion will be great.

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


Re: How many followers of comp.lang.python

2009-01-27 Thread rantingrick
Seems like the only thing people are interested in is bickering and
name calling. I noticed the post "Does Python really follow..." has
over 400 post mainly from the same 10 people. Maybe this is why Guido
no longer wishes to be a part of this group. Where is the sense of
community here?

Anybody care to correct me, because i would love to be wrong about
this, but i fear i am 100% correct.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How many followers of comp.lang.python

2009-01-27 Thread Mike Driscoll
On Jan 27, 9:17 am, rantingrick  wrote:
> I also looked at Guido's profile and he has not posted a message here
> since 2000. WOW! I know he way ahead of "us" here but why has he not
> drooped in for a chat with the python community? Matz(the creator of
> Ruby), is a regular at comp.lang.ruby.
>
> This makes me wonder if Guido thinks comp.lang.python is a dead Parrot
> (but there could be other reasons?)

I've seen him on the distutils list, but I think he generally keeps to
the dev lists mostly. This list is for general users (i.e. mostly
newbs). We do get some good discussions going on more esoteric
subjects like memoization, but for the most part, it's posts like how
do I do x if y is z, what's the best Python IDE, which is the best
Python GUI toolkit, I hate the GIL, what's a web framework, etc.

I think Guido has better things to do...and his employer probably
doesn't want him spending all day answering stuff like that.

Mike

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


Re: How many followers of comp.lang.python

2009-01-27 Thread Benjamin Kaplan
On Tue, Jan 27, 2009 at 10:42 AM, rantingrick  wrote:

> Seems like the only thing people are interested in is bickering and
> name calling. I noticed the post "Does Python really follow..." has
> over 400 post mainly from the same 10 people. Maybe this is why Guido
> no longer wishes to be a part of this group. Where is the sense of
> community here?
>

> Anybody care to correct me, because i would love to be wrong about
> this, but i fear i am 100% correct.


there is a sense of community here. It just doesn't extend to everyone
joining in the flame war. That particular thread  moved from talking about
difficult to read python code to a not very friendly debate about whether
Python needs to have enforced data hiding to be a good language. After the
first couple hundred posts and when the name calling started, I, for one,
started ignoring those posts.

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


Re: socket.unbind or socket.unlisten? - socket.error: (48, 'Address already in use')

2009-01-27 Thread Hendrik van Rooyen
"Jean-Paul Calderone"  wrote:

8<--

> ...  Setting the
> SO_REUSEADDR flag on POSIX fixes this problem (don't set it on Windows,
> though).

Why not?  I have been merrily setting it, and I have not noticed anything weird.
(yet)

- Hendrik


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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-27 Thread Hendrik van Rooyen
"Luis Zarrabeitia"  wrote:
8<
>Hehe. At the beginning of this thread, I also thought that Russ P. and Paul 
>Robin were the same person. I have serious problems with names.

*nods in agreement, because the man's surname is Rubin, not Robin*  

:-)

- Hendrik

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


Re: creating a pattern using a previous match and a count of the number of '('s in it

2009-01-27 Thread MRAB

me wrote:


I'm new to regexs and trying to get a list of all my C++ methods with balanced 
parenthesis as follows.



#find all c++ method prototypes with a '::' in the middle 
#upto and including the 1st closing parenthesis
pattern_upto_1st_closed_parenth  = re.compile('\w+::\w+\([^)]*\)') 
match_upto_1st_closed_parenth= 
re.findall(pattern_upto_1st_closed_parenth,txt)

num_of_protos = len(match_upto_1st_closed_parenth)

for i in range (0,num_of_protos-1):  

This should actually be range(0, num_of_protos).


   num_of_open_parenths = match_upto_1st_closed_parenth[i].count('(')
   
   #expand the pattern to get all of the prototype 
   #ie upto the last closed parenthesis

   #saying something like
   pattern = re.compile(\
'match_upto_1st_closed_parenth[i]+\ 
(([^)]*\)){num_of_open_parenths-1}'\

   )
   #
   #HELP!! I'm not sure how to incorporate:
   #1 'match_upto_1st_closed_parenth[i]' into the above extended pattern???
   #2 the count 'num_of_open_parenths' instead of a literal ???
   #




#===
#if I could do it this sort of this would appear to offer the neatest solution
pattern_upto_last_balanced_parenthesis  = re.compile('

(\w+::\w+\([^)]*\))\

([^)]*\)){\1.count('(')-1}  
')  

#===

Should I be using regexs to do this?

I've only put \ line extensions to separate the pattern components to assist 
readability


Thx



Not necessarily the best way, but:

methods = []
# The pattern for the start of the method's header.
start_pattern = re.compile(r'\w+::\w+\([^)]*\)')
# Start at the beginning of the text.
pos = 0
while True:
# Search for the start of the next method's header.
start_match = start_pattern.search(txt, pos)
if not start_match:
break
# Search for the end of the method's header.
end_pattern = re.compile(r'(?:[^)]*\)){%d}' % 
start_match.group().count('('))

end_match = end_pattern.search(txt, pos)
methods.append(txt[start_match.start() : end_match.end()])
# Continue the next search from where we left off.
pos = end_match.end()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Process crash with no reason

2009-01-27 Thread Philip Semanchuk


On Jan 27, 2009, at 10:34 AM, gil.shi...@gmail.com wrote:


On Jan 27, 2:10 pm, Tim Golden  wrote:

gil.shi...@gmail.com wrote:

On Jan 26, 8:40 pm, Philip Semanchuk  wrote:

On Jan 26, 2009, at 1:13 PM, gil.shi...@gmail.com wrote:



Hi All,
I'm running a program that is acting as a nice interface to  
sybase'
replication server. The program is using the cherrypy web  
service for
the GUI. The process is crashing every few days with no reason.  
In the
log I can see INFO and DEBUG (No ERROR) log lines and I do not  
get any

TraceBack python's message. This program is running on solaris 9
machine.
Where can I see or what can I do in order to find out what  
causes the

process to crash?
I have tried simulating a "traceBack" message and I could see this
traceback message in one of the log files I'm using. When the  
process

crashes without my help, I don't have a clue.
Let me know if you need any other info

Although Python isn't immune to fatal errors like you describe, I'd
immediately suspect a 3rd-party module instead, esp. one written  
in C

or C++. Are you using anything like that?



No I do not.


Then how are you interacting with Sybase?


I'm using python's functions to run sybase sql commands.


Can you give a short code sample? I'm unaware of how one would use the  
standard Python library to talk to Sybase, unless Sybase has a raw  
socket interface or some such.

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


Re: How many followers of comp.lang.python

2009-01-27 Thread rantingrick
On Jan 27, 9:43 am, Mike Driscoll  wrote:

> I think Guido has better things to do...and his employer probably
> doesn't want him spending all day answering stuff like that.
> Mike

I totally agree, and i would never expect him to field noob questions
but i just thought it odd he has not dropped by in over 9 years. I
have seen his blog but i wonder why he does not blog here. Seems like
the best place in the world to get feedback from Python users is here.
He could start some very interesting subjects.

To at least, this medium is more of a "personal" exchange, than a blog.
--
http://mail.python.org/mailman/listinfo/python-list


Re: USB in python

2009-01-27 Thread Grant Edwards
On 2009-01-27, Lie Ryan  wrote:

> From the little I know on electronics, a simple, single
> transistor would (almost) immediately switch from
> on-to-off-to-on depending on the voltage of the control pin (I
> think it was the middle pin). I was suggesting this 
> simplistic hack because as far as I comprehend the OP's need,
> he only need on-off switch instead of a complex multiple
> output bits.

The audio output jack outputs AC (alternating current).  If you
put AC into a transistor, you get AC out.  Hence the need for a
rectifier/detector to convert the AC signal into a DC level. To
reliably get an on-off state from an analog DC level, you need
something with some hystersis (e.g. a comparitor). Depending on
the requirements it may possible to do impliment a comparitor
with hysteresis using a single transistor.

If you're looking for a digital output signal whose DC level
you can contol, then either the printer port or the serial port
is a better option than using the sound-card's line-out which
is an analog AC output.

>>> I don't know how much power can be pulled from jack out,
>> 
>> Almost none, and what's there is very low voltage.
>
> That's why the power is taken from USB port.
>
>>> but for a home brewn device it is still feasible to draw power
>>> from USB and signal from jack out.
>> 
>> It would probably be easier to buy a USB-parallel port chip.
>> Then he's got power from the USB bus and something like 14
>> parallel I/O pins he can control.  Alternatively A USB-serial
>> chip will provide 2 outputs and 4 inputs.
>
> The idea was made on the basis that a USB microcontroller is
> not used.

I didn't say anything about using a USB microcontroller.  There
are dead-simple and cheap USB-serial and USB-parallel chips
that you can buy that provide the equivalent of a serial port
or parallel printer port via USB.

> Getting power from USB should be much easier than getting data

Using a USB-serial or USB-parallel chip isn't really much
harder than getting power from the USB port, and it's simpler
than building a detector/comparity circuit to connect to the
audio line-out.

> while the jack out can provide simple on-off signal.

With the addition of a rectifier/detector and an appropriate
comparitor circuit, yes.

-- 
Grant Edwards   grante Yow! Civilization is fun!
  at   Anyway, it keeps me busy!!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How many followers of comp.lang.python

2009-01-27 Thread Bruno Desthuilliers

rantingrick a écrit :

On Jan 27, 9:43 am, Mike Driscoll  wrote:


I think Guido has better things to do...and his employer probably
doesn't want him spending all day answering stuff like that.
Mike


I totally agree, and i would never expect him to field noob questions
but i just thought it odd he has not dropped by in over 9 years.


All you can say is that he didn't *post* here (at least under his real 
identity...) for the 9 past years - this doesn't mean he never *reads* 
(and this, you just have no way to know).


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


Re: How many followers of comp.lang.python

2009-01-27 Thread Bruno Desthuilliers

rantingrick a écrit :

Seems like the only thing people are interested in is bickering and
name calling. I noticed the post "Does Python really follow..." has
over 400 post mainly from the same 10 people.


There are occasionally such kind of threads, indeed. And, as Mike 
mentionned, the usual FAQs (some of them twice or more each week, year 
after year). And sometimes more interesting questions - but that does 
not necessarily makes long thread, so they perhaps are too low for your 
radar.



Maybe this is why Guido
no longer wishes to be a part of this group.


I've been lurking here for years (about early 2000 IIRC), and don't 
remember a single post from the BDFL here. But:



Where is the sense of
community here?


If you set the occasional trolls aside, this group is usually 
newbie-friendly and helpful one. You'll find quite a few posts by 
long-time, experienced and talented Python programmers (and core 
developpers).  As far as I'm concerned, I learned (and I'm still 
learning) quite a lot here.


Please visit comp.databases or comp.lang.javascript for really 
unfriendly and unhelpful places where few happens except "bickering and 
name-calling".



Anybody care to correct me, because i would love to be wrong about
this, but i fear i am 100% correct.


Well, why don't you just try and post a couple practical questions here?
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Twisted Design Decision

2009-01-27 Thread koranthala
On Jan 27, 6:57 pm, Jean-Paul Calderone  wrote:
> On Tue, 27 Jan 2009 05:46:25 -0800 (PST), koranthala  
> wrote:
> >Twisted, being twisted in its behavior is causing quite a lot of
> >confusion in design decisions.
>
> I'm not sure I agree with your premise. ;)
>
>
>
> >I will put forward a comparison of reactor and non-reactor patterns.
> >The code is not exact - whatever is shown is the gist of it.
>
> >For example, a message handler - in a usual scenario:
> >class messageHandler:
> >   def run():
> >         msg = self.get_next_msg()
> >         if not msg.send():
> >             self.handle_failure()
>
> >To handle parallel execution, we will have to use threads, but the
> >code flow is similar.
>
> >How do we do the same in a reactor pattern (Twisted)?
> >msg.send will cause a deferred to be raised - the failure, if it
> >happens will happen much later.
> >i.e. other than sending messageHandler object in msg.send(), I cannot
> >see any mechanism of running handle_failure.
>
> >In Twisted:
> >class messageHandler:
> >   def run():
> >         msg = self.get_next_msg()
> >         msg.send(self):
>
> >class msgClass:
> >    def send(o):
> >        d = deferred.addCallBack(success_handler, o).addErrBack
> >(failure_handler, o)
>
> >    def failure_handler(o):
> >        o.handle_failure()
>
> This doesn't look like a correct or faithful translation of the original.
> Here are two possibilities.  First:
>
>     class messageHandler:
>         def run():
>             msg = self.get_next_msg()
>             d = msg.send()
>             def cbSendFailed(result):
>                 if not result:
>                     self.handle_failure()
>             d.addErrback(cbSendFailed)
>             return d
>
> Next:
>
>     class messageHandler:
>         @inlineCallbacks
>         def run():
>             msg = self.get_next_msg()
>             if not (yield msg.send()):
>                 self.handle_failure()
>
> These are both just straight translations from your version so as to
> be able to handle a Deferred from `msg.send´.
>
> >Basically, what I find is that a lot of functional encapsulation is
> >now lost by following reactor pattern. handle_failure is
> >messageHandlers code and makes for pretty viewing if called from
> >inside messageHandler itself. But, due to the twisted nature of
> >reactor pattern, the msg Class - who is functionally a lower class to
> >messageHandler invoking messageHandler's code.
>
> You don't need to lose anything.  I don't know what your motivation was
> for re-arranging the code when you wrote the Twisted version, but it doesn't
> appear to have been necessary.
>
> >Is there a way to solve this in a more beautiful way? Am I missing
> >something here?
>
> Hope this helps,
>
> Jean-Paul

Thank you Jean-Paul.
My code is more complex than what I have mentioned. When I mentioned
msg.send, the msg object actually gets the data from DB etc to send.
And there are many other items being done.
I will try to see whether I can change the code to incorporate what
you mentioned.

I rewrote most of my code after learning just raw deferreds - I had
planned to study inlineCallbacks - but then it slipped my mind  - now
it has come to bit me. :-(
--
http://mail.python.org/mailman/listinfo/python-list


Pexpect and telnet not communicating properly

2009-01-27 Thread David Anderson
I am trying to automate the following session - to talk to my router:

===
telnet speedtouch
Trying 192.168.1.254...
Connected to speedtouch.
Escape character is '^]'.
Username : Administrator
Password :


 __  SpeedTouch 780
 ___/_/\
/ /\  6.1.7.2
  _/__   /  \
_/   /\_/___ \  Copyright (c) 1999-2006, THOMSON
   //   /  \   /\ \
   ___//___/\ / _\/__
  /  / \   \// //\
   __/  /   \   \  // // _\__
  / /  / \___\// // /   /\
 /_/__/___/ // /___/  \
 \ \  \___\ \\ \   \  /
  \_\  \  /  /\\ \\ \___\/
 \  \/  /  \\ \\  /
  \_/  /\\ \\/
   /__/  \\  /
   \   _  \  /_\/
\ //\  \/___\/
 //  \  \  /
 \\  /___\/
  \\/


_{Administrator}=>?
Following commands are available :

help : Displays this help information
menu : Displays menu
?: Displays this help information
exit : Exits this shell.
..   : Exits group selection.
saveall  : Saves current configuration.
ping : Send ICMP ECHO_REQUEST packets.
traceroute   : Send ICMP/UDP packets to trace the ip path.

Following command groups are available :

firewallservice autopvc connection  cwmp
dhcpdns dsd dyndns  eth
adslatm config  debug   env
exprgrp hostmgr ids igmp
interface   ip  ipqos   label   language
mbusmemmmlp nat ppp
pptpscript  snmpsntpsoftware
system  systemlog   upgrade upnpuser
voice   wireless

{Administrator}=>exit



I am using the following code:

#!/usr/bin/env python

import pexpect
import sys

child = pexpect.spawn('telnet 192.168.1.254')
fout = file('mylog.txt','w')
child.logfile = fout

child.expect('sername : ')
child.sendline('Administrator')
child.expect('assword : ')
child.sendline('')


child.expect('_{Administrator}=>')
child.sendline('?')
child.expect('_{Administrator}=>')
child.expect('exit')



This times out after child.sendline('Administrator')

mylog.txt contains:
Trying 192.168.1.254...

Connected to 192.168.1.254.

Escape character is '^]'.

Username : Administrator
Administrator


Can anyone help me in finding out what I am doing wrong?

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


Re: v = json.loads("{'test':'test'}")

2009-01-27 Thread J. Cliff Dyer

On Sun, 2009-01-25 at 14:28 -0800, gert wrote:
> On Jan 25, 11:16 pm, Дамјан Георгиевски  wrote:
> > > raise ValueError(errmsg("Expecting property name", s, end))
> > >http://docs.python.org/library/json.html
> > > What am I doing wrong ?
> >
> > try this
> > v = json.loads('{"test":"test"}')
> >
> > JSON doesn't support single quotes, only double quotes.
> 
> the funny part is when you print(v) you get
> {'test': 'test'}
> 
> Single quotes works in every browser that support json so i
> recommended python should support it too, besides it looks much
> cleaner
> {'test': 'test'}
> {"test": "test"}
> 
> It can not be that hard to support both notation can it ?

It's not that hard, but it does add a noticeable level of complexity to
the process.  In JSON, you simply tell the parser, "if you see a
double-quote character, we're now parsing a string.  When you see
another (unescaped) double-quote character, the string is done.

The equivalent version for your extended JSON would say, "if you see a
quote character of either kind, we're parsing a string.  When you see
another (unescaped) quote character of either kind, the string is done."
But that doesn't work, because it would allow {'test": "test'}.  So the
parser has to remember which quote character is being used, and require
those characters to be escaped, and not the other (but then does "te
\'st" render as r"te'st" or r"te\'st"?) and only close the string when
the appropriate quote is found.  

Not an impossible task, but certainly more complex than the current
parsing requirements for JSON.

Cheers,
Cliff


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


Re: Counting number of objects

2009-01-27 Thread Scott David Daniels

Kottiyath wrote:

So, in a higher level class, have a weakref list which contains a
reference to each person. Total count will be len(list) at any time.

Now, I couldnt find a weakref list - so I am using WeakKeyDictionary
with the value as None - since len(dict) also should give me the data

I typically use a WeakValueDictionary, with the key id(obj).
...

Now, the only two operations that I am doing are ->
__init__:
  d = weakref.WeakKeyDictionary()

method y:
  x = aa()
  d[x] = None

method z:
  total = len(d)


At least at one point, the WeakValueDictionary was more stable.  I don't
remember the details, but I remember my work-around.  If you do have
troubles, try using almost the same code you now use, but substitute for
the obvious lines above:
d = weakref.WeakValueDictionary()
and
d[id(x)] = x


--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


[xlrd] sanitize the output and store in a 2d arrays

2009-01-27 Thread Jay Jesus Amorin
Hi gurus,

Script:

#!/usr/bin/python

import xlrd, sys

def main(toParse):

workBook = xlrd.open_workbook(toParse)
mySheet = workBook.sheet_by_index(0)

for rownum in range(mySheet.nrows):
print mySheet.row_values(rownum)

if __name__ == '__main__':
if len(sys.argv) < 2:
sys.stderr.write("Usage: %s EXCEL.XLS\n" % (sys.argv[0]))
else:
main(sys.argv[1])

Output:

myu...@testsvr:~> ./parse.py test.xls
*[u'*thisislineone*'*, 343*.0]*
*[u'*thisislinetwo*'*, 344*.0]*
*[u'*thisislinethree*'*, 345*.0]*


This is the content of my test.xls:

thisislineone   343
thisislinetwo   344
thisislinethree 345


How do i remove the bold part of the output (*[u'*. *'* and *.0]* and store
the output in a 2 dimensional array?

Many thanks.


PythonNewbie,


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


Re: Doc for extended call syntax; was: Re: unzip array of arrays?

2009-01-27 Thread Mark Wooding
Bryan Olson  writes:

> Mark Wooding wrote:
>> There's a full description of it in 5.4.3 in the Language Reference, but
>> apparently not indexed.
>
> So I guess this means I can duck out of writing up a lecture on my own
> understanding of Python's extended call syntax. Great.
>
> I think I grock the extended call syntax, and when the question came
> up I was surprised not to be able to find where I learned it. Mark,
> where exactly does one look to see this "full description"?

I typoed, sorry!  I should have written 5.3.4:

http://www.python.org/doc/2.5/ref/calls.html

The description of the fancy * and ** syntax starts with `If the syntax
``*expression'' appears in the function call...'.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


significant release for SIMPL project's Python extension

2009-01-27 Thread bobicanprogram
The SIMPL project (http://www.icanprogram.com/simpl) aims to bring the
simplicity and power of the Send/Receive/Reply messaging (first
pioneered by QNX) to the Linux world.

SIMPL modules are themselves Linux executables and can be written in
any number of languages now (C,  C++,  Tcl/Tk and Python).   A SIMPL
application consists of one or more of these modules interacting in a
single SIMPL sandbox.A SIMPL application can consist of SIMPL
modules written in a mixture of supported languages.

In addtion SIMPL applications can be spread across a network
seamlessly through the use of TCP/IP or RS232 surrogates.In most
cases this redeployment can occur without an code change or
recompilation.

Python is one of the newer languages to be added to the SIMPL family,
but it is already attracting significant attention.An online
course on SIMPL-Python offered for no fees by iCanProgram (http://
www.icanprogram.com/06py/main.html) consistently gets the highest
number of web hits in any given month.

Up until now SIMPL-Python modules could already be built for
deployment on a Linux OS.

Now SIMPL-Python modules can be written for a non Linux OS and
interact with a SIMPL application using the tclSurrogate (TCP/IP)
protocol which SIMPL supports.This means that a Python script
running under Windows can now participate seamlessly in a SIMPL
application running on a Linux network.

In addition SIMPL-Python web scripts can also now participate
seamlessly in a SIMPL application.This feature greatly extends the
reach of SIMPL-Python into the realm of web interfaces and web
applications.

The easiest way to get aquainted with the SIMPL-Python toolset is to
download one of its self installing archives for Linux.These are
safely deployed in /tmp to allow full exploration with an option to
permanently install the release in a directory of your choosing.

SIMPL-Python self installing archive -  
http://www.icanprogram.com/simpl/python.self.html
SIMPL-Python course self installing archive - 
http://www.icanprogram.com/pythoncourse.self.html

the SIMPL project team
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pexpect and telnet not communicating properly

2009-01-27 Thread George Trojan

David Anderson wrote:

I am trying to automate the following session - to talk to my router:

===
telnet speedtouch
Trying 192.168.1.254...
Connected to speedtouch.
Escape character is '^]'.
Username : Administrator
Password :


 __  SpeedTouch 780
 ___/_/\
/ /\  6.1.7.2
  _/__   /  \
_/   /\_/___ \  Copyright (c) 1999-2006, THOMSON
   //   /  \   /\ \
   ___//___/\ / _\/__
  /  / \   \// //\
   __/  /   \   \  // // _\__
  / /  / \___\// // /   /\
 /_/__/___/ // /___/  \
 \ \  \___\ \\ \   \  /
  \_\  \  /  /\\ \\ \___\/
 \  \/  /  \\ \\  /
  \_/  /\\ \\/
   /__/  \\  /
   \   _  \  /_\/
\ //\  \/___\/
 //  \  \  /
 \\  /___\/
  \\/


_{Administrator}=>?
Following commands are available :

help : Displays this help information
menu : Displays menu
?: Displays this help information
exit : Exits this shell.
..   : Exits group selection.
saveall  : Saves current configuration.
ping : Send ICMP ECHO_REQUEST packets.
traceroute   : Send ICMP/UDP packets to trace the ip path.

Following command groups are available :

firewallservice autopvc connection  cwmp
dhcpdns dsd dyndns  eth
adslatm config  debug   env
exprgrp hostmgr ids igmp
interface   ip  ipqos   label   language
mbusmemmmlp nat ppp
pptpscript  snmpsntpsoftware
system  systemlog   upgrade upnpuser
voice   wireless

{Administrator}=>exit



I am using the following code:

#!/usr/bin/env python

import pexpect
import sys

child = pexpect.spawn('telnet 192.168.1.254')
fout = file('mylog.txt','w')
child.logfile = fout

child.expect('sername : ')
child.sendline('Administrator')
child.expect('assword : ')
child.sendline('')


child.expect('_{Administrator}=>')
child.sendline('?')
child.expect('_{Administrator}=>')
child.expect('exit')



This times out after child.sendline('Administrator')

mylog.txt contains:
Trying 192.168.1.254...

Connected to 192.168.1.254.

Escape character is '^]'.

Username : Administrator
Administrator


Can anyone help me in finding out what I am doing wrong?

Regards
David


To debug, add lines

print self.before
print self.after

after each child.expect(). Also, add timeout=2 to the argument list of 
child.expect().


I wrote a thin wrapper that serves me well, at least till now.


class Connection(object):
'''Establishes connection to Cisco modem server.
A wrapper around fdexpect spawn.
'''
def __init__(self, host, port, user, passwd, **kwds):
self.pipe = None
self.socket = None
self.host = host
self.port = port
self.user = user
self.passwd = passwd
self.logger = kwds.get('logger')
self._last = ''

def __getattr__(self, name):
if name not in ['open', 'close', 'send', 'sendline', 'expect']:
return getattr(self.pipe, name)

def open(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.host, self.port))
self.pipe = pexpect.fdspawn(self.socket)
self.expect('Username:', timeout=2)
self.sendline(self.user)
self.expect('Password:', timeout=1)
self.sendline(self.passwd)
self.send('ATZ\r')
self.expect('OK', timeout=1)

def send(self, s):
self._last = s
return self.pipe.send(s)

def sendcr(self, s):
self._last = s
return self.pipe.send(s+'\r')

def sendline(self, s):
self._last = s
return self.pipe.sendline(s)

def expect(self, pattern, **kwds):
rc = self.pipe.expect(pattern, **kwds)
if self.logger:
self.logger.debug('sent "%s", received\n\t1. before "%s"\n\t' \
'2. match "%s"\n\t3. after "%s"\n', self._last,
self.before, self.match.group(0), self.after)
return rc

def close(self):
self.pipe.close()
self.pipe = None
self.socket.close()
 

Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-27 Thread Michele Simionato
On Jan 21, 2:11 am, Mark Wooding  wrote:

> CLOS is much more complex and dynamic than Python's object system; > but it 
> can be compiled very aggressively.

I agree that CLOS is complex and that it can be compiled very
aggressively, but I do not think that it is more dynamic than Python.
What feature are you alluding to? Multimethods? There are many Python
implementations of them, they are just not in the standard library.
Or are you referring to interactive facilities, such as the one
discussed in this recipe http://code.activestate.com/recipes/160164 ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How many followers of comp.lang.python

2009-01-27 Thread Cameron Laird
In article <8692c77c-0498-4c68-940f-e4d4427f3...@x37g2000yqj.googlegroups.com>,
rantingrick   wrote:
>Seems like the only thing people are interested in is bickering and
>name calling. I noticed the post "Does Python really follow..." has
>over 400 post mainly from the same 10 people. Maybe this is why Guido
>no longer wishes to be a part of this group. Where is the sense of
>community here?
>
>Anybody care to correct me, because i would love to be wrong about
>this, but i fear i am 100% correct.

Which "this"?  Are you asking for evidence that more
than ten people regularly read comp.lang.python, OR
that there is traffic in comp.lang.python other than
bickering and name-calling?

My own rough estimate of readership is at least 4,000.
If motivated, one could refine the figure, I'm
confident).
--
http://mail.python.org/mailman/listinfo/python-list


Re: v = json.loads("{'test':'test'}")

2009-01-27 Thread Richard Brodie

"Steven D'Aprano"  wrote in message 
news:018d0300$0$20629$c3e8...@news.astraweb.com...

> Supposedly "every browser" (what, all of them?) already support a de
> facto extension to the JSON standard, allowing more flexible quoting.

That's a consequence of JSON being a subset of Javascript syntax,
so you can just call eval() on it, if you're willing. When you use a
library, it's pot luck whether it accepts JSON-soup or not. 


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


Re: How many followers of comp.lang.python

2009-01-27 Thread Grant Edwards
On 2009-01-27, Bruno Desthuilliers  
wrote:

> Please visit comp.databases or comp.lang.javascript for really
> unfriendly and unhelpful places where few happens except
> "bickering and name-calling".

I've always found comp.lang.c to be a rather dangerous place as
well.

Of the newsgroups I read, c.l.python is probably the most
friendly and has one of the highest S/N ratios.  People who
would have been roasted alive in other newsgroups for their
laziness or presumptuousness get surprisingly gentle treatment
in c.l.python.  I do know of a few low-volume mailing lists
that are probably as good, but for a Usenet news group with any
volume at all, c.l.pythong is exceptionally good.

-- 
Grant Edwards   grante Yow! I wonder if I should
  at   put myself in ESCROW!!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Exec woes

2009-01-27 Thread Hendrik van Rooyen

It starts with the conspiracy of silence at the interactive prompt:

Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

IDLE 1.1.3   No Subprocess 
>>> help(exec)
SyntaxError: invalid syntax
>>>
Its the same under Linux SuSe, Python 2.5.1.

I think this is a BUG.

Anyway, my real problem looks like this:

>>> def Somefunc():
def excrescence():
 exec('BUILD = "someString"')
 return BUILD
 
SyntaxError: unqualified exec is not allowed in function 'excrescence 
it is a nested function (, line 3)
>>>

Now this works if it is not nested, and it works if it is a method in a class.
Why the complaint about the nestedness?

I would appreciate it if someone would explain, as the library reference
simply says that it would default to globals() and locals(), which also does
not seem to happen - also true for a "nested" eval after a compile - you have
to specify the globals() or you get a NameError - global BUILD is not defined.

So there is some namespace thing happening that is too subtle for me, and I
would like to know what "unqualified" means in the above message, and
what one must do to "qualify" the statement, if that is what is needed.

The original thing came up because I really need relative imports - I have
some version.py files in various directories that have a single line in them
that looks like the string I am feeding the exec.

By the way, execfile works in this situation, but also only if you specify
globals() explicitly.  I would really like to understand what is going on.

- Hendrik


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


Re: socket.unbind or socket.unlisten? - socket.error: (48, 'Address already in use')

2009-01-27 Thread Mark Wooding
Laszlo Nagy  writes:

> I have a program that uses socket.bind() and socket.listen()
> frequently. After that program stops, it is not able to bind() again for a
> while:

This is the usual TIME-WAIT problem.  The TCP protocol requires one end
of the connection (whichever actually started the close) to keep a
record of it for a while after it closes, in order to avoid confusion
caused by old packets.

> The problem with this, is that this server program SOMETIMES need to be
> restarted very quickly.

The usual solution is to set the SO_REUSEADDR socket option before
binding.  This is safe for listening sockets.

Here's an interactive session.

In [1]: import socket as S

In [2]: def make_server_socket():
   ...:   sk = S.socket(S.AF_INET, S.SOCK_STREAM)
   ...:   sk.bind(('', 12345))
   ...:   sk.listen(5)
   ...:   return sk
   ...:

In [3]: def serve_client(sk):
   ...:   (nsk, addr) = sk.accept()
   ...:   nsk.send('Hello.\n')
   ...:   nsk.close()
   ...:

In [4]: sk = make_server_socket()

In [5]: serve_client(sk)

(At this point, I connect to the server in another terminal.)

In [6]: sk.close()

In [7]: sk = make_server_socket()
[...]
error: (98, 'Address already in use')

And to confirm that it's TIME-WAIT that's stopping us:

[ponder ~]netstat -n | grep 12345
tcp0  0 127.0.0.1:12345 127.0.0.1:49988 TIME_WAIT

If I change make_server_socket, then everything works fine.

In [8]: def make_server_socket():
   ...:   sk = S.socket(S.AF_INET, S.SOCK_STREAM)
   ...:   sk.setsockopt(S.SOL_SOCKET, S.SO_REUSEADDR, 1)
   ...:   sk.bind(('', 12345))
   ...:   sk.listen(5)
   ...:   return sk
   ...:

In [10]: sk = make_server_socket()

In [11]: serve_client(sk)

In [13]: sk.close()

In [14]: sk = make_server_socket()

Done.

If you try this, note that both the old, closed socket /and/ the new one
must have SO_REUSEADDR set on them.  If you try this interactively,
you'll have to wait for the non-SO_REUSEADDR socket to leave TIME-WAIT
before you can bind.  But once you've done that, it'll work fine from
then on.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


IDLE 3000 (suggested improvements)

2009-01-27 Thread r
Proposal:
OK, so the python language has officially moved into the next level. I
look at IDLE and think, hmm great IDE but it could really use a spit
shining. So here is a very simple script showing my ideas to improve
IDLE.

Reason for change:
The text widget and the prompt(>>>) should be separated. Trying to
write a conditional in the interactive IDLE is a real pain. Not to
mention that when you copy code from Interactive  IDLE to the IDLE
editor window the indention is eight spaces instead four and you've
got that prompt(>>>) stuck in there. I have a solution for the problem
though.

I hope you are using fixed-width font

Lst|<- Text Widget >|
   ||
>>>|if this:|
...|if that:|
...|... |
...|elif that:  |
...|... |
...|else:   |
...|... |
>>>||
>>>|x = 10  |
>>>||


Basically you have a Listbox on the left for the prompt and a Text on
the right. Disable the Listbox highlight and key press events and now
we have a very friendly interactive IDLE! No more prompt hijacking
your snippets, and no more eigtht space indention! Hip-Hip-Hooray!


#-- Start Script --#

from Tkinter import *
import tkMessageBox as MB

class CMD(Toplevel):
def __init__(self, master):
Toplevel.__init__(self, master)
self.master = master
self.startidx = '1.0'
self.backidx = '1.0'
self.title('IDLE 3000')

self.listbox = Listbox(self, width=3, relief=FLAT, font=
('Courier New',12), takefocus=0)
self.listbox.pack(fill=Y, side=LEFT)
self.listbox.insert(0, '>>>')

self.text = Text(self, relief=FLAT, spacing3=1, wrap=NONE,
font=('Courier New',12))
self.text.pack(fill=BOTH, side=LEFT, expand=1)
self.text.config(width=50, height=20)
self.text.focus_set()

self.listbox.bind(""  , lambda e: "break")
self.listbox.bind(""  , lambda e: "break")
self.listbox.bind("" , lambda e: "break")
self.listbox.bind(""   , lambda e: "break")
self.listbox.bind("" , lambda e: "break")
self.listbox.bind("", lambda e: "break")

self.text.bind('' , lambda e: "break")#pageup
self.text.bind('', lambda e: "break")#pagedown
self.text.bind(''   , lambda e: "break")
self.text.bind('' , lambda e: "break")
self.text.bind(''  , lambda e: "break")
self.text.bind("", lambda e: "break")
self.text.bind('' , lambda e: "break")
self.text.bind(""   , lambda e: "break")

self.text.bind(""   , self.onUp)
self.text.bind("" , self.onDown)
self.text.bind(""  , self.onTab)
self.text.bind(""   , self.onReturn)
self.text.bind("", self.onBackSpace)

self.protocol("WM_DELETE_WINDOW", self.onQuit)
self.lift(master)
self.master.withdraw()

def fix_index(self, chars):
self.backidx = '%d.0' %(int(self.backidx.split('.')[0])+1)
self.text.insert(END, '\n')
self.text.mark_set(INSERT, END)
self.text.see(INSERT)
self.listbox.insert(END, chars)
self.listbox.see(self.listbox.size())

def onQuit(self):
self.grab_release()
self.master.destroy()

def onTab(self, event=None):
curline, cursor = self.text.index(INSERT).split('.')[0]+'.0',
self.text.index(INSERT)
self.text.insert(INSERT, '')
return "break"

def onDown(self, event):
i = self.text.index(INSERT+'+1l') #;print 'New index: ', i
self.text.mark_set(INSERT, i)
self.text.see(i)
self.listbox.see(int(i.split('.')[0])-1)
return "break"

def onUp(self, event=None):
i = self.text.index(INSERT+'-1l') #;print 'New index: ', i
self.text.mark_set(INSERT, i)
self.text.see(i)
self.listbox.see(int(i.split('.')[0])-1)
return "break"

def onBackSpace(self, event=None):
if self.text.compare(self.text.index(INSERT), '!=',
self.backidx):
self.text.delete(self.text.index(INSERT+'-1c'))
return "break"

def onReturn(self, event=None):
curline, cursor = self.text.index(INSERT).split('.')[0]+'.0',
self.text.index(INSERT)
text = self.text.get(self.startidx, END).strip()
if self.text.compare(curline, '<', self.startidx):#'Out Of
Zone'
self.text.mark_set(INSERT, END+'-1c')
self.text.see(INSERT)
self.listbox.see(END)
elif '.0' in cursor: #nothing typed on this line, try to exec
command
cmd = text.rstrip('\n')
try:
exec(cmd)
except:
self.master.bell()
print '%s\n%s\n%s' %(sys.exc_traceback, sys.exc_type,
sys.exc_value)
finally:

regular expression, help

2009-01-27 Thread Vincent Davis
I think there are two parts to this question and I am sure lots I am
missing. I am hoping an example will help meI have a html doc that I am
trying to use regular expressions to get a value out of.
here is an example or the line
Parcel ID: 39-034-15-009 
I want to get the number "39-034-15-009" after "Parcel ID:" The number will
be different each time but always the same format.
I think I can match "Parcel ID:" but not sure how to get the number after.
"Parcel ID:" only occurs once in the document.

is this how i need to start?
pid = re.compile('Parcel ID: ')

Basically I am completely lost and am not finding examples I find helpful.

I am getting the html using myurl=urllib.urlopen().
Can I use RE like this
thenum=pid.match(myurl)


I think the two key things I need to know are
1, how do I get the text after a match?
2, when I use myurl=urllib.urlopen(http://...). can I use the myurl as
the string in a RE, thenum=pid.match(myurl)

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


regular expression, help

2009-01-27 Thread Vincent Davis
I think there are two parts to this question and I am sure lots I am
missing. I am hoping an example will help meI have a html doc that I am
trying to use regular expressions to get a value out of.
here is an example or the line
Parcel ID: 39-034-15-009 
I want to get the number "39-034-15-009" after "Parcel ID:" The number will
be different each time but always the same format.
I think I can match "Parcel ID:" but not sure how to get the number after.
"Parcel ID:" only occurs once in the document.

is this how i need to start?
pid = re.compile('Parcel ID: ')

Basically I am completely lost and am not finding examples I find helpful.

I am getting the html using myurl=urllib.urlopen().
Can I use RE like this
thenum=pid.match(myurl)


I think the two key things I need to know are
1, how do I get the text after a match?
2, when I use myurl=urllib.urlopen(http://...). can I use the myurl as
the string in a RE, thenum=pid.match(myurl)

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


Re: Calling Python-tk code from C/C++

2009-01-27 Thread Gabriel Genellina
En Tue, 27 Jan 2009 07:42:01 -0200, Rajorshi Biswas   
escribió:


Hello all, This is my first post to this mailing list. Our requirement  
is to invoke a Tkinter python panel from a C++ GUI app where both GUI  
windows would run in 2 separate threads. We have written a sample PyQt  
application which calls this Tk panel using something like this:class  
TkPanel(threading.Thread):def run(self): # call showPaneldef  
showPanel():# create window = Tk.Tk() window.mainloop()def start():t =  
TkPanel()t.start()Now we call this from our main python code:def  
startPanel(self): import tkPanel tkPanel.start() # this calls  
tkwindow.mainloop() in a separate thread.This works absolutely fine when  
the invoking app is Python.


From the above description I don't see where PyQt is involved. Do you  
really want to mix Qt and Tk in the same application? I don't think they  
could coexist...

--
Gabriel Genellina

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


Re: Exec woes

2009-01-27 Thread Christian Heimes
Hendrik van Rooyen schrieb:
> It starts with the conspiracy of silence at the interactive prompt:
> 
> Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
> 
> IDLE 1.1.3   No Subprocess 
 help(exec)
> SyntaxError: invalid syntax
> Its the same under Linux SuSe, Python 2.5.1.
> 
> I think this is a BUG.

No, it's the way exec is defined. exec is not a function, it's a
statement. "help(exec)" raises a syntax error like "help(if)" or
"help(while)" would raise a syntax error, too.

Christian

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


Re: optparse question

2009-01-27 Thread Thorsten Kampe
* John Machin (Tue, 27 Jan 2009 05:31:42 -0800 (PST))
> Nobody is upset, and nobody has "gone off on a tear". The point about
> the "Windows example" is that the docs say in a close-to-screamingly-
> obvious manner that /options are not supported, no matter what
> religion uses them. It was not, and still is not, apparent what you
> really wanted. We're all patiently waiting for you to rephrase the
> question(s).

Amen, brother.

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


Re: optparse with numpy.array?

2009-01-27 Thread Steve Holden
Johan Ekh wrote:
> Thanks,
> James I will try your suggestion!
> Robert, what mean with "interactively" is that i would like to create an
> array in the ipython shell, e.g. with m_i = array([1.0, 2.0, 3.0]) or
> by reading a file with values etc., and then execute my program with
> "myprog -m m_i" and thus pass the array "m_i" to my program.
> 
> This is just an example. I would like to pass several arrays. My program
> will be wrapped inside a loop and the arrays are updated
> in each loop.
> 
The bottom line is that there is no "natural" way to pass Python objects
through the command line, so you will need to find a natural way to
represent the objects as character strings, and then extend the optparse
module to recognize that type.

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 many followers of comp.lang.python

2009-01-27 Thread Vincent Davis
Being a newbie and not aware of other good places to ask dump questions. I
have been very happy with the help I have gotten. Some of the
other discussions are a little interesting to me but I wonder/am grateful if
these keep the knowledgeable people around so us newbies can ask questions.
Since I am a beginner programer and new to python it is really help to have
a place to ask quick or long questions. Books are nly so good, Google helps
but it doesn't debug code for you.
Thanks
Vincent Davis



On Tue, Jan 27, 2009 at 10:13 AM, Grant Edwards  wrote:

> On 2009-01-27, Bruno Desthuilliers
>  wrote:
>
> > Please visit comp.databases or comp.lang.javascript for really
> > unfriendly and unhelpful places where few happens except
> > "bickering and name-calling".
>
> I've always found comp.lang.c to be a rather dangerous place as
> well.
>
> Of the newsgroups I read, c.l.python is probably the most
> friendly and has one of the highest S/N ratios.  People who
> would have been roasted alive in other newsgroups for their
> laziness or presumptuousness get surprisingly gentle treatment
> in c.l.python.  I do know of a few low-volume mailing lists
> that are probably as good, but for a Usenet news group with any
> volume at all, c.l.pythong is exceptionally good.
>
> --
> Grant Edwards   grante Yow! I wonder if I
> should
>  at   put myself in ESCROW!!
>   visi.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression, help

2009-01-27 Thread Vincent Davis
is BeautifulSoup really better? Since I don't know either I would prefer to
learn only one for now.
Thanks
Vincent Davis



On Tue, Jan 27, 2009 at 10:39 AM, MRAB  wrote:

> Vincent Davis wrote:
>
>> I think there are two parts to this question and I am sure lots I am
>> missing. I am hoping an example will help me
>> I have a html doc that I am trying to use regular expressions to get a
>> value out of.
>> here is an example or the line
>> Parcel ID: 39-034-15-009 
>> I want to get the number "39-034-15-009" after "Parcel ID:" The number
>> will be different each time but always the same format.
>> I think I can match "Parcel ID:" but not sure how to get the number after.
>> "Parcel ID:" only occurs once in the document.
>>
>> is this how i need to start?
>> pid = re.compile('Parcel ID: ')
>>
>> Basically I am completely lost and am not finding examples I find helpful.
>>
>> I am getting the html using myurl=urllib.urlopen(). Can I use RE like this
>> thenum=pid.match(myurl)
>>
>> I think the two key things I need to know are
>> 1, how do I get the text after a match?
>> 2, when I use myurl=urllib.urlopen(http://...). can I use the myurl
>> as the string in a RE, thenum=pid.match(myurl)
>>
>>  Something like:
>
> pid = re.compile(r'Parcel ID: (\d+(?:-\d+)*)')
> myurl = urllib.urlopen(url)
> text = myurl.read()
> myurl.close()
> thenum = pid.search(text).group(1)
>
> Although BeautifulSoup is the preferred solution.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


change syntax coloring in IDLE

2009-01-27 Thread Vincent Davis
I am using mac with python 2.5.2 and IDLE verison 1.2.2. in the help it
states I can change he text coloring by using "Configure IDLE" but I not
sure what this is. It's not sn the menu, running Configure does nothing. How
do I change the color (text and background)
Thanks
Vincent Davis
--
http://mail.python.org/mailman/listinfo/python-list


Re: Exec woes

2009-01-27 Thread Chris Rebert
On Tue, Jan 27, 2009 at 9:34 AM, Christian Heimes  wrote:
> Hendrik van Rooyen schrieb:
>> It starts with the conspiracy of silence at the interactive prompt:
>>
>> Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on 
>> win32
>> Type "copyright", "credits" or "license()" for more information.
>>
>> IDLE 1.1.3   No Subprocess 
> help(exec)
>> SyntaxError: invalid syntax
>> Its the same under Linux SuSe, Python 2.5.1.
>>
>> I think this is a BUG.
>
> No, it's the way exec is defined. exec is not a function, it's a
> statement. "help(exec)" raises a syntax error like "help(if)" or
> "help(while)" would raise a syntax error, too.

Indeed. Although it would happen to work in Python 3.0, as exec()
became a function once again.

Cheers,
Chris

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


Re: regular expression, help

2009-01-27 Thread MRAB

Vincent Davis wrote:
I think there are two parts to this question and I am sure lots I am 
missing. I am hoping an example will help me
I have a html doc that I am trying to use regular expressions to get a 
value out of.

here is an example or the line
Parcel ID: 39-034-15-009 
I want to get the number "39-034-15-009" after "Parcel ID:" The number 
will be different each time but always the same format.
I think I can match "Parcel ID:" but not sure how to get the number 
after. "Parcel ID:" only occurs once in the document.


is this how i need to start?
pid = re.compile('Parcel ID: ')

Basically I am completely lost and am not finding examples I find helpful.

I am getting the html using myurl=urllib.urlopen(). 
Can I use RE like this
thenum=pid.match(myurl) 



I think the two key things I need to know are
1, how do I get the text after a match?
2, when I use myurl=urllib.urlopen(http://...). can I use the myurl 
as the string in a RE, thenum=pid.match(myurl)



Something like:

pid = re.compile(r'Parcel ID: (\d+(?:-\d+)*)')
myurl = urllib.urlopen(url)
text = myurl.read()
myurl.close()
thenum = pid.search(text).group(1)

Although BeautifulSoup is the preferred solution.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I say "two classes up in the inheritance chain" in python?

2009-01-27 Thread Daniel Fetchinson
>> I have two classes that both inherit from two other classes which both
>> inherit from a single class. The two children have two almost
>> identical methods:
>>
>> class grandparent( object ):
>> def meth( self ):
>> # do something
>>
>> class parent1( grandparent ):
>> def meth( self ):
>> # do something p1
>> super( parent1, self ).meth( )
>>
>> class parent2( grandparent ):
>> def meth( self ):
>> # do something p2
>> super( parent2, self ).meth( )
>>
>> class child1( parent1 ):
>> def meth( self ):
>> # do something c
>> super( parent1, self ).meth( ) # I want to invoke meth on
>> grandparent
>
> If so, it might be better to explicitly call grandparent.meth (passing
> self as first argument). But this is an obvious design smell IMHO. What
> you have is :
>
> def meth(self):
>  do_something_more_or_less_specific
>  call_granparent
>
> Looks like a candidate for a template method. Since you don't have hand
> on Grandparent, the simplest would be to add an additional base class, ie:
>
>
> class Abstract(Grandparent):
>  def do_something(self):
>  raise NotImplementedError
>
>  def meth(self):
>  self.do_something()
>  super(Abstract, self).meth()
>
>
> class Parent1(Abstract):
>  def do_something(self):
> # do something p1
>
> class Parent2(Abstract):
>  def do_something(self):
> # do something p2
>
>
> Now you're problem is to factor out do_something() for Child1 and
> Child2. The solution is quite simple : just define it outside the class
> statements, and adds it afterward:
>
> def do_something_children(self):
> # code here
>
> class Child1(Parent1):
>  # code here
>
> Child1.do_something = do_something_children
>
> class Child2(Parent2):
>  # code here
>
> Child2.do_something = do_something_children

Thanks, this was very helpful. Also, thanks Duncan, your simple
suggestion was helpful too to just call the grandparent directly
(without super).

Cheers,
Daniel

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Exec woes

2009-01-27 Thread Stephen Hansen
> IDLE 1.1.3   No Subprocess 
> >>> help(exec)
> SyntaxError: invalid syntax
> >>>
> Its the same under Linux SuSe, Python 2.5.1.
>
> I think this is a BUG.
>

Exec is a statement, not a function nor an object: even though you can
enclose parens around its arguments like you do later on, they don't have
any syntax meaning.

You can't help(print) or help(import) either.


> Anyway, my real problem looks like this:
>
> >>> def Somefunc():
>def excrescence():
> exec('BUILD = "someString"')
> return BUILD
>
> SyntaxError: unqualified exec is not allowed in function 'excrescence
> it is a nested function (, line 3)
> >>>
>
> Now this works if it is not nested, and it works if it is a method in a
> class.
> Why the complaint about the nestedness?
>

Once upon a time, Python had only two scopes or namespaces: local and
globals. It'd look up variables in the local scope and if it didn't find
them, it'd look them up in the global scope. (There's also the builtin
namespace but to not digress...)

Under this scenario, if you define some attributes in Somefunc() those will
NOT be visible within excrescence(). So:

def foo():
a = 5
def bar():
print a # error

wouldn't work.

Then PEP227 came around to add nested scopes -- or lexical scopes. Its what
made "nested" functions like that actually useful: it's what brought
closures into the scenario. As of Python 2.2, within bar() it would be able
to see the definition of a because namespaces can now be nested.

This addition was a problem for a couple features: doing "from blah import
*" within a function, and a bare exec (an exec without an explicit globals()
and locals()) that happened in certain places-- in this case a nested
function. They introduced that SyntaxError to make sure it wouldn't
accidentally hit you. Read up on PEP227 for the full details.

To get around this, you need to specify exactly what scope you want exec to
happen in when you're in a place where the 'current' scope is nested. You
qualify exec--


>
> So there is some namespace thing happening that is too subtle for me, and I
> would like to know what "unqualified" means in the above message, and
> what one must do to "qualify" the statement, if that is what is needed.
>

by doing:

   exec code in , 

In your situation:

>>> def Somefunc():
   def excrescence():
   exec "BUILD = 'someString'" in globals(), locals()

is probably sufficient. globals() returns the dictionary of the global
namespace, locals() the dictionary of the current functions (non-nested)
namespace.

HTH,

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


Re: How many followers of comp.lang.python

2009-01-27 Thread rantingrick
On Jan 27, 10:12 am, Bruno Desthuilliers  wrote:

> All you can say is that he didn't *post* here (at least under his real
> identity...) for the 9 past years - this doesn't mean he never *reads*
> (and this, you just have no way to know).

Ah, this is a good point. You have to wonder, Guido could be one of
the regulars here. very interesting. We should have a vote as to who
would be the most likely candidate, now that would be a good thread :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How many followers of comp.lang.python

2009-01-27 Thread Paul Rubin
Bruno Desthuilliers  writes:
> All you can say is that he didn't *post* here (at least under his real
> identity...) for the 9 past years - this doesn't mean he never *reads*
> (and this, you just have no way to know).

Guido does post here once in a while, under his own name.  I can't
think of any very recent examples, but I can remember some from a few
years back.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unable to print Unicode characters in Python 3

2009-01-27 Thread Thorsten Kampe
* Giampaolo Rodola' (Tue, 27 Jan 2009 04:52:16 -0800 (PST))
> I have this same issue on Windows.
> Note that on Python 2.6 it works:
> 
> Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> print unicode('\u20ac')
> \u20ac
> 
> This is pretty serious, IMHO, since breaks any Windows software
> priting unicode to stdout.
> I've filed an issue on the Python bug tracker:
> http://bugs.python.org/issue5081

For printing to stdout you have to give an encoding that the terminal 
understands and that contains the character. In your case the terminal 
says "I speak cp 850" but of course there is no Euro sign in there. Why 
should that be a bug?

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


Re: A different kind of interface

2009-01-27 Thread BBands
PyScripter does it for me.

http://code.google.com/p/pyscripter/

jab

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


Re: How many followers of comp.lang.python

2009-01-27 Thread rantingrick
On Jan 27, 12:00 pm, Paul Rubin  wrote:
> Guido does post here once in a while, under his own name.  I can't
> think of any very recent examples, but I can remember some from a few
> years back.

I searched the archives for "Guido van Rossum" and there is nothing
since May 2000. That's the most recent i could find anyway??
--
http://mail.python.org/mailman/listinfo/python-list


Re: unable to print Unicode characters in Python 3

2009-01-27 Thread Thorsten Kampe
* Denis Kasak (Tue, 27 Jan 2009 14:22:32 +0100)
> On Tue, Jan 27, 2009 at 1:52 PM, Giampaolo Rodola' 
> wrote:
> > I have this same issue on Windows.
> > Note that on Python 2.6 it works:
> >
> > Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> > (Intel)] on
> > win32
> > Type "help", "copyright", "credits" or "license" for more information.
>  print unicode('\u20ac')
> > \u20ac
> 
> Shouldn't this be
> 
> print unicode(u'\u20ac')

You are trying to create a Unicode object from a Unicode object. Doesn't 
make any sense.
 
> on 2.6? Without the 'u' prefix, 2.6 will just encode it as a normal
> (byte) string and escape the backslash.

You are confusing encoding and decoding. unicode(str) = str.decode. To 
print it you have to encode it again to a character set that the 
terminal understands and that contains the desired character.

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


Re: Why GIL? (was Re: what's the point of rpython?)

2009-01-27 Thread Steve Holden
Bryan Olson wrote:
> Paul Rubin wrote:
>> Bryan Olson  writes:
>>> An object's __dict__ slot is *not* mutable; thus we could gain some
>>> efficiency by protecting the object and its dict with the same lock. I
>>> do not see a major win in Mr. Banks' point that we do not need to lock
>>> the object, just its dict.
>>
>> If the dict contents don't change often, maybe we could use an
>> STM-like approach to eliminate locks when reading.  That would of
>> course require rework to just about every C function that accesses
>> Python objects.
> 
> I'm a fan of lock-free data structure and software transactional memory,
> but I'm also a realist. Heck, I'm one of this group's outspoken
> advocates of threaded architectures. Theoretical breakthroughs will
> happen, but in real world of today, threads are great but GIL-less
> Python is a loser.
> 
> Wherever Python is going, let's recognize that a scripting language that
> rocks is better than any other kind of language that sucks.
> 
> 
Guido, IIRC, has said that he's against any GIL-removal policy that
lowers performance on single-processor systems. Personally I'd be happy
if there were an *alternative* multi-processor implementation that was
slower for single-processor architectures and faster for
multi-processor, but I'm not about to start developing it.

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


pyAA for Python2.5

2009-01-27 Thread Kottiyath
Hi,
   I would like to obtain pyAA for Python 2.5. I went through their
web site, but they provide the windows exe only for Python2.4. I tried
compiling from source, but that also was to no avail - it errs out as
follows:

C:\Documents and Settings\Guest\pyAA>python setup.py install
running install
running build
running build_py
file pyAAc.py (for module pyAAc) not found
file pyAAc.py (for module pyAAc) not found
running build_ext
error: Python was built with Visual Studio 2003;
extensions must be built with a compiler than can generate compatible
binaries.
Visual Studio 2003 was not found on this system. If you have Cygwin
installed,
you can try compiling with MingW32, by passing "-c mingw32" to
setup.py.


C:\Documents and Settings\Guest\pyAA>python setup.py install -c
mingw32
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: invalid command 'mingw32'

Has anyone tried the same? Can anyone give any suggestions?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How many followers of comp.lang.python

2009-01-27 Thread Thorsten Kampe
* rantingrick (Tue, 27 Jan 2009 10:03:16 -0800 (PST))
> On Jan 27, 12:00 pm, Paul Rubin  wrote:
> > Guido does post here once in a while, under his own name.  I can't
> > think of any very recent examples, but I can remember some from a few
> > years back.
> 
> I searched the archives for "Guido van Rossum" and there is nothing
> since May 2000. That's the most recent i could find anyway??

Search again - the last was in December 2008:
http://groups.google.com/groups/search?as_q=&as_epq=&as_oq=&as_eq=&num=
10&scoring=d&lr=&as_sitesearch=&as_qdr=&as_mind=1&as_minm=1&as_miny=2009
&as_maxd=1&as_maxm=1&as_maxy=2009
&as_ugroup=comp.lang.python&as_usubject=&as_uauthors=guido+van+rossum&sa
fe=off
--
http://mail.python.org/mailman/listinfo/python-list


Re: unable to print Unicode characters in Python 3

2009-01-27 Thread Denis Kasak
On Tue, Jan 27, 2009 at 7:08 PM, Thorsten Kampe
 wrote:
> * Denis Kasak (Tue, 27 Jan 2009 14:22:32 +0100)
>> On Tue, Jan 27, 2009 at 1:52 PM, Giampaolo Rodola' 
>> wrote:



>>  print unicode('\u20ac')
>> > \u20ac
>>
>> Shouldn't this be
>>
>> print unicode(u'\u20ac')
>
> You are trying to create a Unicode object from a Unicode object. Doesn't
> make any sense.

Of course it doesn't. :-)

Giampaolo's example was wrong because he was creating a str object
with a non-escaped backslash inside it (which automatically got
escaped) and then converting it to a unicode object. In other words,
he was doing:

print unicode('\\u20ac')

so the Unicode escape sequence didn't get interpreted the way he
intended it to. I then modified that by adding the extra 'u' but
forgot to delete the extraneous unicode().

> You are confusing encoding and decoding. unicode(str) = str.decode. To
> print it you have to encode it again to a character set that the
> terminal understands and that contains the desired character.

I agree (except for the first sentence :-) ). As I said, I simply
forgot to delete the call to the unicode builtin.

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


Re: Why GIL? (was Re: what's the point of rpython?)

2009-01-27 Thread Paul Rubin
Bryan Olson  writes:
> I'm a fan of lock-free data structure and software transactional
> memory, but I'm also a realist. Heck, I'm one of this group's
> outspoken advocates of threaded architectures. Theoretical
> breakthroughs will happen, but in real world of today, threads are
> great but GIL-less Python is a loser.

GIL-less Python (i.e. Jython) already exists and beats CPython in
performance a lot of the time, including on single processors.
Whether the GIL can be eliminated from CPython without massive rework
to every extension module ever written is a separate question, of
course.  Jython can be viewed a proof of concept.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unable to print Unicode characters in Python 3

2009-01-27 Thread Martin v. Löwis
> #include "stdio.h"
> int main(int argc, char **argv) {
> printf("<\xc2\x80>\n");
> }
> 
> compiled with mingw32 (gcc (GCC) 3.4.5 (mingw-vista special r3))
> and using "Lucida Console" font:
> 
> After CHCP 1252, this prints < A-circumflex Euro >, as expected.
> After CHCP 65001, it prints < hollow-square >.

This is not surprising: this character is U+0080, which is a control
character. Try \xe2\x82\xac instead.

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


Re: pyAA for Python2.5

2009-01-27 Thread Mike Driscoll
On Jan 27, 12:12 pm, Kottiyath  wrote:
> Hi,
>    I would like to obtain pyAA for Python 2.5. I went through their
> web site, but they provide the windows exe only for Python2.4. I tried
> compiling from source, but that also was to no avail - it errs out as
> follows:
>
> C:\Documents and Settings\Guest\pyAA>python setup.py install
> running install
> running build
> running build_py
> file pyAAc.py (for module pyAAc) not found
> file pyAAc.py (for module pyAAc) not found
> running build_ext
> error: Python was built with Visual Studio 2003;
> extensions must be built with a compiler than can generate compatible
> binaries.
> Visual Studio 2003 was not found on this system. If you have Cygwin
> installed,
> you can try compiling with MingW32, by passing "-c mingw32" to
> setup.py.
>
> C:\Documents and Settings\Guest\pyAA>python setup.py install -c
> mingw32
> usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
>    or: setup.py --help [cmd1 cmd2 ...]
>    or: setup.py --help-commands
>    or: setup.py cmd --help
>
> error: invalid command 'mingw32'
>
> Has anyone tried the same? Can anyone give any suggestions?

You probably have to put mingw32 on your path or provide an absolute
path to it. By the way, where did you get the source? I couldn't find
it...

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


  1   2   3   >