Re: Basic python help

2006-03-13 Thread John M. Gabriele
(Please don't top-post -- fixed)

Kevin Feng wrote:

> 
> 
> On 3/14/06 2:12 AM, in article [EMAIL PROTECTED],
> "Gregor Horvath" <[EMAIL PROTECTED]> wrote:
> 
> 
>>Kevin Feng schrieb:
>>
>>
>>>More information about this error may be available in the server error log.
>>>
>>>
>>>
>>>Any suggestions?  Much thanks.
>>>
>>
>>What does the error log of the webserver say?
>>
>>--
>>Greg
> 

 > No idea, I do not have permission to access the error log.
 >
 >

In your cgi script, try putting "import cgitb; cgitb.enable()"
on the next line right after "import cgi".

Also try changing your POST to GET.

---John
-- 
(remove zeez if demunging email address)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic python help

2006-03-13 Thread Kevin Feng
No idea, I do not have permission to access the error log.




On 3/14/06 2:12 AM, in article [EMAIL PROTECTED],
"Gregor Horvath" <[EMAIL PROTECTED]> wrote:

> Kevin Feng schrieb:
> 
>> More information about this error may be available in the server error log.
>> 
>> 
>> 
>> Any suggestions?  Much thanks.
>> 
> 
> What does the error log of the webserver say?
> 
> --
> Greg

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


Re: doctest-alike for a unix shell?

2006-03-13 Thread Paddy
Thanks for the pointer to dejagnu, although it is not what I was after.

The question came about because I was scripting an interface to an
electronics design automation tool that comes with a TCL interface.
I was using a companion perl script called from the TCL to do most of
the more complex checking (I am still not allowed Python at work, sob).

I found myself testing the perl script by calling it repeatedly from
tcsh , with different options and different files and directories
created in its run directory that I knew it was sensitive to. I
scrolled back in my xterm window and thought that there before me was
most of my tests! If only their was doctest for tcsh, I could tell the
tool what my prompt strings were, cut-n-paste my shell session, and
Bobs yer uncle!

I guess doctest-alikes could be created for a lot of shell type
interfaces with distinct prompts.

- Paddy.

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


Re: markov query

2006-03-13 Thread Stefan Behnel
Don't know of a Python module (although this doesn't look complex enough for a
package anyway...), but

kpp9c wrote:
> P.S. Does any one know first of all whether these are called markov
> tables, transition tables or probability tables? I am not sure i am
> referring to this correctly and what the differences would be if any

as for terminology:

http://www.csse.monash.edu.au/~lloyd/tildeMML/Structured/HMM.html
http://en.wikipedia.org/wiki/Hidden_Markov_model


Hope it helps,
Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic python help

2006-03-13 Thread Gregor Horvath
Kevin Feng schrieb:

> More information about this error may be available in the server error log.
> 
> 
> 
> Any suggestions?  Much thanks.
> 

What does the error log of the webserver say?

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


Basic python help

2006-03-13 Thread Kevin Feng
Title: Basic python help



I have the following simple html file that is trying to send data to a python script, however, I am getting a weird server error:

This is my HTML:



Ticker 1









This is my Python:

#!/usr/bin/python

import cgi
print "Content-type: text/html"
print

form = cgi.FieldStorage()
print form.keys()

print ""

for x in form.keys():
print "%s=%s" % (x, form[x].value) + ""


This is my error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, [EMAIL PROTECTED] and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.



Any suggestions?  Much thanks.



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

Memory visualization

2006-03-13 Thread bearophileHUGS
Icon is a language that share some similarities with Python:
http://www.cs.arizona.edu/icon/

During the execution of a Icon script there are ways to visualize the
memory:
http://www.cs.arizona.edu/icon/progvis/memmon/memmon.htm

Related pages:
http://www.cs.arizona.edu/icon/progvis/workshop/workshop.htm
http://www.cs.arizona.edu/icon/progvis/progvis.htm

I'd like to know if for Python there is a similar program to
dynamically see the memory in a similar way.
If such tool doesn't exist yet, I'd like to know if it may be diffifult
to create it.

Bye,
bearophile

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


catching java program return

2006-03-13 Thread eight02645999
hi

i have to run a java program inside my python script.
i have some java classes declared:
os.environ['CLASSPATH'] = "blah path"

then i used the os.system method to invoke the java program and using
ret = os.WEXITSTATUS(os.system(cmd)) to catch the return

Java gave me an error about unable to locate some classes,  and the ret
value is 0. Why is this so? thanks
can anyone advise also on how can i properly catch the correct Java
generated exceptions in the above case. I was thinking i could use
subprocess module, is there a good example of using this module instead
of using os.system? or are they both achieve the same results?

thanks very much for your help.

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


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

2006-03-13 Thread Raymond Hettinger
[robert]
> In very rare cases a program crashes (hard to reproduce) :
>
> * several threads work on an object tree with dict's etc. in it. Items
> are added, deleted, iteration over .keys() ... ). The threads are "good"
> in such terms, that this core data structure is changed only by atomic
> operations, so that the data structure is always consistent regarding
> the application. Only the change-operations on the dicts and lists
> itself seem to cause problems on a Python level ..
>
> * one thread periodically pickle-dumps the tree to a file:
>>>> cPickle.dump(obj, f)
>
> "RuntimeError: dictionary changed size during iteration" is raised by
> .dump ( or a similar "..list changed ..." )
>
> What can I do about this to get a stable pickle-dump without risiking
> execution error or even worse - errors in the pickled file ?

See if this fixes the problem for you:

try:
sys.setcheckinterval(sys.maxint)
cPickle.dump(obj, f)  # now runs atomically
finally:
sys.setcheckinterval(100)


Be careful where you use this technique.  In addition to suspending
other threads, it has the side-effect of suspending control-break
checks.  IOW, you won't be able to break out of the dump().



Raymond

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


Re: Accessing overridden __builtin__s?

2006-03-13 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> I'm having a scoping problem.  I have a module called SpecialFile,
> which defines:
> 
> def open(fname, mode):
>   return SpecialFile(fname, mode)
> 
> class SpecialFile:
> 
>   def __init__(self, fname, mode):
> self.f = open(fname, mode)
> ...
> 
[snip]
> 
> How do I tell my class that I want to refer to the __builtin__ open(),
> and not the one defined in the module?

import __builtin__
...
 self.f = __builtin__.open(fname, mode)
...

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


Accessing overridden __builtin__s?

2006-03-13 Thread garyjefferson123
I'm having a scoping problem.  I have a module called SpecialFile,
which defines:

def open(fname, mode):
  return SpecialFile(fname, mode)

class SpecialFile:

  def __init__(self, fname, mode):
self.f = open(fname, mode)
...


The problem, if it isn't obvioius, is that the open() call in __init__
no longer refers to the builtin open(), but to the module open().  So,
if I do:

f = SpecialFile.open(name, mode)

I get infinite recursion.

How do I tell my class that I want to refer to the __builtin__ open(),
and not the one defined in the module?

Thanks,
Gary

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


Re: sizeof(struct timeval)

2006-03-13 Thread David Bolt
On Tue, 14 Mar 2006, Tony Houghton <[EMAIL PROTECTED]>
wrote:-



>In any case, it does imply that timeval can be relied on to be 2 *
>32-bits (2 * long) in 32-bit architectures and something else in 64-bit
>architectures - where long is 64-bit.

Using the source below for a quick test on both a 32 and 64 bit SUSE
system[0], I get a size of 8 bytes on the 32 bit system, which implies 2
* 32 bit, and 16 ( 2 * 64 bit) on the 64 bit system.


/*
 quick, boring, and probably could do with a major cleanup
 but it should be fine
*/
#include 
#include 
#include 
#include 

int main(void)
{
 int the_size=sizeof(struct timeval);
 printf("%u\n", the_size);
 exit(0);
}



[0] see .sig for details.

Regards,
  David Bolt

-- 
Member of Team Acorn checking nodes at 50 Mnodes/s: http://www.distributed.net/
AMD1800 1Gb WinXP/SUSE 9.3  | AMD2400 256Mb SuSE 9.0  | A3010 4Mb RISCOS 3.11
AMD2400(32) 768Mb SUSE 10.0 | RPC600 129Mb RISCOS 3.6 | Falcon 14Mb TOS 4.02
AMD2600(64) 512Mb SUSE 10.0 | A4000 4Mb RISCOS 3.11   | STE 4Mb TOS 1.62
-- 
http://mail.python.org/mailman/listinfo/python-list


markov query

2006-03-13 Thread kpp9c
markov query

I have noticed a couple markov implementations in python, but none
quite seem to do what i would like. Most seem to do an analysis of some
text and create a new text based on that... I think, (sorry i just
don't know terminology well) a markov table (or is it called a
transition table) to describe how to get from one event to another.  So
if i have 3 events, say,  A, B, and C which can come in any order, a
Markov chain describes the probability of what the next event will be
using a table. The following table demonstrates a first-order Markov
chain. There are three possible states. Either the current event is A,
B, or C. For each possible current state, there are three possible next
letters. Each row in the table indicates the relative probability of
going to the next letter. For example, if you are currently on letter
A, there is a 20% chance of repeating letter A, a 50% chance of going
to B, and a 30% chance of going to C. Note that the sum of changes for
each row is 100% (20 + 50 + 30 = 100).

Current -- next -- next -- next
A - B - C
  A:20% -- 50% -- 30%
  B:35% -- 25% -- 40%
  C:70% -- 14% -- 16%

Here the sequence C B and C C would be rare and the sequence C A
common.

This is a first-order Markov chain, which means that only the current
state affects the choice of the next event. A second-order Markov chain
would mean that the current state and the last state affect the choice
of the next event. A third-order Markov chain would indicate that the
current state and the last two states in the sequence will affect the
choice of the next state, and so on. Here is an example transition
table for a 2nd order Markov chain.

Current -- next -- next -- next
A - B - C
  A A  15% 55% 30%
  A B  20% 45% 35%
  A C  60% 30% 10%
  B A  35% 25% 40%
  B B  49% 48% 3%
  B C  60% 20% 20%
  C A  5%  75% 20%
  C B  0%  90% 10%
  C C  70% 14% 16%

For example, if the current event is B and the last one was A, then the
probability of the next event being A is 20%, B is 45% and C is 35%.
The pattern C B A will never occur, and the pattern B B C will occur
rarely.

Does anyone know of any modules or packages that include markov tables
for creating patterns like shown above.


P.S. Does any one know first of all whether these are called markov
tables, transition tables or probability tables? I am not sure i am
referring to this correctly and what the differences would be if any

cheers,

kp

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


how to get all users that currently logged in?

2006-03-13 Thread iclinux
we can do it with 'who' in *nuix,  but os.getlogin() returns only the
user of the current process...
how to do it by python, any suggestions?

Best Regards.

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


Re: "RuntimeError: dictionary changed ... & Ruby

2006-03-13 Thread Alex Martelli
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

> In <[EMAIL PROTECTED]>, robert wrote:
> 
> > * Ruby without refcounts provides no deterministic __del__ in 
> > non-circular refs ==> your type  finally finally finally .close .close
> > .close all the time
> 
> Which is what you should type in Python too as there's no guarantee that
> `__del__()` will be called immidiatly when the file object goes out of
> scope or isn't referenced anymore.  The reference counting memory
> management is an implementation detail.

Absolutely true -- which is why Python 2.5 adds a new `with' statement
that allows using the powerful idiom "resource acquisition is
initialization" without relying on any implementation details (yay!).


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


Re: New python.org website

2006-03-13 Thread robin
"Michael Tobis" <[EMAIL PROTECTED]> wrote:

>While the new one is much better than the old website, the logo strikes
>me as awful.

I personally believe the new logo is miles better than the old one.
Whether you see snakes or a plus-sign or a yin-yang, it has a nice
harmonious look that still captures some playfulness. 

Besides, why is everyone fixated on snakes? Python the language has
nothing to do with python the constrictor.

As far as the layout goes, I still find it too busy. Specifically
there are too many fonts on the one page. But I have already made that
point, and did an entire version of the homepage, which the team have
taken as input.

Anyone who has the time can do the same, rather than simply comment
from the sidelines. The best websites never stay still, but are
constantly evolving. I hope python.org can do the same, and go from
strength to strength.

Congratulations to all involved!
-
robin
noisetheatre.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2006-03-13 Thread Raymond Hettinger
[robert]
> That queue/passing-through-only-an-extra-global-var communication is
> acceptable for thin thread interaction.
> ( hope this extra global var is thread-safe in future Python's :-) )
>
> But "real" thread-programming should also be possible in Python - and it
> is with the usual discipline in thread programming.

LOL, I'm glad you put "real" in quotes, and I'm glad that you recognize
that apps with intrinsic race conditions are not following "the usual
discipline in thread programming."

Embedded in this discussion is a plausable suggestion for Py2.5 to
offer a way for a thread to temporarily block thread switches while it
does something that needs to be atomic; however, the given use case is
on thin ice as a motivating example (because of the intrinsic race
condition, avoidance of locks, and avoidance of queues).


>This RuntimeError in
> iterations is the (necessary) only compromise, I know of. (Maybe this
> RuntimeError must not even be thrown from Python, when walking through
> variable sequences is done smartly - but smart practice may cost speed,
> so a compromise.)
>
> It can be handled commonly by keys() and some error catching. key
> functions like deepcopy and dump (which cannot easily be subclassed)
> should fit into that "highest common factor" and not "judge" themselves
> about _how_ thread programming has to be done.
 . . .
> In addition Python should define its time atoms, and thus also the
> definite sources of this (unavoidable?) RuntimeError - as explained in
> the later link.

Since others have responded directly to these thoughts, I'll aim at the
bigger picture and make an observation on Python sociology.  Most users
are aware that Python is not cast in stone and that good ideas are
always welcome.  That is usually a good thing, but it sometimes creates
a pitfall.  When someone programs themselves into a corner, they
usually get a cue that something is wrong with their design concept or
that they are not working harmoniously with the language; however, in
the Python world, it is tempting avoid questioning one's own design and
instead start to assume that the language itself is misconcieved.

A good language suggestion should be general purpose,
easy-to-understand, universal across implementations, and solve more
than one use case.  It is bad sign if you have to propose multiple,
simultaneous language changes just to get your script to work.
Likewise, it is a bad sign if the use case is somewhat unusual (i.e.
supporting an app with an intrinsic race-condition).  Also, it is a bad
sign if the proposal is over-specific and ad-hoc (i.e. imposing
memory-intensive requirements on random pieces of library code about
how the code is allowed to loop over dictionaries).

Those criteria for good language proprosals are not met by requests to
start making pieces of pure python code try to fake atomicity.
However, there is a some chance for Py2.5 to introduce a thread-switch
lock (as I proposed in my previous post).  If that is what you want,
feel free to log a SourceForge feature request (preferably with a
sensible use case and no troll phrases like "real" thread programming).


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

I sure hope your code isn't being used in mission critical apps like
air traffic control :=0


Raymond

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


Re: sizeof(struct timeval)

2006-03-13 Thread Tony Houghton
In <[EMAIL PROTECTED]>,
Big and Blue <[EMAIL PROTECTED]> wrote:

> Big and Blue wrote:
> > Tony Houghton wrote:
> >>
> >> How safe would I be assuming that
> >> sizeof(struct timeval) == 2 * sizeof(long)
> >>
> >> is always true on Linux on different architectures?
> >
> >Based on what I was looking at today (well, yesterday now), you might
> > be wrong.
>
> However, it looks as though I was wrong:

[Snip headers showing my assumption is correct for his PC too]

I've already looked at those headers too. But most of the definitions
look like internal types and I'm not confident I can rely on them
staying the same size. But I don't think there's a strong enough case
for changing them to justify the glibc ABI change etc, so I'm probably
safe.

-- 
The address in the Reply-To is genuine and should not be edited.
See  for more reliable contact addresses.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sizeof(struct timeval)

2006-03-13 Thread Tony Houghton
In <[EMAIL PROTECTED]>,
Big and Blue <[EMAIL PROTECTED]> wrote:

> Tony Houghton wrote:
>> 
>> How safe would I be assuming that 
>> 
>> sizeof(struct timeval) == 2 * sizeof(long)
>> 
>> is always true on Linux on different architectures? 
>
> Based on what I was looking at today (well, yesterday now), you might 
> be wrong.
>
> I do know that the size of a struct utmp differs between a Linux 
> Itanium system and a Linux x86_64 system, and I seem to recall it migh be 
> related to timeval.  I could be wrong - I wasn't interested in the timeval 
> part - but this part of the bits/utmp.h include file indicates the issue:

So is __WORDSIZE_COMPAT32 defined for one of Itanium or x86_64 but not
the other? The comment in the code below implies the opposite of what
you're saying: the size in 64-bit mode has to be the same as in 32-bit
mode, and as both CPUs have the same 32-bit architecture they should
therefore both use the same sized struct in 64-bit mode.

In any case, it does imply that timeval can be relied on to be 2 *
32-bits (2 * long) in 32-bit architectures and something else in 64-bit
architectures - where long is 64-bit.

> /* The ut_session and ut_tv fields must be the same size when compiled
> 32- and 64-bit.  This allows data files and shared memory to be
> shared between 32- and 64-bit applications.  */
> #if __WORDSIZE == 64 && defined __WORDSIZE_COMPAT32
>int32_t ut_session;   /* Session ID, used for windowing.  */
>struct
>{
>  int32_t tv_sec; /* Seconds.  */
>  int32_t tv_usec;/* Microseconds.  */
>   } ut_tv;  /* Time entry was made.  */
> #else
>long int ut_session;  /* Session ID, used for windowing.  */
>struct timeval ut_tv; /* Time entry was made.  */
> #endif

-- 
The address in the Reply-To is genuine and should not be edited.
See  for more reliable contact addresses.
-- 
http://mail.python.org/mailman/listinfo/python-list


python question about classes

2006-03-13 Thread diffuser78
I have following two classes
Code:

## file_A.py
class A(object):
## a contains is instances of A
a= [ ] def __init__(self, node):
self.nodes_in_A = []
self.nodes_in_A.append(node) packet_queue = [ ] ...etc

## file_B.py
import A
class B(object):
## n contains instances of B
n = [ ] def some_func(self):
_len = len (A.A.a[0].packet_queue)


I get an error AttributeError: 'A' object has no attribute
'packet_queue'


Can you please explain me ...why ? and How to fix this ?

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


Re: Very, Very Green Python User

2006-03-13 Thread Terry Hancock
On 12 Mar 2006 17:58:43 -0800
[EMAIL PROTECTED] wrote:
> Double-underscore methods are rewritten with the class
> name? That's an ugly hack, but remember I'm coming from
> Perl. If the language doesn't pull many other hijinks,
> that's OK.

This is GvR's way of saying "do not use double-underscore
methods". ;-)

You shouldn't ever see the mangled ___
form, unless you've been very, very naughty.

And if you have been, well, we promise not to tell anybody,
but it's Your Problem [TM].

Seriously, truly private methods are generally not something
you want to mess with in Python. Quite frequently, people
with a C++ or Java background come here and ask for them. A
Frequently Repeated Thread ensues:

0) I want private methods in Python

1) you don't need 'em

2) C++ and Java have 'em and the book says you have to
   have 'em, or you aren't doin' OOP

3) total hogwash -- I can use compiler directives to
   defeat C++/Java "private" variables anyday, so it
   doesn't accomplish anything that isn't easier to
   do by putting "__" in front of it to tell the client
   programmer not to use it.

Then we all go back to coding.

Cheers and good luck with your project,  ;-)
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


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

2006-03-13 Thread Terry Hancock
On Mon, 13 Mar 2006 17:18:16 +0100
"Martin P. Hellwig" <[EMAIL PROTECTED]> wrote:

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

In short, if you don't know what it is, you don't need it.
;-)

So far, the only time I've ever encountered this is with the
__new__ method, which, being a classmethod, needs "cls"
(which gets loaded with the *class* not the *instance*).

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: sizeof(struct timeval)

2006-03-13 Thread Big and Blue
Big and Blue wrote:
 > Tony Houghton wrote:
 >>
 >> How safe would I be assuming that
 >> sizeof(struct timeval) == 2 * sizeof(long)
 >>
 >> is always true on Linux on different architectures?
 >
 >Based on what I was looking at today (well, yesterday now), you might
 > be wrong.

However, it looks as though I was wrong:

linux/time.h:
  struct timeval {
  time_t  tv_sec; /* seconds */
  suseconds_t tv_usec;/* microseconds */
  };

time.h:
  typedef __time_t time_t;

sys/time.h:
  typedef __suseconds_t suseconds_t;

bits/types.h:
  __STD_TYPE __TIME_T_TYPE __time_t;  /* Seconds since the Epoch.  */
  ...
  __STD_TYPE __SUSECONDS_T_TYPE __suseconds_t; /* Signed count of microseconds 
*/


bits/typesizes.h:
  #define __TIME_T_TYPE   __SLONGWORD_TYPE
  ...
  #define __SUSECONDS_T_TYPE  __SLONGWORD_TYPE

bits/types.h:
  #define __SLONGWORD_TYPElong int



-- 
  Just because I've written it doesn't mean that
   either you or I have to believe it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sizeof(struct timeval)

2006-03-13 Thread Big and Blue
Tony Houghton wrote:
> 
> How safe would I be assuming that 
> 
> sizeof(struct timeval) == 2 * sizeof(long)
> 
> is always true on Linux on different architectures? 

Based on what I was looking at today (well, yesterday now), you might 
be wrong.

I do know that the size of a struct utmp differs between a Linux 
Itanium system and a Linux x86_64 system, and I seem to recall it migh be 
related to timeval.  I could be wrong - I wasn't interested in the timeval 
part - but this part of the bits/utmp.h include file indicates the issue:


/* The ut_session and ut_tv fields must be the same size when compiled
32- and 64-bit.  This allows data files and shared memory to be
shared between 32- and 64-bit applications.  */
#if __WORDSIZE == 64 && defined __WORDSIZE_COMPAT32
   int32_t ut_session;   /* Session ID, used for windowing.  */
   struct
   {
 int32_t tv_sec; /* Seconds.  */
 int32_t tv_usec;/* Microseconds.  */
   } ut_tv;  /* Time entry was made.  */
#else
   long int ut_session;  /* Session ID, used for windowing.  */
   struct timeval ut_tv; /* Time entry was made.  */
#endif


-- 
  Just because I've written it doesn't mean that
   either you or I have to believe it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Q's: pythonD and range(1,12)

2006-03-13 Thread Raymond Hettinger
John Savage wrote:
> Could
> someone please explain the rationale behind python designers' thinking
> in deciding the function "range(1,12)" should return the sequence 1 to
> 11 rather than the more intuitively-useful 1 to 12??

There are several ways to do this, closed intervals, half-open
intervals, zero indexed, indexed from one, etc.   Each way has its own
strengths and weaknesses.  Guido chose the one he liked best and
applied the concept consistently throughout the language (slicing,
etc).  His choice has some nice properties such as len(range(n))==n and
range(0,i)+range(i,n)==range(n).

The downside of the half-open interval approach is that it can be
confusing when counting backwards:  range(n-1, -1, -1).  Accordingly,
the builtin reversed() function was introduced so you could write this
in a more intuitive and readable manner:  list(reversed(range(n))).

Some of this is a matter of taste and a matter of what you're used to
using, so the answer to what is the "more intuitively-useful" varies
depending on who is answering the question.


Raymond

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


Is xml.dom.minidom.Element.cloneNode(deep=True) really fixed already?

2006-03-13 Thread Sullivan WxPyQtKinter
Hi, I am now using minidom for my current development. I use cloneNode
method in Element object, but it just does not work. The test code is
very simple as follows:

=CODE==
from xml.dom.minidom import *
a=Element('see')
print a.toprettyxml()

b=a.cloneNode(True)
print b.toprettyxml()
---END CODE---



Traceback (most recent call last):
  File "D:\__Apply\test8XML.py", line 10, in -toplevel-
b=a.cloneNode(True)
  File "C:\Python24\lib\xml\dom\minidom.py", line 211, in cloneNode
return _clone_node(self, deep, self.ownerDocument or self)
  File "C:\Python24\lib\xml\dom\minidom.py", line 1814, in _clone_node
if node.ownerDocument.isSameNode(newOwnerDocument):
AttributeError: 'NoneType' object has no attribute 'isSameNode'

--result end--

Since the prototype of cloneNode is cloneNode(deep), which does not
indicate the type of deep, I also tied other non-None value like
cloneNode(1), cloneNode('a') etc.None of them work.
Referencing the document, I have seen in python 2.0, this function was
very broken. But my Python version is quite up-to-date: version 2.4.1.

Is it a bug still not fixed??

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


sizeof(struct timeval)

2006-03-13 Thread Tony Houghton
I'm writing a python program which reads input device events so it needs
to know sizeof(struct timeval). By using the struct module I should be
able to work out sizeof(long) from python, but I can't think of a way to
measure non-fundamental types without including a little bit of C,
which I'd rather avoid.

How safe would I be assuming that 

sizeof(struct timeval) == 2 * sizeof(long)

is always true on Linux on different architectures? AFAIK the input
device interface is Linux-specific so I don't need to worry about other
OS's.

-- 
The address in the Reply-To is genuine and should not be edited.
See  for more reliable contact addresses.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help Create Good Data Model

2006-03-13 Thread mwt

fumanchu wrote:
> If you used a Queue, it wouldn't be the container itself; rather, it
> would be a gatekeeper between the container and consumer code. A
> minimal example of user-side code would be:
>
> class Request:
> def __init__(self, op, data):
> self.op = op
> self.data = data
> self.reply = None
> req = Request('get', key)
> data_q.put(req, block=True)
> while req.reply is None:
> time.sleep(0.1)
> do_something_with(req.reply)
>
> The container-side code would be:
>
> while True:
> request = data_q.get(block=True)
> request.reply = handle(request)
>
> That can be improved with queue timeouts on both sides, but it shows
> the basic idea.
>
>
> Robert Brewer
> System Architect
> Amor Ministries
> [EMAIL PROTECTED]

I get it. That's cool.
Here's the latest incarnation of this code. I haven't implemented the
lock you suggested yet, although this version seems to be working fine.


#!/usr/bin/python
# author mwt
# Mar '06
import copy, threading, observable

class FAHData(observable.Observable):
"""The data model for the [EMAIL PROTECTED] monitor."""

def __init__(self):
observable.Observable.__init__(self)
self.data = {}#this dict will hold all data
self.mutex = threading.RLock()

def get_all_data(self):
"""Returns a COPY of entire data dict."""
#not sure deepcopy() is really necessary here
#but using it for now
#might cause some weird synchronization problems...
self.mutex.acquire()
try:
return copy.deepcopy(self.data)
finally:
self.mutex.release()

def get_data(self, key):
"""Returns a COPY of  data element."""
self.mutex.acquire()
try:
return copy.deepcopy(self.data[key])
finally:
self.mutex.release()

def set_value(self, key, value):
"""Sets value of  data element."""
self.mutex.acquire()
try:
self.data[key] = value
observable.Observable.notifyObservers(self, event =
'VALUE_CHANGED', key = key)
finally:
self.mutex.release()

def set_values(self, values):
"""Sets a list of values"""
self.mutex.acquire()
try:
for value in values:
self.data[value] = values[value]
#print 'values input are: %s' %self.data
observable.Observable.notifyObservers(self, event =
'VALUES_CHANGED', keys = values.keys())
finally:
self.mutex.release()

def set_data(self, data):
"""Sets entire data dictionary."""
self.mutex.acquire()
try:
self.data = data
observable.Observable.notifyObservers(self, event =
'DATA_SET')
finally:
self.mutex.release()

def clear_data(self):
"""Clears entire data dictionary."""
self.mutex.acquire()
try:
self.data = {}
observable.Observable.notifyObservers(self, event =
'DATA_CLEARED')
finally:
self.mutex.release()

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


Re: global namescape of multilevel hierarchy

2006-03-13 Thread Ben Cartwright
Sakcee wrote:
> now in package.module.checkID function, i wnat to know what is the ID
> defiend in the calling scriipt

It's almost always a really bad idea to kludge scopes like this.  If
you need to access a variable from the caller's scope in a module
function, make it an argument to that function.  That's what arguments
are for in the first place!

But, if you must, you can use the inspect module:

  import inspect
  def checkID():
  ID = inspect.currentframe().f_back.f_locals['ID']
  print ID

--Ben

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


Re: Q's: pythonD and range(1,12)

2006-03-13 Thread Tim Leslie
On 3/14/06, John Savage <[EMAIL PROTECTED]> wrote:
I've very new to python, and am currently toying with pythonD. Couldsomeone please explain the rationale behind python designers' thinkingin deciding the function "range(1,12)" should return the sequence 1 to
11 rather than the more intuitively-useful 1 to 12??The range() function maps closely to a very common idiom in c-like languages.for (i = a; i < b; i++) { do_stuff(i); }in a C-like language is the same as
for i in range(a, b): do_stuff(i)in python. Another way to think about it is to notice that if you do range(10), you get exactly 10 items in your list (starting at 0), so going from 0 to n-1 is the correct way to go. Having the "start from zero" case work intuitively is the starting point and being able to specify a different starting value to zero simply generalises on this.
Are you sure you need your range to start at 1? It's a common newbie error to start counting from 1 instead of zero in some places, but I won't accuse you of such an error without seeing more context :-)HTH
Tim After downloading the substantial distribution .zip file, I'm intrigued
to find it includes 3 files of identical size and creation date, differingapparently only in name (python, python2.4 and python24.exe) and each ofexactly 2,597,888 bytes. What possible purpose could be served by such
triplication that couldn't more efficiently be done by other means?Naive but curious minds wish to know!--John Savage   (my news address is not valid for email)--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Cross Module Command Useage

2006-03-13 Thread Terry Hancock
On Sun, 12 Mar 2006 21:50:32 +0800
"Keith" <[EMAIL PROTECTED]> wrote:
> So lets say have two modules.. moduleA and moduleB. they
> are both imported into a main python program using the
> "from module import *" command. now moduleA has a dynamic
> command that needs to access a command that is in moduleB.
> but when I run these modules from the main python scrip
> they cant see each other.. it gives me an error that the
> command does not exist. Dose this mean that I need to
> import moduleB into moduleA for it to see it. or is there
> a way that I can tell moduleA too look out to the main
> python program for the commands. 

Yes, you need for "moduleA" to import "moduleB" before
it can do that.

That's not as bad as it sounds, because once you've imported
a module once, all the work is done -- later imports do
nothing except grab an existing namespace for you.

The one caveat that you get into, is don't try to design
two "friend" modules that import each other.  This results
in an impossible situation (it's recursive).

If you have something that two modules both need, and
a module which needs both of those modules, you should
break the functionality up into four modules, e.g.:

   common_utils.py
   /\
   modA  modB
   \/
  main_mod

I find this is a pretty common pattern for me --
there are some utilities that I write to use throughout
my code, so I put them in one module (or sub-package),
usually named "utility" or "constants" which are
imported by all modules, and then there's usually a
top or "main" module which drives everything else.

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Q's: pythonD and range(1,12)

2006-03-13 Thread Scott David Daniels
John Savage wrote:
> Could someone please explain the rationale behind python designers' thinking
> in deciding the function "range(1,12)" should return the sequence 1 to
> 11 rather than the more intuitively-useful 1 to 12??
Essentially, it has to do with the decision to have range(5) mean the
list [0, 1, 2, 3, 4] (which is five elements long).  Any choice will
please some and offend others; this one in Python has no chance of
changing.

> After downloading the substantial distribution .zip file, I'm intrigued
> to find it includes 3 files of identical size and creation date, differing
> apparently only in name (python, python2.4 and python24.exe) and each of
> exactly 2,597,888 bytes. What possible purpose could be served by such
> triplication that couldn't more efficiently be done by other means?

You obviously know what and where PythonD came from, but we don't.


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


global namescape of multilevel hierarchy

2006-03-13 Thread Sakcee
Hi

I have a script e.g.

import package.module

ID = "55"

package.module.checkID()



now in package.module.checkID function, i wnat to know what is the ID
defiend in the calling scriipt


if I dot globals(), it returns only items in module.   is there a way
to get the script level namesapce


thanks

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


Re: anonymous memory mapping

2006-03-13 Thread Peter Hansen
Fabiano Sidler wrote:
> 2006/3/12, Fabiano Sidler <[EMAIL PROTECTED]>:
> 
>>Is there any way to use anonymous memory mapping in python, versions
>>earlier than 2.5?
> 
> No idea or no way to do it?

Often when there's no reply for a while, it's because the question is 
unclear.  Rather than just appending speculation about why it wasn't 
answered, consider rephrasing your request or expanding on it with 
examples, references to missing info about your platform (which might be 
essential), or at least mention where you've looked in the docs or on 
the web in an attempt to answer it yourself.  (For example, perhaps it's 
a really easy thing and everyone who knows the answer figures if you did 
the obvious Google search you'd find out yourself, so they can't be 
bothered answering.  Or perhaps if you show an example search and a 
stray comment about the useless results you found, you'd inspire someone 
else to try a variation and maybe they'll find the answer you need.)

(As for me, I have no idea what the question is about, so this is the 
most help I can give.)

-Peter

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


Q's: pythonD and range(1,12)

2006-03-13 Thread John Savage
I've very new to python, and am currently toying with pythonD. Could
someone please explain the rationale behind python designers' thinking
in deciding the function "range(1,12)" should return the sequence 1 to
11 rather than the more intuitively-useful 1 to 12??

After downloading the substantial distribution .zip file, I'm intrigued
to find it includes 3 files of identical size and creation date, differing
apparently only in name (python, python2.4 and python24.exe) and each of
exactly 2,597,888 bytes. What possible purpose could be served by such
triplication that couldn't more efficiently be done by other means?

Naive but curious minds wish to know!
--
John Savage   (my news address is not valid for email)

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


Re: time series calculation in list comprehension?

2006-03-13 Thread falcon
Wow, thanks for all the reponses.  Very helpful!

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


Re: lighter weight options to Python's logging package?

2006-03-13 Thread Vinay Sajip
> Trent> Do you have any profile information for where in the logging
> Trent> package the time is being spent?
>
> Looking back at a recent run from a few days ago Formatter.formatTime()
> seems to be a current problem.

As Kent suggested, don't use %(asctime)s if you don't want fancy time
formatting. If needed, you can use %(created)f and postprocess logs if
you want absolute times.

> We create our own LogRecord subclass.  Because that was such a heavyweight
> operation, instead of calling logging.LogRecord.__init__ from our class's
> constructor, I wound up inlining it and deleting the state it set that we
> never used.
>
> Trent> I don't know how much of a perf issue it is for you. Perhaps
> Trent> tweaking your usage of the logging package (perhaps using custom
> Trent> Loggers, Filters, outputters, etc.)  could be made "good enough".
>
> We've done a bit already.  I will see if there's more we can do.  Our use of
> the package is actually very simple.  All we do are log basic messages.  Our
> Formatter instance includes the time, level and message.  That's it.  We
> have no need for displaying exception info, don't do threads, don't mess
> with the file or module names, etc.  The only thing we do that isn't
> supported directly by the package is to use a compressing version of the
> RotatingFileHandler class.

If you set logging._srcfile to None, there's no walking of the stack
done by the logging package to get caller info such as line no, func
name, file name etc.

Exception info is only logged if you set exc_info to 1 in a logging
call, or if you use the exception(...) method or module-level function.

I've just checked in a change into Subversion which adds two module
variables, logThreads and logProcesses (both set to 1 to enable current
behaviour). If you don't want to log thread info, set logThreads to 0
in the svn trunk version. If you don't want os.getpid() called, set
logProcesses to 0 in this version.

To summarise: for the version in the svn trunk, setting _srcFile to
None and logThreads and logProcesses to 0, and avoiding %(asctime)s in
your Formatter specification, should remove a fair chunk of the
overhead.

Regards,

Vinay Sajip

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


Re: Localized month names?

2006-03-13 Thread Benji York
Jarek Zgoda wrote:
> How do I get a list of localized month names for current locale? The
> first thing that came to my mind was an ugly hack:

 >>> import locale
 >>> locale.nl_langinfo(locale.MON_1)
'January'

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


Re: trying to find repeated substrings with regular expression

2006-03-13 Thread johnzenger
Robert Dodier wrote:

> I've decided it's easier for me just to search for FOO, and then
> break up the string based on the locations of FOO.
>
> But I'd like to better understand regular expressions.

Those who cannot learn regular expressions are doomed to repeat string
searches.  Which is not such a bad thing.

txt = "blah FOO blah1a blah1b FOO blah2 FOO blah3a blah3b blah3b"

def fa(s, pat):
retlist = []
try:
while True:
i = s.rindex(pat)
retlist.insert(0,s[i:])
s = s[:i]
except:
return retlist

print fa(txt, "FOO")

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


Build issue on AIX 5.3 with python 2.4.2

2006-03-13 Thread ktelep
I'm trying to build python 2.4.2 on AIX 5.3 with the IBM xlC compiler
as per the notes in the AIX Readme file.  Basically my make fails with
the errors listed below.

I'm calling configure with:

./configure --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64"
--disable-ipv6 AR="ar -X64"

It looks like it's not resolving symbols in readline.  I originally
tried the RPMS IBM supplies for GNU readline, then tried compiling GNU
readline 5.1 myself, same errors with either version of the libraries.

Anyone run into this with AIX and resolved it?

Kurt

building 'readline' extension
xlc_r -q64 -DNDEBUG -O -I. -I/home/ktelep/Python-2.4.2/./Include
-I/usr/local/include -I/home/ktelep/Python-2.4.2/Include
-I/home/ktelep/Python-2.4.2 -c
/home/ktelep/Python-2.4.2/Modules/readline.c -o
build/temp.aix-5.3-2.4/readline.o
"/home/ktelep/Python-2.4.2/Modules/readline.c", line 675.34: 1506-068
(W) Operation between types "char**" and "int" is not allowed.
./Modules/ld_so_aix xlc_r -q64 -bI:Modules/python.exp
build/temp.aix-5.3-2.4/readline.o -L/usr/lib/termcap -L/usr/local/lib
-lreadline -lcurses -o build/lib.aix-5.3-2.4/readline.so
ld: 0711-317 ERROR: Undefined symbol: rl_instream
ld: 0711-317 ERROR: Undefined symbol: rl_outstream
ld: 0711-317 ERROR: Undefined symbol: .rl_prep_terminal
ld: 0711-317 ERROR: Undefined symbol: .history_get_history_state
ld: 0711-317 ERROR: Undefined symbol: .history_get
ld: 0711-317 ERROR: Undefined symbol: .add_history
ld: 0711-317 ERROR: Undefined symbol: rl_event_hook
ld: 0711-317 ERROR: Undefined symbol: .readline
ld: 0711-317 ERROR: Undefined symbol: .using_history
ld: 0711-317 ERROR: Undefined symbol: rl_readline_name
ld: 0711-317 ERROR: Undefined symbol: rl_insert
ld: 0711-317 ERROR: Undefined symbol: .rl_bind_key
ld: 0711-317 ERROR: Undefined symbol: rl_complete
ld: 0711-317 ERROR: Undefined symbol: emacs_meta_keymap
ld: 0711-317 ERROR: Undefined symbol: .rl_bind_key_in_map
ld: 0711-317 ERROR: Undefined symbol: rl_startup_hook
ld: 0711-317 ERROR: Undefined symbol: rl_attempted_completion_function
ld: 0711-317 ERROR: Undefined symbol:
rl_completer_word_break_characters
ld: 0711-317 ERROR: Undefined symbol: rl_completion_append_character
ld: 0711-317 ERROR: Undefined symbol: .rl_initialize
ld: 0711-317 ERROR: Undefined symbol: .completion_matches
ld: 0711-317 ERROR: Undefined symbol: rl_attempted_completion_over
ld: 0711-317 ERROR: Undefined symbol: .rl_redisplay
ld: 0711-317 ERROR: Undefined symbol: .rl_insert_text
ld: 0711-317 ERROR: Undefined symbol: .clear_history
ld: 0711-317 ERROR: Undefined symbol: rl_line_buffer
ld: 0711-317 ERROR: Undefined symbol: .replace_history_entry
ld: 0711-317 ERROR: Undefined symbol: .remove_history
ld: 0711-317 ERROR: Undefined symbol: .write_history
ld: 0711-317 ERROR: Undefined symbol: .history_truncate_file
ld: 0711-317 ERROR: Undefined symbol: .read_history
ld: 0711-317 ERROR: Undefined symbol: .rl_read_init_file
ld: 0711-317 ERROR: Undefined symbol: .rl_parse_and_bind
ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more
information.
*** WARNING: renaming "readline" since importing it failed: Could not
load module build/lib.aix-5.3-2.4.
System error: No such file or directory
error: No such file or directory
make: The error code from the last command is 1.


Stop.

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


Re: Localized month names?

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

> How do I get a list of localized month names for current locale? The
> first thing that came to my mind was an ugly hack:
>
> import datetime
> for i in range(12):
> # as I remember, all months in 2005 had 1st in days
> datetime.date(2005, i + 1, 1).strftime('%B')

doesn't look very ugly to me...

the strftime tables are hidden deep inside the C library, but I guess you
could use the _strptime implementation module to dig out the information
you're after:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "sv_SE")
'sv_SE'
>>> import _strptime
>>> vars(_strptime.LocaleTime())
{'lang': ('sv_SE', 'ISO8859-1'), 'am_pm': ['', ''], 'f_month': ['', 'januari',
'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 
'oktober',
'november', 'december'], 'LC_date': '%Y-%m-%d', 'a_weekday': ['m\xe5n',
'tis', 'ons', 'tor', 'fre', 'l\xf6r', 's\xf6n'], 'f_weekday': ['m\xe5ndag', 
'tisdag',
'onsdag', 'torsdag', 'fredag', 'l\xf6rdag', 's\xf6ndag'], 'LC_date_time':
'%a %d %b %Y %H.%M.%S', 'timezone': (frozenset(['utc', 'cet', 'gmt']),
frozenset(['cest'])), 'a_month': ['', 'jan', 'feb', 'mar', 'apr', 'maj', 'jun',
'jul', 'aug', 'sep', 'okt', 'nov', 'dec'], 'LC_time': '%H.%M.%S'}

(I'm pretty sure _strptime uses your ugly hack-approach to extract this
information from the C library...)

hope this helps!





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


Re: Python IDE: great headache....

2006-03-13 Thread Dag Fjeld Edvardsen
> What features exactly does it not have?
Come to think of it, the only exception is probably that PyScripter (AFAIK)
does not provide conditional pause.

But I really like it. PyScripter is written in Delphi, my other favorite
language :)

  -Dag


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


Re: Is this possible in Python?

2006-03-13 Thread Grant Edwards
On 2006-03-13, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Hello again,
> I am disappointed.

Yea, life's like that. 

Sucks, eh?

-- 
Grant Edwards   grante Yow!  ... The waitress's
  at   UNIFORM sheds TARTAR SAUCE
   visi.comlike an 8" by 10" GLOSSY...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Love :)

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

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


Localized month names?

2006-03-13 Thread Jarek Zgoda
How do I get a list of localized month names for current locale? The
first thing that came to my mind was an ugly hack:

import datetime
for i in range(12):
# as I remember, all months in 2005 had 1st in days
datetime.date(2005, i + 1, 1).strftime('%B')

but I am sure there is a better way...

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anomalous behaviour when compiling regular expressions?

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

> I agree to a certain extent, but by analogy
>
>  
> ]>
> 
>
> is a valid SGML/XML document and their is a lot of (superficial?)
> similarity between DTD content models and REs.

they're related, but they don't have the same semantics (Python uses
a backtracking engine, while the DTD model is a true DFA).





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


Re: Is this possible in Python?

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

> I don't want a better way, i just want a solution to the problem as
> described!

any special reason you cannot use Python to write Python programs,
instead of demanding that someone else wastes time inventing a non-
portable solution to a braindead problem?

what's wrong with you?





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


Re: list/classmethod problems

2006-03-13 Thread ahart
Diez, Scott, and Bruno,

I thank you all for your help and suggestions. I wasn't aware that
default values were considered class (static) values. That seems a
little odd to me, but as long as I know that's the case, I'll be fine.

I initialized my list member in the __init__() method and all is
working as it should now.

Again, I thank you all.

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


Re: "RuntimeError: dictionary changed ... & Ruby

2006-03-13 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, robert wrote:

> * Ruby without refcounts provides no deterministic __del__ in 
> non-circular refs ==> your type  finally finally finally .close .close 
> .close all the time

Which is what you should type in Python too as there's no guarantee that
`__del__()` will be called immidiatly when the file object goes out of
scope or isn't referenced anymore.  The reference counting memory
management is an implementation detail.

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


Re: Is this possible in Python?

2006-03-13 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> I don't want a better way, i just want a solution to the problem as
> described!

I once did something like:

  try:
 raise ValueError
  except ValueError, e:
pass

then get the traceback object out of e, and snarf the relevant source
line as mentioned before.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this possible in Python?

2006-03-13 Thread alainpoint
Hi Kent,
My intention is to be able to retrieve any line of code in a running
program, in the following way:
def magic_funct(s):
for line in file(s.gi_frame.f_code.co_filename):
print line
magic_funct(i for i in [1,2,3])

I just find it stupid to be obliged to use a generator expression, just
because it has got the gi_frame attribute. Such a kind of introspection
can be very useful.
I don't want a better way, i just want a solution to the problem as
described!

Alain

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


Re: Is this possible in Python?

2006-03-13 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> Hello again,
> I am disappointed. You are the experts, you've got to try harder ;-)
> What i want is a generalisation of this tiny function:

Why? Maybe we can find a better way...

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


Re: list/classmethod problems

2006-03-13 Thread Bruno Desthuilliers
ahart a écrit :
> I'm pretty new to python and am trying to write a fairly small
> application to learn more about the language. I'm noticing some
> unexpected behavior in using lists in some classes to hold child
> objects. Here is some abbreviated code to help me explain.
> 
> 
> class Item(object)
> __text = ""
> def __get_text(self):
> return self.__text
> def __set_text(self, value):
> self.__text = value
> text = property(fget=__get_text, fset=__set_text)


If you don't have any computation to do in the getter/setter, just use 
direct attribute access. If the need arise, then it will be time to use 
a property.

Also, takes care with leading double underscores, they may not do what 
you think. The usual convention is to use a single leading underscore 
for implementation details.

(snip)

> class Parent(object):
> __items = []

This is a class attribute. It will be shared by all instances.

(snip)

> The list appears to be acting as if it were a
> static member - which it is not.

Well, in Python it's called a class attribute, but that's pretty much 
the same thing.

> I do have some @classmethod methods in these classes in my complete
> script. Would that confuse the interpreter into thinking that other
> members are also static?

Don't you think such a bug would have been spotted a long time ago ?-)

If you come from Java, take the time to read this:
http://dirtsimple.org/2004/12/python-is-not-java.html

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


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

2006-03-13 Thread paron
Well, there's OpenLaszlo, which handles the sounds/animation for
http:www.pandora.com, I understand. It may be overkill for a desktop
app, but it's free. It was originally written in Python, I think, but
it uses ECMAScript for scripting.

It's free, and reportedly handles sounds and animations, and isn't too
hard to program.

Ron

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


Re: Why property works only for objects?

2006-03-13 Thread John J. Lee
Michal Kwiatkowski <[EMAIL PROTECTED]> writes:
[...]
> "Return a property attribute for new-style classes". After reading a bit
> about descriptors I've just assumed that property is a handy way to
> create (any) descriptors. Learning that it only creates overriding
> descriptors was a bit shocking. I'm not suggesting it's bad behavior,
> only that it seemed unexpected for an unaware programmer. What at first
> glance looked like a shortcut, turned out to be designed for a specific
> use case.
[...]

Python builtins (especially the newer ones, perhaps) are often
targetted fairly tightly on particular use cases.


John

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


Re: list/classmethod problems

2006-03-13 Thread Scott David Daniels
ahart wrote:
> I'm pretty new to python and am trying to write a fairly small
> application to learn more about the language. I'm noticing some
> unexpected behavior in using lists in some classes to hold child
> objects. Here is some abbreviated code to help me explain.
> 
> When I run this script, I expect to see the following string printed:
> 
> "onetwo"
> 
> Instead, I see the following:
> 
> 
> "onetwothree"
> 
> Apparently, the p1 instance somehow thinks that the i3 instance is in
> its list. The i3 instance should instead be in the list for p2. By the
> way, when I call the __str__() method of p2, I get the same results as
> when I do it for p1. The list appears to be acting as if it were a
> static member - which it is not.
> 
> I do have some @classmethod methods in these classes in my complete
> script. Would that confuse the interpreter into thinking that other
> members are also static?
> 
> I can't seem to find any information on this problem. Does anyone have
> any ideas?

First, a few kvetches:

(1) Submit the _actual_code_ when you have problems, not paraphrases:
 > class Item(object)
should have been (and probably was):
   class Item(object):

 > def __str__(self):
 > ...
 > s += ""
should have been (and probably was):
   def __str__(self):
   ...
   s += ""
   return s

(2) You must have been a Java or C++ programmer.  Don't be so stingy
 with access to your variables and methods (all the __xxx methods
 and variables).  Just use a single underscore (at least for the
 methods) telling users, "don't muck with this."  The double
 underscores make figuring out what's going interactively awkward.

(3) The if statement takes a boolean expression, not parens around a
 boolean expression.  "if a > b:" is the way to write a test, not
 "if(a>b):" (which is why I think Java or C++).

And now to your actual question:

 > 
 > class Item(object)
 > __text = ""

The line above is unnecessary (and deceptive).  It sets a _class_
variable named _Item__text to a zero-length string.

 > def __get_text(self):
 > return self.__text
 > def __set_text(self, value):
 > self.__text = value
 > text = property(fget=__get_text, fset=__set_text)
 >
 > def __init__(self, text=""):
 > self.__text = text
This line sets an _instance_ variable named _Item__text to the arg.
 >
 > #...some other methods here...
 >
 > class Parent(object):
 > __items = []
The line above is unnecessary (and deceptive).  You want
a list-per instance, but you are accessing the class variable below

 > def __get_items(self):
 > return self.__items
 > items = property(fget=__get_items)
 >
 > def addItem(self, item):
 > """Adds an Item object to the internal list."""
 >  self.__items.append(item)
 >
 > def __init__(self, items=[]):
 > if(len(items)>0):
 > for item in items:
 > self.addItem(item)

If you wrote this method as either:
   def __init__(self, items=[]):
   self.__items = []
   for item in items:
   self.addItem(item)
or:
   def __init__(self, items=[]):
   self.__items = list(items)

You would have the effect you want -- a list per instance.
By the way,
 > if(len(items)>0):
 > for item in items:
 > self.addItem(item)
Two complaints about this:
First, the "Pythonic way to test for a non-zero length list is "if var"
Second, even if the test were:
 > if items:
 > for item in items:
 > self.addItem(item)
That code is just plain slower (and less clear) than:
   for item in items:
   self.addItem(item)
If items is zero length, it goes through the loop body zero times.
 >
 > def __str__(self):
 > s = ""
 > for item in self.__items:
 > s += "%s" % item.text
 > s += ""
 >
 > #...some other methods here...
 >
 > if(__name__=="__main__"):
 > i1 = Item("one")
 > i2 = Item("two")
 > i3 = Item("three")
 >
 > p1 = Parent([i1, i2])
 > p2 = Parent([i3])
 >
 > print str(p1)
 > 
 >
Now you get the output you expect.

By-the-by, why shouldn't the first class be simply?:

class Item(object)
def __init__(self, text=""):
self.text = text

Finally, defining __repr__ rather than __str__ will make it
easier to fiddle with your code interactively w/o keeping anything
from working.

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


Re: Is this possible in Python?

2006-03-13 Thread alainpoint
Hello again,
I am disappointed. You are the experts, you've got to try harder ;-)
What i want is a generalisation of this tiny function:
import tokenize
import token
def magic_function(s):
readline = open(s.gi_frame.f_code.co_filename).readline
for t in
tokenize.generate_tokens(open(s.gi_frame.f_code.co_filename).readline):
t_type,t_string,(r_start,c_start),(r_end,c_end),line = t
if r_start == s.gi_frame.f_code.co_firstlineno:
if t_string=="magic_function":
args= line.split(t_string)
arg=args[1]
return arg
# returns its own argument !
print magic_function(i+2 for i in [1,2])

There ought to be a way to make it work for more than generator
expressions !!!

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


Re: anonymous memory mapping

2006-03-13 Thread Fabiano Sidler
2006/3/12, Fabiano Sidler <[EMAIL PROTECTED]>:
> Is there any way to use anonymous memory mapping in python, versions
> earlier than 2.5?

No idea or no way to do it?

Greetings,
F. Sidler
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter / Mac OS X Question (Aqua vs. X11)

2006-03-13 Thread Kevin Walzer
[EMAIL PROTECTED] wrote:
> I am running Mac OS X.  I have Tcl/Tk installed.  I can run the Aqua
> version (TkAqua) of wish by typing 'wish' at a terminal prompt.  I can
> run the X11 version (TkX11) of wish by typing 'wish8.4-X11' in an
> x-term.  If I run python and import Tkinter it always grabs the TkAqua
> version.  How can I get Tkinter to load the TkX11 version?
> 
> I want to be able to switch back and forth between the two at will.
> 
> Thanks
> David
> 

I don't think the version of Python that ships with OS X by default is
compatible with the X11 environment. For one thing, it is built with the
 "-framework" flag, which is how OS X packages libraries--this works
differently than on other *Nix environments. The Aqua version of Tcl/Tk
is also a framework build, and it's not compatible with the X11 version.
(The "wish8.4-x11" command is just a wrapper script that invokes a
completely different wish binary, linked against an entirely different
set of libraries.)

The advice to install Python and Tcl/Tk via Fink (or DarwinPorts) then
run your script against that is the right advice. It's a much cleaner
way to go.

-- 
Kevin Walzer
iReveal: File Search Tool
http://www.wordtech-software.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list/classmethod problems

2006-03-13 Thread Diez B. Roggisch
> 
> Apparently, the p1 instance somehow thinks that the i3 instance is in
> its list. The i3 instance should instead be in the list for p2. By the
> way, when I call the __str__() method of p2, I get the same results as
> when I do it for p1. The list appears to be acting as if it were a
> static member - which it is not.
> 
> I do have some @classmethod methods in these classes in my complete
> script. Would that confuse the interpreter into thinking that other
> members are also static?
> 
> I can't seem to find any information on this problem. Does anyone have
> any ideas?

Read this:

http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects

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


Re: Is it better to use class variables or pass parameters?

2006-03-13 Thread Derek Basch
Wow! Thanks everyone. Such coherent and philisophical answers. I will
read them all over on a lazy sunday as this type ethereal stuff hurts
my head after about 30 seconds. All the gurus on the python list are so
friggin' smart. This should improve my coding after I digest it all.
Thanks Again!

Derek Basch

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


Re: Python Love :)

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

Umm, 
Did you mean to write the above?
What has it to do with Ruby?

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


list/classmethod problems

2006-03-13 Thread ahart
I'm pretty new to python and am trying to write a fairly small
application to learn more about the language. I'm noticing some
unexpected behavior in using lists in some classes to hold child
objects. Here is some abbreviated code to help me explain.


class Item(object)
__text = ""
def __get_text(self):
return self.__text
def __set_text(self, value):
self.__text = value
text = property(fget=__get_text, fset=__set_text)

def __init__(self, text=""):
self.__text = text

#...some other methods here...

class Parent(object):
__items = []
def __get_items(self):
return self.__items
items = property(fget=__get_items)

def addItem(self, item):
"""Adds an Item object to the internal list."""
self.__items.append(item)

def __init__(self, items=[]):
if(len(items)>0):
for item in items:
self.addItem(item)

def __str__(self):
s = ""
for item in self.__items:
s += "%s" % item.text
s += ""

#...some other methods here...

if(__name__=="__main__"):
i1 = Item("one")
i2 = Item("two")
i3 = Item("three")

p1 = Parent([i1, i2])
p2 = Parent([i3])

print str(p1)


When I run this script, I expect to see the following string printed:

"onetwo"

Instead, I see the following:


"onetwothree"

Apparently, the p1 instance somehow thinks that the i3 instance is in
its list. The i3 instance should instead be in the list for p2. By the
way, when I call the __str__() method of p2, I get the same results as
when I do it for p1. The list appears to be acting as if it were a
static member - which it is not.

I do have some @classmethod methods in these classes in my complete
script. Would that confuse the interpreter into thinking that other
members are also static?

I can't seem to find any information on this problem. Does anyone have
any ideas?

Thank you.

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


Re: Very, Very Green Python User

2006-03-13 Thread Lonnie Princehouse
> Python closures are apparently very poor, but from what I can surmise
> of the PyGTK2 page, instances of objects are dynamic enough to add new
> methods, so you get your callbacks, at least.

It's true that Python's "lambda" is somewhat limited, but this is
rarely a problem because you can define named functions on-the-fly.

> Double-underscore methods are rewritten with the class name? That's an ugly 
> hack

Yes, it is.  But in practice, you will rarely need to pay attention to
this.  I'd been using Python for two years before I noticed this odd
behavior.

I heartily applaud shopping around for new languages.  Coming from
Perl, I think you'll find Python to be a figurative breath of fresh
air, but you might also want to look at languages like Ruby, Haskell,
etc.

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


Re: Which GUI toolkit is THE best?

2006-03-13 Thread ahart
i'm pretty much a newbie, too, and have been dabbling with some gui
tools

so far, i like pythoncard pretty well

it wraps wxpython and seems to be pretty easy to use

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


Re: Which GUI toolkit is THE best?

2006-03-13 Thread Paul Boddie
Paul Rubin wrote:
> "Paul Boddie" <[EMAIL PROTECTED]> writes:
> > What people don't usually understand (or rather complain about loudly)
> > is that Trolltech can refuse to license Qt to you under the commercial
> > licence, as is their right as the owner of the copyrighted work.
>
> What is the deal here?  Why would they refuse, to someone willing to
> pay the commercial license fee?  They are a business, and as such,

Well, I can't answer for them in any sense (and I should ask you to
substitute any company with a similar business model for Trolltech in
the text, along with accompanying product names, in order to emphasize
the mere speculative nature of my explanation), but all I was trying to
do was to explain the pattern of behaviour that goes something like
this:

 1. Developer downloads Qt GPL edition.
 2. Developer develops product based on Qt.
 3. Some time later, with finished product, developer now wants
to release a closed source version of the product.
 4. Developer approaches Trolltech and asks for a commercial
licence in order to ship a closed source product.

Now, since the commercial licence is "per developer", some cunning
outfit could claim that only one developer wrote their product (rather
than one hundred developers, say), but this would be a fairly big
breach of trust (although nothing unusual in the world of commerce, I'm
sure). Would a business making software for other such businesses care
about such things? What kind of recourse would they have?

> they presumably like gettng money.  And someone wanting to develop a
> proprietary app with Qt that users have to pay for, shouldn't mind
> paying Trolltech for the commercial Qt license.

It's the "after the fact" switching from GPL to commercial licensing,
rather than the up-front "wanting to develop" scenario, that would be
difficult for anyone issuing commercial licences to monitor. Trolltech
specifically mention "exposure to the GPL" on their "open source
downloads" page presumably (and again I speculate, so beware!) to
suggest that if you want to end commercial, you need to start
commercial:

http://www.trolltech.com/download/opensource.html

I don't see why anyone planning to make big bucks on proprietary
software can't shell out for the technology which would make their
success possible, either. But anyway, the key part of my explanation
was that the copyright holder can always refuse to license their work
to you. Obviously, if they've already licensed it to you under the GPL,
you'll always have that kind of permission.

Paul

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


Re: Python Love :)

2006-03-13 Thread gregarican
Paul Rubin wrote:

> Darn, yes, that's the second time in the past couple weeks I've made
> that exact same error in a clpy post.  So what's the most concise way
> of turning it back into a string?  ''.join(list(reversed(a_string))) ?
> Bleccch. 

Use Ruby:

print "A String".reverse

Just kidding :-)~

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


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

2006-03-13 Thread paron
Since you are comfortable with HTML, you could use the browser as your
GUI, and use a lightweight python server like Karrigell (or CherryPy,
or Turbogears) to serve the pages. A little javascript to move the
highlighting around, and . . .

Well, frankly, it's still harder than it ought to be. (I agree with
Steven, it sure seems like it has been long enough.) It's not totally
dreadful, though, and it is free.

Ron

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


Re: No more then 1 Instance of Application..

2006-03-13 Thread Grant Edwards
On 2006-03-13, Math <[EMAIL PROTECTED]> wrote:

> Does anybody know what I have to do to run only 1 instance of
> my Python Application?

Yes.

http://www.google.com/search?hl=en&q=python+single+application+instance

On Unix, one creates a lock file.  Typically
/var/run/.pid if you want a single system-wide
instance.

-- 
Grant Edwards   grante Yow!  They
  at   collapsed... like nuns
   visi.comin the street... they had
   no teenappeal!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to find repeated substrings with regular expression

2006-03-13 Thread Giovanni Bajo
Robert Dodier wrote:

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

> [...]

> Can someone suggest a regular expression which will return
> groups corresponding to the FOO substrings above?

FOO.*?(?=(?:FOO|$))
-- 
Giovanni Bajo


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


Re: Python Love :)

2006-03-13 Thread Kent Johnson
Paul Rubin wrote:
> So what's the most concise way
> of turning it back into a string?  ''.join(list(reversed(a_string))) ?

You don't need the list(), join() can take an iterator:

''.join(reversed(a_string))

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


Re: doctest-alike for a unix shell?

2006-03-13 Thread JW
1. Try os.popen:

>>> import os
>>> os.popen('echo Hello World').read()
'Hello World\n'

2. Try a test environment built for testing shell commands, such as
DejaGnu:
http://www.gnu.org/software/dejagnu/

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


Re: Tkinter / Mac OS X Question (Aqua vs. X11)

2006-03-13 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
>> Install python using fink, and invoke that. Should work against X11 for
>> all GUI-Toolkits.
> 
> I prefer not to do this.  Darwin is already a Unix, and Apple provides
> a version of X11 that works well with it. 
>  Fink seems like an
> unecessary layer that I would rather not mess with.  Tcl/Tk has a very
> simple way to select.  It would be nice if Python did something similar
> (command line option, an environment variable, whatever).

Fink works precisely _because_ OS X is a unix & has a X11 server. It is 
no "layer", it is just precompiled package management for unix-software 
running under OS X.

 >  I looked for
 > an option in the build process, and from what I can tell, the OS X
 > version looks like it only builds a single version (TkAqua).
> TkAqua and TkX11 do differ, and it would be nice to see the same script
> run under both Aqua and X11 without having to switch machines.

You might be able to tamper with the build process - but I have no idea 
how to do so.

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


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

2006-03-13 Thread Terry Reedy

"robert" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Though mostly ignorant of threading issues, I wonder if the following would 
work.  Derive a class from dict.  Define a backup method that sets and 
unsets a private self.lock.  Define setitem and delitem methods that wrap 
calls to the real methods with while self.lock: sleep(1 second).

tjr



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


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

2006-03-13 Thread bruno at modulix
Martin P. Hellwig wrote:
> While I was reading PEP 8 I came across this part:
> 
> """
> Function and method arguments
>Always use 'self' for the first argument to instance methods.
>Always use 'cls' for the first argument to class methods.
> """
> 
> Now I'm rather new to programming and unfamiliar to some basic concepts
> of OOP. However I wrote most of my classes in the new style way and by
> this I have always used 'self' for the first argument of an Instance
> method, but now I'm unsure what actually the difference is between an
> instance and a class method is and when to use it in which case.

As you noticed, an instance method gets an instance as the first
parameter (usually named 'self'), and does something with this instance.
A class method doesn't takes the instance as first parameter, but the
class itself, and does something with the class (NB: in Python, classes
are objects too...).

Note that, as well as class methods, there are class variables (see
below for an example).

> Could somebody please enlighten me (a rtfm/wrong newsgroup is just as
> welcome of course),

No problem, you're at the right place.

> preferably in a short code example?

A stupid exemple that won't teach you much about the usefulness of class
methods :

class Foo(object):
  # a class variable:
  _number_of_foos = 0

  # a class method
  @classmethod
  def increase_foo_counter(cls):
 cls._number_of_foos +=1

  # another class method
  @classmethod
  def decrease_foo_counter(cls):
 cls._number_of_foos -=1

  # and a third one
  @classmethod
  def get_foos_count(cls):
return cls._number_of_foos

  # instance methods
  def __init__(self):
self.increase_foo_counter()
print "now we have %d foos" % self.get_foos_count()

  def __del__(self):
self.decrease_foo_counter()
print "now we have %d foos" % self.get_foos_count()

foos = [Foo() for i in range(10)]
print "how many foos ? %d " % Foo.get_foos_count()
del foos


Note that a class method can be called on the class itself or on any of
it's instances - it'll still get the class as first param.


FWIW, you won't probably need class methods before you get much more
familiar with OO. Not that they are an advanced topic by themselves, but
their usefulness appears mostly in heavyly OO designs.

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


Re: Python IDE: great headache....

2006-03-13 Thread Caleb Hattingh
Hi

Being a Delphi user at work, I know what you mean :)

The best python IDE I have found is Stani's Python Editor (SPE), and I 
think Stani himself replied to your message as well.

It integrates wxGlade, which is nice for form-building, although I don't 
really do much of that with the python code I write.

My only gripe with SPE is that the memory usage, while SPE is running, 
slowly climbs and climbs, and after several hours that python thread 
running SPE is using several hundred megabytes of RAM.  I usually just 
restart it.   It seems as if the effect is pronouced when running code 
in the IDE.

Other than that, I now use SPE instead of Vim for python editing, which 
is a big step for me.  SPE is quite slick; some ways to go, but 
certainly on the right track.   The built-in code-completion is a godsend.

Hope this helps
Caleb

Sullivan WxPyQtKinter wrote:
> IDLE is no longer satisfactory for me. Other IDEs make me very
> confused. Really do not know which one to use.
> 
> I use WinXP sp2 for current development.
> 
> So far as I know, Eclipse + PyDev + PyDev Extension is perfect for
> source code editing. Since I am really not sure how to use the debugger
> module, I really do not know how to add watch to variables etc. Anyone
> knows if this platform is a good one?
> 
> I hope that an IDE should be featured with:
> 1. Grammar Colored highlights.
> 2. Manage project in a tree view or something alike, ie, a project file
> navigator.
> 3. Code collapse and folding.
> 4. Code auto-completion: especially prompting function parameters when
> I am typing a function previously defined by myself. Like the one in
> Visual Studio series.
> 5. Debugging: Breakpoints, conditional pause. watch for variables.step
> into, over and out of a function.
> What about other IDEs? Since I do not need GUI development. More over,
> the free-of-charge IDE is highly preferred.
> 6.Indentation management like in IDLE: press ctrl+[/] to modify the
> identation of a line or a block.
> 
> In addition, I have seen quite a few editors, which are definitely not
> what I want. 
> 
> Thank you so much for suggestions.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Love :)

2006-03-13 Thread Paul Rubin
Peter Otten <[EMAIL PROTECTED]> writes:
> >>> print reversed("abba")
> 

Darn, yes, that's the second time in the past couple weeks I've made
that exact same error in a clpy post.  So what's the most concise way
of turning it back into a string?  ''.join(list(reversed(a_string))) ?
Bleccch.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No more then 1 Instance of Application..

2006-03-13 Thread Christoph Haas
On Monday 13 March 2006 18:31, Math wrote:
> Does anybody know what I have to do to run only 1 instance of my Python
> Application?
> How do I check if I'm running more instances of a Application?

I would use lockfiles for that purpose. Like this:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/193488

I'm surprised that this is not in the standard library.

If you are not familiar with lockfiles: 
http://en.wikipedia.org/wiki/File_locking

Kindly
 Christoph
-- 
~
~
".signature" [Modified] 1 line --100%--1,48 All
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to find repeated substrings with regular expression

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

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


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

Use re.split() for this.

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


Re: Which GUI toolkit is THE best?

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

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

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


Re: Python Love :)

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

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

Needs a little help, though:

>>> print reversed("abba")


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

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

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


No more then 1 Instance of Application..

2006-03-13 Thread Math
Hello,

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

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


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

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

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

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


Re: IOS-style command line interface module?

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

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

Thanks again,


David.

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


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

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

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

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

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

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

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


Re: suse linux 10 and wx.listctrl display issues

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

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


Re: Which GUI toolkit is THE best?

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

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


Re: Is this possible in Python?

2006-03-13 Thread Caleb Hattingh
Hi

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

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

fun(8+7)

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

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



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


Re: Is this possible in Python?

2006-03-13 Thread Terry Reedy

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

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

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

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

Terry Jan Reedy



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


Re: Which GUI toolkit is THE best?

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

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

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

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

Paul

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


Re: Environmental Variables

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

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

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

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

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


Re: Python Love :)

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

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


Re: Python Love :)

2006-03-13 Thread gregarican
Paul Rubin wrote:

> reversed(a_string) (python)

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

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


trying to find repeated substrings with regular expression

2006-03-13 Thread Robert Dodier
Hello all,

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

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

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

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

Thanks for any insights, I appreciate it a lot.

Robert Dodier

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


Re: Python Love :)

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

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


Re: Is this possible in Python?

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

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

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

(defmacro magic (arg) arg)

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


Re: Is this possible in Python?

2006-03-13 Thread alainpoint

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

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

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

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

Alain

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


Re: Python Love :)

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

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

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

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


Re: IOS-style command line interface module?

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

sh tech

instead of:

show tech-support
?

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


Announcing edupython list

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

  1   2   >