Re: NEWB: General purpose list iteration?

2005-08-12 Thread Peter Otten
Donald Newcomb wrote:

> I was wondering it there's a simple routine (I
> think I can write a recurisve routine to do this.) to scan all the
> elements of a list, descending to lowest level and change something. What
> I'd like to do today is to convert everything from string to float. So, if
> I had a list of lists that looked like:
> [['1.1', '1.2', '1.3'], [['2.1', '2.2'], [['3.1', '3.2'], ['4.1',
> [['4.2'
> and I'd like it to be:
> [[1.1, 1.2, 1.3], [[2.1, 2.2], [[3.1, 3,2], [4.1, 4.2
> is there just a library routine I can call to do this? Right now, I'm
> using 'for' loops nested to the maximum depth anticipated.

A non-recursive approach:

def enumerate_ex(items):
stack = [(enumerate(items), items)]
while stack:
en, seq = stack[-1]
for index, item in en:
if isinstance(item, list):
stack.append((enumerate(item), item))
break
yield index, seq[index], seq
else:
stack.pop()


data = [['1.1', '1.2', '1.3'], [['2.1', '2.2'], [['3.1', '3.2'], ['4.1',
'4.2'

for index, value, items in enumerate_ex(data):
items[index] = float(value)

# Now let's test the algorithm and our luck with float comparisons
assert data == [[1.1, 1.2, 1.3], [[2.1, 2.2], [[3.1, 3.2], [4.1, 4.2

Peter

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


Re: Where can be a problem?

2005-08-12 Thread Peter Otten
Lad wrote:

> I use the following
> ###
> import re
> Results=[]
> data1=' href="detailaspxmember=15016&mode=advert"  href="detailaspxmember=15017&mode=advert" '
> ID = re.compile(r'^.*=(\d+)&.*$',re.MULTILINE)
> Results=re.findall(ID,data1)
> print Results
> #
> to extract from data1 all numbers such as 15015,15016,15017
> 
> But the program extracts only the last number 15017.
> Why?
> Thank you for help
> La.

After changing 

data = '...
'

to 

data = '''...
'''

I get all three numbers. There is probably another significant difference
between the posted code and the code you are actually running.

Peter

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


Cheese shop (was Re: python2.4/site-packages)

2005-08-12 Thread Michael Hoffman
Lucas Raab wrote:
> Michael Hoffman wrote:
>> http://www.python.org/pypi
>>
>> This used to be called the Python Package index but is now the Python 
>> Cheese Shop? Huh???
> 
> You've never heard the Cheese Shop Sketch by Monty Python??

I have but I've never heard of PyPI's name being changed? I can only 
find an announcement on Slashdot?
-- 
Michael Hoffman

P.S. Would you like another question mark for good measure???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: net view /domain

2005-08-12 Thread usenet
Hi Tim!

Thanks again for your help!

I just tried it out and it does exactly what I want it to do :-)

Have a nice day!
Dirk

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


Re: Why does __init__ not get called?

2005-08-12 Thread Fuzzyman
If you subclass strings you have to do your magic in __new__ rather
than __init__. It receives the same arguments as you would normally
expect to go to __init__.

(Except cls rather than self).

Best Regards,

Fuzzy
http://www.voidspace.org.uk/python

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


Re: Cheese shop (was Re: python2.4/site-packages)

2005-08-12 Thread Erik Max Francis
Michael Hoffman wrote:

> I have but I've never heard of PyPI's name being changed? I can only 
> find an announcement on Slashdot?

I came across the change a good while back in my Web referrals, not 
having heard of it except passively.  PyPI was a simple, clear, 
unambiguous name; Cheese Shop is just a silly name for no purpose.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   We learn from history that we do not learn from history.
   -- Georg Friedrich Wilhelm Hegel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expression to match a #

2005-08-12 Thread Duncan Booth
John Machin wrote:

> The point was made in a context where the OP appeared to be reading a 
> line at a time and parsing it, and re.compile(r'something').match() 
> would do the job; re.compile(r'^something').search() will do the job too 
> -- BECAUSE ^ means start of line anchor -- but somewhat redundantly, and 
> very inefficiently in the failing case with dopey implementations of 
> search() (which apply match() at offsets 0, 1, 2, .).

Answering the question you think should have been asked rather than the 
question which was actually asked is a great newsnet tradition, and often 
more helpful to the poster than a straight answer would have been. However, 
you do have to be careful to make it clear that is what you are doing.

The OP did not use the word 'line' once in his post. He simply said he was 
searching a string. You didn't use the word 'line' either. If you are going 
to read more into the question than was actually asked, please try to say 
what question it is you are actually answering.

If he is using individual lines and re.match then the presence or absence 
of a leading ^ makes virtually no difference. If he is looking for all 
occurences in a multiline string then re.search with an anchored match is a 
correct way to do it (splitting the string into lines and using re.match is 
an alternative which may or may not be appropriate).

Either way, putting the focus on the ^ was inappropriate: the issue is 
whether to use re.search or re.match. If you assume that the search fails 
on an 80 character line, then I get timings of 6.48uS (re.search), 4.68uS 
(re.match with ^), 4.66uS (re.match without ^). A failing search on a 
10,000 character line shows how performance will degrade (225uS for search, 
no change for match), but notice that searching 1 10,000 character string 
is more than twice as fast as matching 125 80 character lines.

I don't understand what you think an implementation of search() can do in 
this case apart from trying for a match at offsets 0, 1, 2, ...? It could 
find a match at any starting offset within the string, so it must scan the 
string in some form. A clever regex implementation will use Boyer-Moore 
where it can to avoid checking every index in the string, but for the 
pattern I suggested it would suprise me if any implementations actually 
manage much of an optimisation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expression to match a #

2005-08-12 Thread Duncan Booth
John Machin wrote:

>> Your wording makes it hard to distinguish what exactly is "dopey".
>> 
> 
> """
> dopey implementations of search() (which apply match() at offsets 0, 1, 
> 2, .).
> """
> 
> The "dopiness" is that the ^ operator means that the pattern cannot 
> possibly match starting at 1, 2, 3, etc but a non-optimised search will 
> not recognise that and will try all possibilities, so the failing case 
> takes time dependant on the length of the string.

The ^ operator can match at any position in the string if the preceding 
character was a newline. 'Dopey' would be failing to take this into 
account.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using globals with classes

2005-08-12 Thread Diez B. Roggisch

> Is there a way to make a Python function "remember" the values of certain
> variables ? Or use fortran 95 like use module, only : varname, type of
> within a def ?

I'm not sure what you are trying to do here - but it seems to me that
you are not properly designing your application. You really shouldn't
use the Designers code-insertion features. The reason is simple: you
the have two tools to write code in instead of one (your editor/IDE).
And you don't make plotkey* global - use instance variables.

 So I'm going to describe how I dow work with PyQt:

- I create a Widget in the designer
- compile it using pyuic
- _extend_ it
- write my code in the extended version

So I end up with something like this (I use modules to separate
classes):

ui/plot.ui
ui/plot.py
views/plot.py

where views/plot.py looks like this:

class Plot(ui.plot.Plot):
def __init__(self, *args):
 ui.plot.Plot.__init__(self, *args)
 self.plotkey1 = 

def update(self):
 # access self.plotkey here
   


HTH,

DIez

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


Re: Using globals with classes

2005-08-12 Thread Diez B. Roggisch

> Is there a way to make a Python function "remember" the values of certain
> variables ? Or use fortran 95 like use module, only : varname, type of
> within a def ?

I'm not sure what you are trying to do here - but it seems to me that
you are not properly designing your application. You really shouldn't
use the Designers code-insertion features. The reason is simple: you
the have two tools to write code in instead of one (your editor/IDE).
And you don't make plotkey* global - use instance variables.

 So I'm going to describe how I dow work with PyQt:

- I create a Widget in the designer
- compile it using pyuic
- _extend_ it
- write my code in the extended version

So I end up with something like this (I use modules to separate
classes):

ui/plot.ui
ui/plot.py
views/plot.py

where views/plot.py looks like this:

class Plot(ui.plot.Plot):
def __init__(self, *args):
 ui.plot.Plot.__init__(self, *args)
 self.plotkey1 = 

def update(self):
 # access self.plotkey here
   


HTH,

DIez

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


Re: Why is this?

2005-08-12 Thread Matt Hammond
On Fri, 12 Aug 2005 00:10:08 +0100, John Hazen <[EMAIL PROTECTED]> wrote:

>>  [[], []] is [[]]*2
>> > True
>
> Just curious, did you actually cut and paste this from a real
> interactive session?  (I think not.)  My interpreter (yes, I know it's
> old) gives:

Ooops - you're absolutely right. I was cutting and pasting, but it seems I  
was a little overzealous with my editing!

I've still got that in my terminal's history buffer, and it does indeed  
read:

>>> [[], []] is [[]]*2
False




-- 

| Matt Hammond
| R&D Engineer, BBC Research and Development, Tadworth, Surrey, UK.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do these Java concepts translate to Python?

2005-08-12 Thread bruno modulix
Ray wrote:
> Hello,
> 
> I've been learning Python in my sparetime. I'm a Java/C++ programmer by
> trade. So I've been reading about Python OO, and I have a few questions
> that I haven't found the answers for :)
> 
> 1. Where are the access specifiers? (public, protected, private)

object.name => public
object._name => protected
object.__name => private

> 2. How does Python know whether a class is new style or old style?
> E.g.:
> 
> class A:
> pass

This is an old-style class.

> How does it know whether the class is new style or old style? Or this
> decision only happens when I've added something that belongs to new
> style? How do I tell Python which one I want to use?

class B(object): # or any subclass of object
  pass

> 3. In Java we have static (class) method and instance members. But this
> difference seems to blur in Python. I mean, when you bind a member
> variable in Python, is it static, or instance? 

Depends if you bind it to the class or to the instance !-)

> It seems that everything
> is static (in the Java sense) in Python. Am I correct?

No.

class Foo(object):
  bar = 42 # this is a class variable

  # __init__ is the equivalent of Java constructors
  def __init__(self, baaz):
self.baaz = baaz # this is an instance variable

  # this is a class method
  # (the first argument is the class object, not the instance)
  @classmethod
  def bak(cls, frooz):
cls.bar = min(cls.bar, frooz) + 1138

  # default is instance method
  def zoor(self):
print "%s %d" % (self.baaz, Foo.bar)

> Thanks in advance,

HTH



-- 
bruno desthuilliers
ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p|
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')"
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: How do these Java concepts translate to Python?

2005-08-12 Thread bruno modulix
Devan L wrote:
> Fausto Arinos Barbuto wrote:
> 
>>Ray wrote:
>>
>>
>>>1. Where are the access specifiers? (public, protected, private)
>>
>>AFAIK, there is not such a thing in Python.
>>
>>---Fausto
> 
> 
> Well, technically you can use _attribute to mangle it, 

__attribute would work better !-)

> but technically
> speaking, there are no public, protected, or private things.

Yes there are:
object.name is public
object._name is protected
object.__name is private

You don't need the language to enforce this, it's just a matter of
conventions.


-- 
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


win32com: use not possible as normal user

2005-08-12 Thread Sibylle Koczian
Hello,

I've installed Python 2.4 and the win32 extensions, using administrator 
rights, under Windows XP in "C:\Programme". As this is a directory 
without spaces I didn't expect any problems. But now I can't _use_ 
win32com as a normal user, because normal users can't write there:

PythonWin 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] 
on win32.
Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED]) - 
see 'Help/About PythonWin' for further copyright information.
 >>> import win32com.client
...
 >>> import wdclass
 >>> kal = wdclass.easyWord()
Traceback (most recent call last):
   File "", line 1, in ?
   File "h:\eigene dateien\abt\kalender\wdclass.py", line 10, in __init__
 self.wdApp = win32com.client.Dispatch('Word.Application')
   File 
"C:\Programme\Python24\Lib\site-packages\win32com\client\__init__.py", 
line 96, in Dispatch
 return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, 
UnicodeToString, clsctx)
   File 
"C:\Programme\Python24\Lib\site-packages\win32com\client\__init__.py", 
line 38, in __WrapDispatch
 klass = gencache.GetClassForCLSID(resultCLSID)
   File 
"C:\Programme\Python24\Lib\site-packages\win32com\client\gencache.py", 
line 179, in GetClassForCLSID
 mod = GetModuleForCLSID(clsid)
   File 
"C:\Programme\Python24\Lib\site-packages\win32com\client\gencache.py", 
line 222, in GetModuleForCLSID
 mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
   File 
"C:\Programme\Python24\Lib\site-packages\win32com\client\gencache.py", 
line 262, in GetModuleForTypelib
 AddModuleToCache(typelibCLSID, lcid, major, minor)
   File 
"C:\Programme\Python24\Lib\site-packages\win32com\client\gencache.py", 
line 575, in AddModuleToCache
 _SaveDicts()
   File 
"C:\Programme\Python24\Lib\site-packages\win32com\client\gencache.py", 
line 64, in _SaveDicts
 f = open(os.path.join(GetGeneratePath(), "dicts.dat"), "wb")
IOError: [Errno 13] Permission denied: 
'C:\\Programme\\Python24\\lib\\site-packages\\win32com\\gen_py\\dicts.dat'
 >>>

Do I have to move my Python installation to another directory with write 
permissions for normal users? Or is there a simpler way? This might not 
be a problem for users with english Windows installations who can get 
bitten anyway by the space in "program files". But in my german 
installation I never had a reason to install Python outside of "Programme".

Thanks for any help,
Koczian
-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spreadsheet with Python scripting and database interface?

2005-08-12 Thread Wolfgang Keller
Hello,

and thanks for your reply.

> One thing that's not clear from your question is whether you want to
> script the office from within using a macro or from the outside via
> "remote control".

What I basically dream of is using Python as THE embedded macro 
language of the spreadsheet.

Because Postgres already supports Python as a trigger/procedure 
language, so I can stick with one single tool (to learn and use).

> PyUNO allows both, but Python macros are only possible
> with the OpenOffice 2 scripting framework.

Sincerely,

Wolfgang Keller


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


Re: How do these Java concepts translate to Python?

2005-08-12 Thread bruno modulix
Ray wrote:
> Fausto Arinos Barbuto wrote:
> 
>>Ray wrote:
>>
>>
>>>1. Where are the access specifiers? (public, protected, private)
>>
>>AFAIK, there is not such a thing in Python.
> 
> 
> So everything is public? I know that you can prefix a member with
> underscores to make something private, 

The "2 leadings underscore name mangling" scheme is intented to protect
"sensible" attributes from being accidentally overriden by derived
classes, not to prevent access to the attribute.

class Foo(object):
  def __init__(self):
self.__baaz = 42

f = Foo()
print f._Foo__baaz

> but how about protected, for
> example?

object._protected_attribute is enough to tell anyone not to mess with
this attribute. Believe it or else, but this happens to work perfectly.

And BTW, don't bother making all your attributes "protected" or
"private" then writing getters and setters, Python has a good support
for computed attributes, so you can change the implementation without
problem (which is the original reason for not-public attributes):

# first version:
class Foo(object):
  def __init__(self):
 self.baaz = 42 # public attribute

# later we discover that we want Foo.baaz to be computed:
class Foo(object):
  def __init__(self):
 self.baaz = 42

  def _set_baaz(self, value):
 if value < 21 or value > 84:
raise ValueError, "baaz value must be in range 21..84"
 self._baaz = value

  def _get_baaz(self):
  return self._baaz * 2

  baaz = property(fget=_get_baaz, fset=_set_baaz)

Easy as pie, uh ?-)


-- 
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: Psyco & Linux

2005-08-12 Thread Jeremy Sanders
Fausto Arinos Barbuto wrote:

> The specifics of my system are:
> 
> Athlon AMD-64 3300+
> SuSE 9.3 Professional (64-bit)
> Python 2.4
> gcc/g++ 3.3.5

Ummm... I thought psyco only supported 32 bit systems. I haven't seen
anything else to suggest otherwise. See

http://psyco.sourceforge.net/psycoguide/req.html

Maybe you could recompile your python in 32 bit mode. You may find that
native 64 bit python is faster than 32 bit psyco however!

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are modules really for?

2005-08-12 Thread Tito
bruno modulix wrote:
> Magnus Lycka wrote:
> 
>>N.Davis wrote:
>>
>>
>>>Functions existing in a module? Surely if "everything is an object"
>>>(OK thats Java-talk but supposedly Python will eventually follow this
>>>too) 
>>
>>
>>int too? ;)
> 
> 
> Yes, int too.

I think he is talking about *Java* int.

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


__getattribute__ for class object

2005-08-12 Thread Sylvain Ferriol
hello
when i define __getattribute__ in a class, it is for the class instances
but if i want to have a __getattribute__ for class attributes

how can i do that ?

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


Re: What are modules really for?

2005-08-12 Thread Magnus Lycka
bruno modulix wrote:
> Magnus Lycka wrote:
> 
>>N.Davis wrote:
>>
>>
>>>Functions existing in a module? Surely if "everything is an object"
>>>(OK thats Java-talk but supposedly Python will eventually follow this
>>>too) 
>>
>>
>>int too? ;)
> 
> 
> Yes, int too.

I was talking about everything being an object in Java...

Java has an Integer class which is OO and an int type
which is usable from a performance point of view. At
least that distinction existed when I was looking at
Java.

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


Re: What are modules really for?

2005-08-12 Thread Magnus Lycka
Terry Reedy wrote:
> However, everything is an instance of a class or type.

Except whitespace, comments, operators and statements!
(Did I miss anything?)

You can obviously argue whether a "variable" (or name if
you like) is an object, or just refers to an object, but
then we're getting philosophical I guess. C.f.
http://www.comviz.com.ulaval.ca/module1/Images/MagrittePipe.jpg
or http://www.fredosaurus.com/notes-cpp/arrayptr/60song.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to quit a Windows GUI program gracefully with Python under Cygwin?

2005-08-12 Thread KB
Thanks.

After I confirmed 'Alt-F4' would terminate and close a win32
application running independently,
I installed 'SendKeys' module and tested with the following code under
both Cygwin and Python Windows

import os, SendKeys
os.system('program datafile')
SendKeys.SendKeys("""
{PAUSE 0.25}
%{F4}
""")

What happened was that the 'program' ran correctly, but it stayed, not
closing the window
under Cygwin and Python Windows.  So it seems to me that this does not
work.

One more thing: How do I control the pause time if I do not know the
execution
time of an application?

Thanks in advance.

KB

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


Re: How to Adding Functionality to a Class by metaclass(not by inherit)

2005-08-12 Thread Paolino
Dont' know where are you going with that but if what you need is 
cancelling some attributes when inheriting then probably this is a 
cleaner approach:

class Meta(type):
   def __init__(cls, name, bases, dic):
 def attributeError(*_):
   raise AttributeError
 for base in bases:
   for dont in base.privates:
 setattr(cls,dont,attributeError) #override private methods

class Foo(object):
   privates=('f',)
   def f(self):
 pass
   def g(self):
 pass

class Bar(Foo):
   __metaclass__ = Meta

b=Bar()
b.g()
b.f()

and it implies writing only one metaclass.






___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattribute__ for class object

2005-08-12 Thread Paolino
Sylvain Ferriol wrote:
> hello
> when i define __getattribute__ in a class, it is for the class instances
> but if i want to have a __getattribute__ for class attributes
> 
> how can i do that ?
> 

Skating on thin ice eh.Read something on metaclasses.


class Meta(type):
   def __getattribute__(klass,attr):
 value=type.__getattribute__(klass,attr)
 print attr,'==',value
 return value

class Foo(object):
   __metaclass__=Meta
   a=2

Foo.a

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


pywin32 from network install

2005-08-12 Thread agostino . russo
I managed to make pywin32 work from a network installation (not really
hard work: a shared folder + copying some dlls + setting PYTHONPATH).
PythonWin amd COM seem to be working fine from the network install, BUT
when I need to pass PyTime to a COM object expecting a Date I get the
following error:

Python24\Lib\site-packages\win32com\client\dynamic.py", line 251, in
_ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType,
argTypes) + args)
TypeError: Objects of type 'time' can not be converted to a COM VARIANT

Note 1: The same code works when using the local installation of
python/pywin, it only happens when executing the code from a network
"installation".

Note 2: As mentioned other COM components seem to be working when
running them via pywin from the network install

Note 3: I am passing pywintipes.Time(datetime.datetime.today()) to a
COM object method which expects a Date argument.

Do I need to change some environment variable/registry settings/other
hack to fix this?

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


Re: Help sorting a list by file extension

2005-08-12 Thread Tom Anderson
On Fri, 12 Aug 2005, Bengt Richter wrote:

> On Fri, 12 Aug 2005 00:06:17 GMT, Peter A. Schott <[EMAIL PROTECTED]> wrote:
>
>> Trying to operate on a list of files similar to this:
>>
>> test.1
>> test.2
>> test.3
>>
>> I want to sort them in numeric order instead of string order.
>
> >>> [name for dec,name in sorted((int(nm.rsplit('.',1)[1]),nm) for nm in 
> >>> namelist)]
> ['test.1', 'test.2', 'test.3', 'test.4', 'test.10', 'test.15', 'test.20']
>
> This depends on the extension being nicely splittable with a single '.'

You could use os.path.splitext to do that more robustly:

>>> [name for dec,name in sorted((int(os.path.splitext(nm)[1][1:]),nm) for nm 
>>> in namelist)]

tom

-- 
Everybody with a heart votes love
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Python?!

2005-08-12 Thread Magnus Lycka
Evil Bastard wrote:
  > I guess a language could be called a 'scripting language' if:
>  - the source code can be executed directly, and/or
>  - source need not be converted to a separate file in a
>non-human-readable format before it can be executed, and/or
>  - a change to the source file automatically causes a change in
>runtime behaviour

That kind of a language is typically called an interpreted
language, in contrast to a compiled. But it's really not an
aspect of the language, but rather of the tools being used
to convert the source code to "action" on a computer. I've
used both interpreted and compiled versions of Pascal and
BASIC, and I know of interpreted versions of C etc.

In a way, I guess Python's problem in achieving the popularity
it deserves is due to its versitility. Python works well as
an embedded macro language, and is used like that in both off
the shelf software and bespoke systems. It's useful as a scripting
language and is used in that way by NASA, ILM etc. It's also
very useful for building all sorts of software without mixing in
other languages or programs, and can replace VB, C++, COBOL, Java
or what have you. How do you sell this without making it sound
like snake oil? (Particularly with that name! :)

While other P-languages are used beyond their intended use, Perl
*is* basically a scripting language. The strong point of Perl is
that it's a "unified" replacement for a whole bunch of Unix tools.
PHP is for embedding functionality in web pages. Free cross
platform ASP. They explaining Python in two sentences!
-- 
http://mail.python.org/mailman/listinfo/python-list


how do i make exteranl module work under debug session?

2005-08-12 Thread Wen
Hi guys! I'm writing a small DLL thingy that requieres the use of loading 
the Python
interpreter and executing a series of scripts. I have generated an interface 
to my
dll with SWIG and put it in. It works like this:

1) a small .exe loads the .dll and calls the main init() function
2) the dll starts up some services, among them Py_Initialize ()
3) i tell python to execute: execfile("kikura.py") (kikura.py is the file 
that SWIG
generates for the shadow classes)

All this works in the release version, but in the debug version i get this 
error
message along with an assert failure: Fatal Python error: Interpreter not 
initialized
(version mismatch?)

Now, this might due to a fault of mine, but... The thing is that the windows
installer of python didn't come with debug libraries or .dll, so i 
downloaded the
python source, and compiled those, and am using those for the debug, but the 
original
instalation ones for release version.

Can anyone help? Thanx 


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


Re: pywin32 from network install

2005-08-12 Thread Neil Benn
[EMAIL PROTECTED] wrote:

>I managed to make pywin32 work from a network installation (not really
>hard work: a shared folder + copying some dlls + setting PYTHONPATH).
>PythonWin amd COM seem to be working fine from the network install, BUT
>when I need to pass PyTime to a COM object expecting a Date I get the
>following error:
>
>Python24\Lib\site-packages\win32com\client\dynamic.py", line 251, in
>_ApplyTypes_
>result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType,
>argTypes) + args)
>TypeError: Objects of type 'time' can not be converted to a COM VARIANT
>
>Note 1: The same code works when using the local installation of
>python/pywin, it only happens when executing the code from a network
>"installation".
>
>Note 2: As mentioned other COM components seem to be working when
>running them via pywin from the network install
>
>Note 3: I am passing pywintipes.Time(datetime.datetime.today()) to a
>COM object method which expects a Date argument.
>
>Do I need to change some environment variable/registry settings/other
>hack to fix this?
>
>  
>
Simply moving the win32 install and setting the python path isn't all 
you need to do to get a network install working.  In addition, you need 
to remove the win32 from your local install (or piss around with 
sys.path to strip out those local references) as that will automatically 
be included.  In addition, there is a registry setting you need to 
delete which automagically adds to the python path - it's in 
HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE.

That's probably won't solve your problem but it's somethng to be 
aware of anyways.

Neil

-- 

Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 47
D-01307
Dresden
Germany

Tel : +49 (0)351 4173 154
e-mail : [EMAIL PROTECTED]
Cenix Website : http://www.cenix-bioscience.com

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


Re: Help sorting a list by file extension

2005-08-12 Thread Cyril Bazin
Maybe simpler but not very much simpler: one line for each solution. 

And in your solution the lambda is evaluated at each comparaison of the sort algorithm isn't it? 

So your code seems less productive than the bengt's code which apply
the same code as the lambda only one time by entry in the list.
Cyril
On 8/12/05, George Yoshida <[EMAIL PROTECTED]> wrote:
Bengt Richter wrote:[name for dec,name in sorted((int(nm.split('.')[1]),nm) for nm in namelist)]>> ['test.1', 'test.2', 'test.3', 'test.4', 'test.10', 'test.15', 'test.20']Giving a key argument to sorted will make it simpler::
>>> sorted(namelist, key=lambda x:int(x.rsplit('.')[-1]))-- george--http://mail.python.org/mailman/listinfo/python-list

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

Re: What is Python?!

2005-08-12 Thread Martin P. Hellwig
Magnus Lycka wrote:

> or what have you. How do you sell this without making it sound
> like snake oil? (Particularly with that name! :)


This *is* the languange you are looking for ...


Stops the argument every time, although afterwards they look kind a 
funny at me.

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


Re: Jargons of Info Tech industry

2005-08-12 Thread Ulrich Hobelmann
Jürgen Exner wrote:
> Just for the records at Google et.al. in case someone stumbles across Xah's
> masterpieces in the future:
> Xah is very well known as the resident troll in many NGs and his
> 'contributions' are less then useless.

And you are the resident troll-reply service, posting this reply every time?

> Best is to just ignore him.

You just broke that rule.

> But for heaven's sake unless you want to embarrass yourself really badly
> don't take any of his postings serious because he has proven again and again
> that he has no clue whatsoever about computer science or programming.

Fine.  Many people don't.  Whoever takes the time to read Xah's postings 
(I don't) will probably be able to find that out by himself.

-- 
I believe in Karma.  That means I can do bad things to people
all day long and I assume they deserve it.
Dogbert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattribute__ for class object

2005-08-12 Thread Dan
> > but if i want to have a __getattribute__ for class attributes
>
> Read something on metaclasses.

Depending on what you want to do, it might be better to use properties
instead:

  class Meta(type):
 x = property(lambda klass: 'Called for '+str(klass))

  class Foo(object):
 __metaclass__=Meta

  print Foo.x

-- 
  Do I know what's in this bill? Are you kidding? Only God knows...
  - U.S. Senator Robert Byrd, when asked if he knew the
contents of a $520 billion, 4000-page spending bill


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


Help with wxPython

2005-08-12 Thread mitsura
Hi,

I have encountered an annoying problem with wx.Choice from wx.Python.
Basically, what I want to do is create a drop down box with a set of
choices (so far so good). The problem is that when the drop down box is
created, the first entry in the list of the drop down box is empty and
you need to drop down in the list to make your choice.
I was looking for an option that allows to set a default/preset choice
in the list.
This is important because I have written an apps where you can set the
properties of objects (cars) via drop down list and choose between a
set of pre-defined choices. However, if the set the properties of the
car (color, model, ...) via the Edit Properties windows but later you
which to change a properties it would be nice to see the choices you
made in de dropdown list and not a blank a first choice.

It seems trivial do.

Any help very much appreciated.

Kris

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


Re: Why is this?

2005-08-12 Thread Peter Mott
If I use concatenation + instead of multiplication * then I get the 
result that Jiri expected:

 >>> L = [[]] + [[]]
 >>> L[1].append(1)
 >>> L
[[], [1]]

With * both elements are changed:

 >>> L = [[]] * 2
 >>> L[1].append(1)
 >>> L
[[1], [1]]

Alex Martelli says in his excellent Nutshell book that + is 
concatenation and that "n*S is the concatenation of n copies of S". But 
it seems not so. Surely, from a logical point of view, S + S should be 
the same as S * 2?

Peter



The excellent Martelli Python Nutshell says that multiplication S*n is 
"the concatenation of n copies of S" so S+S and S*2 would be expected to 
be the same. It seems though that they are not but that * creates a list


Jiri Barton wrote:
> Hi everyone,
> 
> I have a problem with initialization.
> 
a, b = [[]]*2
a.append(1)
b
> 
> [1]
> 
> Why is this? Why does not this behave like the below:
> 
> 
a, b = [[], []]
a.append(1)
b
> 
> []
> 
> And, just to add to my confusion:
> 
> 
[[]]*2
> 
> [[], []]
> 
[[], []] == [[]]*2
> 
> True
> 
> Thanks in advance for the explanation.
> jbar
> 
> 
> BTW, if it matters...
> Python 2.4.1 (#2, Mar 30 2005, 20:41:35)
> [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: len(sys.argv) in (3,4)

2005-08-12 Thread Magnus Lycka
Daniel Schüle wrote:
> I just tried the same code at home and it worked fine
> it has to do with windows .. some settings or whatever
> (python 2.4.1 installed on both)
> 
> maybe someone have experienced the same problem
> and had more luck in solving the puzzle

First of all: "Windows" is a whole family of OSes,
and not all members have any blood relations. The
NT family is probably more related to VMS than to
MS DOS.

Secondly: There is an association mechanism (I don't
have access to Windows at work, but you can find it
in some Explorer menu) where you define what the OS
does when you try to fire off a file with a certain
extension. That mechanism defines if and how the OS
passes command line arguments.

It might we work better if you run "python x.py y z"
instead of just "x.py y z".

This might give a hint...
http://www.robvanderwoude.com/call.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NEWB: General purpose list iteration?

2005-08-12 Thread Donald Newcomb

"Devan L" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> This will just do_something(object) to anything that is not an
> iterable. Only use it if all of your nested structures are of the same
> depth.

Cool! I'll try it.

-- 
Donald Newcomb
DRNewcomb (at) attglobal (dot) net


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


bug in property?

2005-08-12 Thread Damir Hakimov
#!/usr/bin/python2.4
class test_property:
def __init__(self):
self._x="Zero"
pass
def setx(self,x):
print "set x"  #this is not work
self._x=x
def getx(self): return self._x
def delx(self): del(self._x)
x=property(getx,setx,delx,"XXX")
t=test_property()
t.x=1
print t.x

[EMAIL PROTECTED]:~$ ./test.py
1

And were is "set x"?
If you comment out t.x=1 you'll see that getx() works.

Damir


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


Re: Jargons of Info Tech industry

2005-08-12 Thread Thomas Fritsch
Xah Lee wrote:
> [...]
> My time is limited, so i'll just give a brief explanation of my thesis
> [...]
This is what psychology calls a disordered self-perception.

-- 
"Thomas:Fritsch$ops:de".replace(':','.').replace('$','@')

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


Re: bug in property?

2005-08-12 Thread Simon Brunning
On 8/12/05, Damir Hakimov <[EMAIL PROTECTED]> wrote:
> #!/usr/bin/python2.4
> class test_property:
> def __init__(self):
> self._x="Zero"
> pass
> def setx(self,x):
> print "set x"  #this is not work
> self._x=x
> def getx(self): return self._x
> def delx(self): del(self._x)
> x=property(getx,setx,delx,"XXX")
> t=test_property()
> t.x=1
> print t.x

Properties only work with new style classes, so try:

class test_property(object):

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pywin32 from network install

2005-08-12 Thread agostino . russo
Hmm I have the same problem using python -E... Moreover I do not see
anything strange in the sys.path (Z\LocalApps is my shared folder):

'Z:\\LocalApps\\examples',
'Z:\\LocalApps\\python\\python24.zip',
'Z:\\LocalApps\\examples',
'Z:\\LocalApps\\python\\DLLs',
'Z:\\LocalApps\\python\\lib',
'Z:\\LocalApps\\python\\lib\\platwin',
'Z:\\LocalApps\\python\\lib\\libtk',
'Z:\\LocalApps\\python',
'Z:\\LocalApps\\python\\lib\\sitepackages',
'Z:\\LocalApps\\python\\lib\\sitepackages\\Numeric',
'Z:\\LocalApps',
'Z:\\LocalApps\\python\\lib\\sitepackages\\win32',
'Z:\\LocalApps\\python\\lib\\site-packages\\win3\\lib',
'Z:\\LocalApps\\python\\lib\\sitepackages\\Pythonwin', '
'Z:\\LocalApps\\python\\lib\\site-packages\\wx-2.6-mswansi'

BUT when the error is thrown out it is:

C:\Program
Files\Python24\Lib\site-packages\win32com\client\dynamic.py...

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


Re: Why is this?

2005-08-12 Thread Duncan Booth
Peter Mott wrote:

> If I use concatenation + instead of multiplication * then I get the 
> result that Jiri expected:
> 
> >>> L = [[]] + [[]]
> >>> L[1].append(1)
> >>> L
> [[], [1]]
> 
> With * both elements are changed:
> 
> >>> L = [[]] * 2
> >>> L[1].append(1)
> >>> L
> [[1], [1]]
> 
> Alex Martelli says in his excellent Nutshell book that + is 
> concatenation and that "n*S is the concatenation of n copies of S". But 
> it seems not so. Surely, from a logical point of view, S + S should be 
> the same as S * 2?
> 
What you did was not S+S. You did S+T, i.e. you added two distinct lists. 
Try it again adding the same list and you will see that both addition and 
multplication do work the same:

>>> S = [[]]
>>> L = S + S
>>> L[1].append(1)
>>> L
[[1], [1]]
>>> S = [[]]
>>> L = 2*S
>>> L[1].append(1)
>>> L
[[1], [1]]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is this?

2005-08-12 Thread Matt Hammond
On Fri, 12 Aug 2005 12:57:38 +0100, Peter Mott <[EMAIL PROTECTED]> wrote:

> If I use concatenation + instead of multiplication * then I get the  
> result that Jiri expected:
>
>  >>> L = [[]] + [[]]
>  >>> L[1].append(1)
>  >>> L
> [[], [1]]
>
> With * both elements are changed:
>
>  >>> L = [[]] * 2
>  >>> L[1].append(1)
>  >>> L
> [[1], [1]]
>
> Alex Martelli says in his excellent Nutshell book that + is  
> concatenation and that "n*S is the concatenation of n copies of S". But  
> it seems not so. Surely, from a logical point of view, S + S should be  
> the same as S * 2?

S+S is the same as S*2, but L= [[]] + [[]] is not S+S. The two terms being  
added are different instances of an empty list. You are  
adding/concatenating two different object instances.

Suppose I do concatenate two of the same object instance, then I get the  
same behaviour as with the multiply example:
>>> T = [[]]
>>> L = T + T
>>> L[1].append(1)
>>> L
[[1], [1]]

In fact, you could argue this is exactly what the multiply operation is  
doing. (internally the implementation may be slightly different, but it is  
still equivalent to this)

regards


Matt
-- 

| Matt Hammond
| R&D Engineer, BBC Research and Development, Tadworth, Surrey, UK.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do these Java concepts translate to Python?

2005-08-12 Thread Roy Smith
"Ray" <[EMAIL PROTECTED]> wrote:
> I've been learning Python in my sparetime. I'm a Java/C++ programmer by
> trade. So I've been reading about Python OO, and I have a few questions
> that I haven't found the answers for :)
> 
> 1. Where are the access specifiers? (public, protected, private)

Quick answer; there are none, all attributes are public.

Slightly longer answer; if you name an attribute with two leading 
underscores (i.e. "__myPrivateData"), there is some name mangling that goes 
on which effectively makes the attribute private.  There are ways around 
it, but you have to know what you're doing and deliberately be trying to 
spoof the system (but, then again, exactly the same can be said for C++'s 
private data).

Soapbox answer; private data is, in some ways, a useful tool, but it is not 
part and parcel of object oriented programming.  I've had people (mostly 
C++/Java weenies) that Python is not an OOPL because it does not enforce 
data hiding.  "Feh", I say to them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to quit a Windows GUI program gracefully with Python under Cygwin?

2005-08-12 Thread Jason Tishler
On Fri, Aug 12, 2005 at 03:07:02AM -0700, KB wrote:
> After I confirmed 'Alt-F4' would terminate and close a win32
> application running independently,
> I installed 'SendKeys' module and tested with the following code under
> both Cygwin and Python Windows

If you installed the SendKeys binary, then it will not work with Cygwin
Python since it is a Windows Python shared extension module.  It may be
possible to port SendKeys to Cygwin.  Unfortunately, this may not solve
your problem... :,(

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with wxPython

2005-08-12 Thread Roel Schroeven
[EMAIL PROTECTED] wrote:

> I have encountered an annoying problem with wx.Choice from wx.Python.
> Basically, what I want to do is create a drop down box with a set of
> choices (so far so good). The problem is that when the drop down box is
> created, the first entry in the list of the drop down box is empty and
> you need to drop down in the list to make your choice.
> I was looking for an option that allows to set a default/preset choice
> in the list.

The SetSelection method does that. I guess the reason you didn't find it 
is because it is not included in the documentation for wxChoice itself; 
it is described in the section for wxControlWithItems, which is 
wxChoice's base class.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Writing a small battleship game server in Python

2005-08-12 Thread Michael Goettsche
On Thursday 11 August 2005 18:08, Brian Quinlan wrote:
> Michael Goettsche wrote:
> > What would be a good, but still easy way to write such a server?
>
> You could use SimpleXMLRPCServer. A client call sequence could like this:

Thanks for the example Brian.
I wonder... is there a standard implementation for languages like Delphi and 
C++/Qt too? The server should work well with other clients.

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


Re: Writing a small battleship game server in Python

2005-08-12 Thread Michael Goettsche
On Thursday 11 August 2005 19:03, [EMAIL PROTECTED] wrote:
> Why not using directly SOAP ?
>
> A minimalistic 'Hello world' client looks like :
>
>from SOAPpy import SOAPProxy
>
>server= SOAPProxy("http://localhost:8080";)
>print server.Hello("world")
>
> and the server side like :
>
> from SOAPpy import SOAPServer
>
> def Hello(name):
>   print "Wishing "+name+" hello !"
>   return "Hello "+name
>
> server= SOAPServer(("localhost",8080))
> server.registerFunction(Hello)
> server.serve_forever()
>
> Difficult to make it simpler isn't it ?

Thanks to you too and the same question for you. :-)
How well will this server work with clients written in other 
languages/toolkits without the need of installing additional things? for 
example, does Delphi have a Soap implementation? IIRC Qt doesn't offer one 
for free.

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


Re: Writing a small battleship game server in Python

2005-08-12 Thread Michael Goettsche
On Thursday 11 August 2005 18:34, Dan wrote:
> > The server should accept connections from new players and be able to
> > handle multiple games concurrently.
>
> Multiple threads would be the way to go for a real application. But if
> you want to avoid the complexity involved in threading and
> synchronization in this exercize, you can avoid threads by using
> "select" instead:
>   http://www.python.org/doc/2.3.5/lib/module-select.html
>
> The "select" function allows you to determine (without blocking) which
> sockets have input available.
>
> Python's "select" is a wrapper for the C function with the same name. On
> Unix you can learn more about it using "man select".
>

Thanks Dan.
Assuming the server accepts connections in an endless loop, how would I handle 
communication without additional threads and create new games in that loop?
Could you give me pseudo-code for this?

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


Re: Where can be a problem?

2005-08-12 Thread Lad
Peter,
I tried exactly this

import re
Results=[]
data1=''
ID = re.compile(r'^.*=(\d+)&.*$',re.MULTILINE)
Results=re.findall(ID,data1)
print "Results are= ",Results
#
and received
Results are=  ['15017']

Not all numbers

What exactly did you get?
Thanks.
L.

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


Zope, Python 2.4 pythonScripts import problem

2005-08-12 Thread krzychu
Hi,

I have installed brand new platform - Zope-2-7-6, Python 2.4.1, Plone
2.0.5, OS Debian 1:3.3.6-2.

After import a old Plone site from the following platform
Zope-2-7-4, Python 2.3.3, Plone 2.0.3 to the new one, I get error when
I visit PuthonScript in the ZMI.

"invalid syntax (Script (Python), line 1)"

There 2 are examples of 1 line:
from DateTime import DateTime
and
request = container.REQUEST

There is no syntax error!

When I just save this script in ZMI then error disappers :)

What is the reason???
KK

p.s I have the same problem when I import to the same platform but with
Python 2.4.0

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


Re: Printing to printer

2005-08-12 Thread Larry Bates
I adapted some code from David Boddie into a Python class to write
directly to Linux print queues.  I have used it in one project and
it worked just fine.  I've attached a copy for your use.  You are
free to use it as you wish, with no guarantees or warranties.

Hope it helps.

Larry Bates

Steve M wrote:
> Hello,
> 
> I'm having problems sending information from a python 
> script to a printer. I was wondering if someone might send me 
> in the right direction. I wasn't able to find much by Google
> 
> TIA
> Steve
#! /usr/bin/python
"""
Name: lpr.py
Author  : adapted from code by David Boddie
Created : Tue 08th August 2000
Last modified   : Thu 06th September 2001
Purpose : Send a file to a printer queue.
"""

import os, socket, string, sys

class lprClass:
_debug=0
_trace=0

def __init__(self, host, user, server, printer):
#
# Handle empty arguments by assiging default values
#
if host: self.host=host
else:self.host=socket.gethostname()

if user: self.user=user
else:
try:
self.user=os.environ['USER']
except KeyError:

print "lprClass***Error no user passed to class 
and no USER env variable found"
sys.exit(2)

if server: self.server=server
else:  self.server=socket.gethostbyaddr(self.host)[2][0]

if printer: self.printer=printer
else:
try:
self.printer=os.environ['PRINTER']
except KeyError:
print "lprClass***Error no printer passed to 
class and no PRINTER env variable found"
sys.exit(2)

if self._debug:
print "lprClass*** host=",self.host
print "lprClass*** user=",self.user
print "lprClass*** server=",self.server
print "lprClass*** printer=",self.printer

#
# Create a socket object to communcate with the LPR daemon
#
if self._trace: print "lprClass***Creating a socketobj instance"
self.socketobj=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if self._trace: print "lprClass***Conecting to port 515 on 
server"
self.socketobj.connect((self.server, 515))
if self._trace: print "lprClass***Initializing LPR daemon for 
job to printer=", self.printer
self.socketobj.send("\002"+self.printer+"\012")
d=self.socketobj.recv(1024)
#
# Wait for reply and check response string
#
errormsg="lprClass***Error initializing communications with LPR 
daemon"
if d != "\000": self._abort(d, errormsg)
return

def _initcontrol(self, filename):
#
# Build a control string
#
control='H'+self.host[:31]+"\012"+'N'+filename[:131]+"\012"+ \

'P'+self.user[:31]+"\012"+'o'+filename[:131]+"\012"


#
# Send the receive control file subcommand
#
if self._trace: print "lprClass***Sending the receive control 
file subcommand"
self.socketobj.send("\002"+str(len(control))+" 
cfA000"+self.host+"\012")
#
# Wait for reply and check response string
#
if self._trace: print "lprClass***Waiting for reply"
d=self.socketobj.recv(1024)
errormsg="lprClass***Error in control string initialization for 
LPR daemon"
if d != "\000": self._abort(d, errormsg)

#
# Send the control file
#
if self._trace: print "lprClass***Sending the control file 
command"
self.socketobj.send(control)
self.socketobj.send("\000")
#
# Wait for reply and check response string
#
if self._trace: print "lprClass***Waiting for reply"
d=self.socketobj.recv(1024)
errormsg="lprClass***Error in control string for LPR daemon"
if d != "\000": self._abort(d, errormsg)
return

def _abort(self, d

Re: How do these Java concepts translate to Python?

2005-08-12 Thread Ray


bruno modulix wrote:

> And BTW, don't bother making all your attributes "protected" or
> "private" then writing getters and setters, Python has a good support
> for computed attributes, so you can change the implementation without
> problem (which is the original reason for not-public attributes):

Thanks Bruno! This is good stuff. This is exactly what I want to avoid:
writing Java in Python.

Cheers,
Ray

>
> # first version:
> class Foo(object):
>   def __init__(self):
>  self.baaz = 42 # public attribute
>
> # later we discover that we want Foo.baaz to be computed:
> class Foo(object):
>   def __init__(self):
>  self.baaz = 42
>
>   def _set_baaz(self, value):
>  if value < 21 or value > 84:
> raise ValueError, "baaz value must be in range 21..84"
>  self._baaz = value
>
>   def _get_baaz(self):
>   return self._baaz * 2
>
>   baaz = property(fget=_get_baaz, fset=_set_baaz)
>
> Easy as pie, uh ?-)
>
>
> --
> 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: len(sys.argv) in (3,4)

2005-08-12 Thread infidel
> Nope. But since you're running this on a very peculiar OS, I just can
> guess that this very peculiar OS consider all args to be one same string...

It depends on what you're coding with.  If you're writing a Win32
program in C/C++ (and by extension, Visual Basic), the WinMain()
function passes all of the arguments in a single string.  One of the
many stunningly boneheaded Win32 decisions, IMNSHO.

> BTW, isn't the DOS syntax for command line args something like :
> > myprog /arg1 /arg2

No, by convention only, the "switch" character for DOS programs is "/"
instead of "-" or "--".  Personally, I'm of the opinion that this
switch convention, backslashes in paths, and two-byte newlines are all
intentionally designed to make things LESS compatibile with other OSes,
and MORE difficult to interoperate.

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


Re: Catching stderr output from graphical apps

2005-08-12 Thread gry
Linux -2.4.20 (x86), Python 2.3.3.
I did exactly as you suggested.
After the stderr.write, a window pops up with title "Error Stream from
run of errorwindow.pyc".
The window is otherwise blank.
Nothing more happens when I do the "x=7+nosuchvariable", I just get
the next python ">>>" prompt, but no error messages.
When I try to exit the python, e.g. sys.exit(), it hangs and I have to
Control-C.
After the control-C, the "Error Stream..." window goes away.

Any more suggestions?  Perhaps we should take this to email, instead of
newsgroup?
This *is* something I would like to be able to use, if we can get it
working.

-- George

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


Re: len(sys.argv) in (3,4)

2005-08-12 Thread infidel
It might make more sense if you could find out exactly what that one
argument contains.

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


Python's Exception, and Capitalization

2005-08-12 Thread Ray
Hello guys,

OK, I've been reading some more about Python. There are some things
about Python exception that I haven't been able to grasp:

1. This is a small thing, but why is object spelled "object", and the
mother of all exception "Exception" (with capital E)? Why is not object
spelled "Object" then? Especially since Exception's descendants are
named with the first letter of each word capitalized? I mean, in Java,
it's Object. Whereas in C++, they're quite consistent, standard stuff
are usually all lowercaps (basic_string, iostream, etc.). Python seems
to have a mix of both.

Am I right in assuming that object is object (with lower case 'o')
because it is built-in, and Exception is not? So when we write our own
classes, exceptions, etc., we should capitalize it like in Java or C#?
By the way, what's the convention for functions? It's a bit confusing
because when I see Python builtins, it seems that they follow C++ style
(e.g.: has_key, readline). So... does it mean that when I write my own
function, customarily I'd say myFunction() (or MyFunction()?)

2. I'm quite baffled that you either have try/except, or try/finally.
In Java, it is quite common to do this:

try {
// something
} catch(AException e) {
// handle
} catch(BException e) {
// handle
} catch(CException e) {
// handle
} finally {
// whatever happens, execute this
}

It seems that since except and finally are mutually exclusive I can't
do this. So... what's the usual idiom for this?

Thanks!
Ray

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


Re: Where can be a problem?

2005-08-12 Thread Peter Otten
Lad wrote:

> Peter,
> I tried exactly this
> 
> import re
> Results=[]
> data1=' href="detailaspxmember=15016&mode=advert"  href="detailaspxmember=15017&mode=advert" '
> ID = re.compile(r'^.*=(\d+)&.*$',re.MULTILINE)
> Results=re.findall(ID,data1)
> print "Results are= ",Results
> #
> and received
> Results are=  ['15017']
> 
> Not all numbers
> 
> What exactly did you get?

With /exactly/ this, I get:

$ cat lad1.py
import re
Results=[]
data1=''
ID = re.compile(r'^.*=(\d+)&.*$',re.MULTILINE)
Results=re.findall(ID,data1)
print "Results are= ",Results
$ python lad1.py
  File "lad1.py", line 3
data1=
ID = re.compile(r'^.*=(\d+)&.*$',re.MULTILINE)
Results=re.findall(ID,data1)
print "Results are= ",Results
$ python lad2.py
Results are=  ['15015', '15016', '15017']

Peter

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


simpli int/str problem

2005-08-12 Thread sinan .
hi all,
i have a string and int values in same dictionary like this
dict = {'str_name': 'etc' , 'int_name' : 112 }
the error occures when do this
SQL = "INSERT INTO (`AH`, `BH` ) VALUES ('" + dict['str_name'] + "',
'" + dict['int_name'] + "')"
cursor.execute(SQL)
python does not accep dict['int_name'] in SQL variable but when i
convert this variable to the str , python accepts but i cannot insert
that into database because database only accept int in `BH `
thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do these Java concepts translate to Python?

2005-08-12 Thread Ray
Roy Smith wrote:
> Quick answer; there are none, all attributes are public.
>
> Slightly longer answer; if you name an attribute with two leading
> underscores (i.e. "__myPrivateData"), there is some name mangling that goes
> on which effectively makes the attribute private.  There are ways around
> it, but you have to know what you're doing and deliberately be trying to
> spoof the system (but, then again, exactly the same can be said for C++'s
> private data).

Well yeah... if you really want it, in Java you can do that too via
reflection. Just that I'm not used to it yet so I feel a bit jittery
with so much power on my hands!

> Soapbox answer; private data is, in some ways, a useful tool, but it is not
> part and parcel of object oriented programming.  I've had people (mostly
> C++/Java weenies) that Python is not an OOPL because it does not enforce
> data hiding.  "Feh", I say to them.

Feh... those weenies don't know what they're talkin about.

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


Text/IDE Python Editor?

2005-08-12 Thread djanvk
Any recommendations on a editior/IDE for programming in python?

I'm using windows xp.


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


Re: Python's Exception, and Capitalization

2005-08-12 Thread D H
Ray wrote:
> Hello guys,
> 
> OK, I've been reading some more about Python. There are some things
> about Python exception that I haven't been able to grasp:
> 
> 1. This is a small thing, but why is object spelled "object", and the
> mother of all exception "Exception" (with capital E)? Why is not object
> spelled "Object" then? 

I would guess that object is considered a primitive/basic type like int 
or float or string.


> I mean, in Java,
> it's Object. Whereas in C++, they're quite consistent, standard stuff
> are usually all lowercaps (basic_string, iostream, etc.). Python seems
> to have a mix of both.

Yeah java capitalizes anything that is a class like String, Object, 
Integer, and lowercases its primitives like int, byte.


> By the way, what's the convention for functions? It's a bit confusing
> because when I see Python builtins, it seems that they follow C++ style
> (e.g.: has_key, readline). So... does it mean that when I write my own
> function, customarily I'd say myFunction() (or MyFunction()?)

Yeah, the python standard library has been built by lots of different 
people.  It wasn't designed by one entity using one standard like the 
java standard library or .NET/Mono class library.


> 2. I'm quite baffled that you either have try/except, or try/finally.

Apparently that will be fixed sometime:
http://python.miscellaneousmirror.org/peps/pep-0341.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Text/IDE Python Editor?

2005-08-12 Thread Simon Brunning
On 8/12/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Any recommendations on a editior/IDE for programming in python?

http://wiki.python.org/moin/PythonEditors

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in slice type

2005-08-12 Thread Michael Hudson
Bryan Olson <[EMAIL PROTECTED]> writes:

> The Python slice type has one method 'indices', and reportedly:
>
>  This method takes a single integer argument /length/ and
>  computes information about the extended slice that the slice
>  object would describe if applied to a sequence of length
>  items. It returns a tuple of three integers; respectively
>  these are the /start/ and /stop/ indices and the /step/ or
>  stride length of the slice. Missing or out-of-bounds indices
>  are handled in a manner consistent with regular slices.
>
>  http://docs.python.org/ref/types.html
>
>
> It behaves incorrectly 

In some sense; it certainly does what I intended it to do.

> when step is negative and the slice includes the 0 index.
>
>
>  class BuggerAll:
>
>  def __init__(self, somelist):
>  self.sequence = somelist[:]
>
>  def __getitem__(self, key):
>  if isinstance(key, slice):
>  start, stop, step = key.indices(len(self.sequence))
>  # print 'Slice says start, stop, step are:', start,
>stop, step
>  return self.sequence[start : stop : step]

But if that's what you want to do with the slice object, just write

 start, stop, step = key.start, key.stop, key.step
 return self.sequence[start : stop : step]

or even

 return self.sequence[key]

What the values returned from indices are for is to pass to the
range() function, more or less.  They're not intended to be
interpreted in the way things passed to __getitem__ are.

(Well, _actually_ the main motivation for writing .indices() was to
use it in unittests...)

>  print   range(10) [None : None : -2]
>  print BuggerAll(range(10))[None : None : -2]
>
>
> The above prints:
>
>  [9, 7, 5, 3, 1]
>  []
>
> Un-commenting the print statement in __getitem__ shows:
>
>  Slice says start, stop, step are: 9 -1 -2
>
> The slice object seems to think that -1 is a valid exclusive
> bound, 

It is, when you're doing arithmetic, which is what the client code to
PySlice_GetIndicesEx() which in turn is what indices() is a thin
wrapper of, does

> but when using it to actually slice, Python interprets negative
> numbers as an offset from the high end of the sequence.
>
> Good start-stop-step values are (9, None, -2), or (9, -11, -2),
> or (-1, -11, -2). The later two have the advantage of being
> consistend with the documented behavior of returning three
> integers.

I'm not going to change the behaviour.  The docs probably aren't
especially clear, though.

Cheers,
mwh

-- 
  (ps: don't feed the lawyers: they just lose their fear of humans)
 -- Peter Wood, comp.lang.lisp
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simpli int/str problem

2005-08-12 Thread [EMAIL PROTECTED]
Use substitution like below.
Hope this helps

py> d = {'str_name': 'etc' , 'int_name' : 112 }
py> SQL = "INSERT INTO (`AH`, `BH` ) VALUES ('" + d['str_name'] + "',
'" + d['int_name'] + "')"

Traceback (most recent call last):
  File "", line 1, in -toplevel-
SQL = "INSERT INTO (`AH`, `BH` ) VALUES ('" + d['str_name'] + "',
'" + d['int_name'] + "')"
TypeError: cannot concatenate 'str' and 'int' objects
py> SQL = "INSERT INTO (`AH`, `BH` ) VALUES ('%s', %d)" %
(d['str_name'], d['int_name'])
py> print SQL
INSERT INTO (`AH`, `BH` ) VALUES ('etc', 112)
py>

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


Re: Python's Exception, and Capitalization

2005-08-12 Thread Ray
D H wrote:
> Yeah, the python standard library has been built by lots of different
> people.  It wasn't designed by one entity using one standard like the
> java standard library or .NET/Mono class library.

Um, OK, so is it customary in modern Python programs to follow Java
convention? then methods/functions should be written someMethod() or
myFunction()?

> > 2. I'm quite baffled that you either have try/except, or try/finally.
>
> Apparently that will be fixed sometime:
> http://python.miscellaneousmirror.org/peps/pep-0341.html

Ah, okay. I'm quite surprised to see the date--it was _that_ recent! :)
But currently, how have you--Python guys who code for a living--been
handling this case? I know that you can put another try inside a try,
but obviously the need for that is not common enough in idiomatic
Python program (or else this would have been a PEP in, say, 2000).

Cheers
Ray

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


Re: simpli int/str problem

2005-08-12 Thread Paolino
sinan . wrote:
> hi all,
> i have a string and int values in same dictionary like this
> dict = {'str_name': 'etc' , 'int_name' : 112 }
> the error occures when do this
> SQL = "INSERT INTO (`AH`, `BH` ) VALUES ('" + dict['str_name'] + "',
> '" + dict['int_name'] + "')"
> cursor.execute(SQL)
> python does not accep dict['int_name'] in SQL variable but when i
> convert this variable to the str , python accepts but i cannot insert
> that into database because database only accept int in `BH `
> thanks.
Try use:
SQL = "INSERT INTO (`AH`, `BH` ) VALUES 
('%s,%d)"%(dict['str_name'],dict['int_name'])

Paolino


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simpli int/str problem

2005-08-12 Thread Paul McGuire
I just did this sort of thing the other day!

Your database only accepts ints for BH, but remember, you are building
an SQL *string* to be executed.  To show SQL that your BH value is an
int, not a string, do not enclose it in quotes.

(Another style hint: don't name dict's "dict", as this will mask the
actual type name.  Let's try "vDict" for now, meaning "value dict".)

SQL = "INSERT INTO XYZ('AH', 'BH' ) VALUES ('" + vDict['str_name'] + \
   "', " + str(vDict['int_name']) + ")"

In my program, I found it a bit easier to follow if I used string
interpolation (the string % operation), and named format fields.  Try
this:

SQL = "INSERT INTO XYZ('AH', 'BH' ) VALUES ('%(str_name)s',
%(int_name)d)" % vDict

Again, note that the string value is surrounded by quotes, but the
integer value is not.

Also, you will need to replace XYZ with the actual table name. :)

-- Paul

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


Re: Python's Exception, and Capitalization

2005-08-12 Thread [EMAIL PROTECTED]
For youtr try, except, finally:

you can construct something like this:
try:
try:
print 'egg' + 1
except ValueError, e:
print e
finally:
print 'spam'

It results in:
py>
spam

Traceback (most recent call last):
  File "C:/Martin/test.py", line 3, in -toplevel-
print 'egg' + 1
TypeError: cannot concatenate 'str' and 'int' objects
py>

If you catch the TypeError you get:


try:
try:
print 'egg' + 1
except TypeError, e:
print e
finally:
print 'spam'

py> 
cannot concatenate 'str' and 'int' objects
spam
py>

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


Re: thread limit in python

2005-08-12 Thread danieldsmith
i modified my C test program (included below) to explicitly set the
default thread stack size, and i'm still running into the same
problem.  can you think of any other thing that would possibly be
limiting me?

and sorry to continue to post here.  since this is occurring in both c
and python, i think there's no question i'm running into an os limit.


#include 
#include 
#include 
#include 

void *
run (void *arg) {

   sleep(1000);
}

int main(int argc, char *argv[]) {

   int j;
   int ret;
   pthread_t tid;
   int num_threads = atoi(argv[1]);
   pthread_attr_t attr;
   int stacksize;

   pthread_attr_init(&attr);
  pthread_attr_getstacksize (&attr, &stacksize);
  printf("Default stack size = %d\n", stacksize);

   // set stack size to 64K
   pthread_attr_setstacksize (&attr, 0x1);

  pthread_attr_getstacksize (&attr, &stacksize);
  printf("New stack size = %d\n", stacksize);

   for (j=0; j < num_threads; j++) {

   ret = pthread_create (&tid, NULL, run, NULL);

   if (ret != 0) {
   printf("thread create failed\n",j);
   fflush(stdout);
   exit(0);
   }
   printf("created thread %d\n",j);
   fflush(stdout);

   }

   sleep(1000);
}

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


Re: Where can be a problem?

2005-08-12 Thread Lad
Thank you Peter for help.
The reason why it did not work was the fact that findall function
required CRLF among lines

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


Re: Where can be a problem?

2005-08-12 Thread Paul McGuire
Try this, its a bit more readable than your re.

from pyparsing import Word,nums,Literal,replaceWith

data1=''

# a number is a word composed of nums, that is, the digits 0-9
# your search string is looking for a number between an '=' and '&'
EQUALS = Literal("=")
AMPER = Literal("&")
number = Word(nums)
hrefNumber = EQUALS + number + AMPER

# scanString is a generator, that returns matching tokens, start,
# and end location for each occurrence in the input string - we
# just care about the second token of each match
print [ tokens[1] for tokens,s,e in hrefNumber.scanString(data1) ]

# just for grins, here is how to convert the numbers to the
# string "###"
number.setParseAction( replaceWith("###") )
print number.transformString(data1)


Prints:

['15015', '15016', '15017']


Download pyparsing at http://pyparsing.sourceforge.net.

-- Paul

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


Re: Jargons of Info Tech industry

2005-08-12 Thread Mike Schilling

"Jürgen Exner" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Xah Lee wrote:
>> Jargons of Info Tech industry
>>
>> (A Love of Jargons)
>>
>> Xah Lee, 2002 Feb
>>
>> People in the computing field like to spur the use of spurious
>> jargons. The less educated they are, the more they like extraneous
> [...]
>
> Just for the records at Google et.al. in case someone stumbles across 
> Xah's
> masterpieces in the future:
> Xah is very well known as the resident troll in many NGs and his
> 'contributions' are less then useless.

He sent a lovely one to some of the language groups the other day, 
explaining why Jonathan Swift was a poor writer. 


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

problem extending tkSimpleDialog.Dialog

2005-08-12 Thread William Gill
I have created a widget that extends Frame() and contains labels, 
checkboxes, and entrys.  I am trying to use tkSimpleDialog.Dialog to 
create a modal display of this widget, but am running into some 
(addressing) problems.  My widget displays in the parent widget, not the 
tkSimpleDialog.Dialog?  I hope this snippet is enough to help, as my 
actual code is really too hard to follow.

class showtestWidget(tkSimpleDialog.Dialog):
 def body(self,master):
   Label(master,text="showPhoneNums").grid()
   testWidget(self).grid()

class testWidget(Frame):
 def __init__(self, master):
   Frame.__init__(self)
   self.createWidgets()
 def createWidgets(self):
   Label(self,text="testWidget").grid()

When the parent script instantiates showtestWidget() it should create a 
transient dialog containing a label with the text "showPhoneNums".  It 
does, but the label containing the text "testWidget" is being created in 
the parent widget, not the dialog.

It seems obvious to me that I'm addressing the wrong parent somehow, 
since the label (probably the testWidget) is being created, but in the 
wrong place.

I tried changing   testWidget(self).grid() to 
testWidget(master).grid(), just to see if that helped, but it made no 
difference.

Can someone show me where I went wrong?

Bill


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


Re: How do these Java concepts translate to Python?

2005-08-12 Thread Aahz
In article <[EMAIL PROTECTED]>,
Ben Finney  <[EMAIL PROTECTED]> wrote:
>
>Recently, the language came to partially support '__foo' (i.e. a name
>beginning with two underscores) as a pseudo-"private". It's just a
>namespace munging though; sufficiently determined users can get at it
>without much effort.

Recently?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

The way to build large Python applications is to componentize and
loosely-couple the hell out of everything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's Exception, and Capitalization

2005-08-12 Thread Aahz
In article <[EMAIL PROTECTED]>,
Ray <[EMAIL PROTECTED]> wrote:
>
>2. I'm quite baffled that you either have try/except, or try/finally.
>In Java, it is quite common to do this:
>
>try {
>// something
>} catch(AException e) {
>// handle
>} catch(BException e) {
>// handle
>} catch(CException e) {
>// handle
>} finally {
>// whatever happens, execute this
>}
>
>It seems that since except and finally are mutually exclusive I can't
>do this. So... what's the usual idiom for this?

Keep in mind that Python actually predates Java.  The way this is
handled now is

try:
try:
except:
else:
finally:

Way back when, Guido thought that it would be confusing to allow both
except and finally clauses in the same try because people wouldn't know
what ordering to use (particularly with the else clause).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

The way to build large Python applications is to componentize and
loosely-couple the hell out of everything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jargons of Info Tech industry

2005-08-12 Thread jan V
> Xah is very well known as the resident troll in many NGs and his
'contributions' are less then useless.
>
> Best is to just ignore him.

Did you know that some deranged people take sexual pleasure out of starting
fires? Apparently some of the latest forest/bush fires in southern Europe
were even started by firemen (with their pants down?).

Maybe characters like Xah take some kind of sexual pleasure out of posting
his kind of posts... the tought doesn't bear thinking, does it?


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


Re: Why is this?

2005-08-12 Thread Peter Mott
Matt Hammond wrote:
> On Fri, 12 Aug 2005 12:57:38 +0100, Peter Mott <[EMAIL PROTECTED]> wrote:
> 
>> If I use concatenation + instead of multiplication * then I get the  
>> result that Jiri expected:
>>
>>  >>> L = [[]] + [[]]
>>  >>> L[1].append(1)
>>  >>> L
>> [[], [1]]
>>
>> With * both elements are changed:
>>
>>  >>> L = [[]] * 2
>>  >>> L[1].append(1)
>>  >>> L
>> [[1], [1]]
>>
>> Alex Martelli says in his excellent Nutshell book that + is  
>> concatenation and that "n*S is the concatenation of n copies of S". 
>> But  it seems not so. Surely, from a logical point of view, S + S 
>> should be  the same as S * 2?
> 
> 
> S+S is the same as S*2, but L= [[]] + [[]] is not S+S. The two terms 
> being  added are different instances of an empty list. You are  
> adding/concatenating two different object instances.

But it is still true that [[]] + [[]] is not the same as [[]] * 2. In my 
usage anyway this means that "S+S is the same as S*2" is false. Because 
there are Python expressions for which it is falsfied.

The problem I have is pretty philosophical I admit, but I don't think 
you do it justice. It's really about identity. Logically speaking 
identity is a congruence relation of a language, which means that if x=y 
is true then C(x) = C(y) will be true for any context C of the lanuage. 
Python is so regular that most of the time it follows this. But not with 
*. If you define C(x):

def C(x):
... x[1].append(1)
... return x[0]

then although [[]]+[[]] == [[]]*2 evaluates true  C([[]]+[[]]) is 
different from C([[]]*2). So == is not a congruence in Python. 
Inbteresting that Phil Hunt just posted about 'Unify' which, if I 
understand it right, has the feature that provided expressions S and T 
are in the canonical "Storage Manager" format then == will be a 
congruence and hence an idenity.

Cheers

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


Re: Python's Exception, and Capitalization

2005-08-12 Thread bruno modulix
Ray wrote:
> Hello guys,
> 
> OK, I've been reading some more about Python. There are some things
> about Python exception that I haven't been able to grasp:
> 
> 1. This is a small thing, but why is object spelled "object", and the
> mother of all exception "Exception" (with capital E)? Why is not object
> spelled "Object" then? 

I always wondered too... But then, you'll notice that Python's builtin
types are usually all lowercase.

(snip)

> So when we write our own
> classes, exceptions, etc., we should capitalize it like in Java or C#?

Yes, definitively.

> By the way, what's the convention for functions? It's a bit confusing
> because when I see Python builtins, it seems that they follow C++ style
> (e.g.: has_key, readline). So... does it mean that when I write my own
> function, customarily I'd say myFunction() (or MyFunction()?)

The all_lower_underscore is the common usage, at least in the std lib,
but feel free to use your favorite convention for this. It's up to you
as long as you stick to a given convention for a whole project.

> 2. I'm quite baffled that you either have try/except, or try/finally.
yes, it's a PITA.

> In Java, it is quite common to do this:
(snip)
> It seems that since except and finally are mutually exclusive I can't
> do this. So... what's the usual idiom for this?

try:
  try:
do_something()
  except Exception, e:
handle_error(e)
  else:
do_this_too()
finally:
  do_this_whatever()


-- 
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: Help sorting a list by file extension

2005-08-12 Thread Peter A.Schott
OK - I actually got something working last night with a list that is then
converted into a dictionary (dealing with small sets of data - < 200 files per
run).  However, I like the sorted list option - I didn't realize that was even
an option within the definition and wasn't quite sure how to get there.  I
realized I could use os.path.splitext and cast that to an int, but was having
trouble with the sort.

My files only have a single "." in them so this will work well for me.

(from Tom's code)
[name for dec,name in
sorted((int(os.path.splitext(nm)[1][1:]),nm) for nm in namelist)]

I'll give that a try - it would eliminate the dictionary part of my code and be
a little more efficient.

Thanks to all for the quick responses.

-Pete

Peter A. Schott <[EMAIL PROTECTED]> wrote:

> Trying to operate on a list of files similar to this:
> 
> test.1
> test.2
> test.3
> test.4
> test.10
> test.15
> test.20
> 
> etc.
> 
> I want to sort them in numeric order instead of string order.  I'm starting 
> with
> this code:
> 
> import os
> 
> for filename in [filename for filename in os.listdir(os.getcwd())]:
>   print filename
>   #Write to file, but with filenames sorted by extension
> 
> 
> Desired result is a file containing something like:
> C:\MyFolder\test.1,test.001
> C:\MyFolder\test.2,test.002
> C:\MyFolder\test.3,test.003
> C:\MyFolder\test.4,test.004
> C:\MyFolder\test.10,test.010
> C:\MyFolder\test.15,test.015
> C:\MyFolder\test.20,test.020
> 
> I need to order by that extension for the file output.
> 
> I know I've got to be missing something pretty simple, but am not sure what.
> Does anyone have any ideas on what I'm missing?
> 
> Thanks.
> 
> -Pete Schott
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do these Java concepts translate to Python?

2005-08-12 Thread bruno modulix
Ray wrote:
> Roy Smith wrote:
> 
>>Quick answer; there are none, all attributes are public.
>>
(snip)
> 
> Well yeah... if you really want it, in Java you can do that too via
> reflection. Just that I'm not used to it yet so I feel a bit jittery
> with so much power on my hands!

Then wait until you discover what one can do with __magic_methods__,
functions-as-objects, closures, callable objects, descriptors
(properties on steroids), decorators, generators, and metaclasses...
*Then* you'll know what power means !-)

And more is to come...

-- 
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: FTP over SSL (explicit encryption)

2005-08-12 Thread David Isaac
"Alan Isaac" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> http://www.lag.net/paramiko/
> However it requires the PyCrypto module.
> http://www.amk.ca/python/code/crypto
>
> Can you briefly outline how to use this as a client
> to upload and down files from a server using SFTP?


OK, the mechanics are pretty easy.

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(20)
sock.connect((hostname, port))
my_t = paramiko.Transport(sock)
my_t.connect(hostkey=None ,username=username, password=password, pkey=None)
my_chan = my_t.open_session()
my_chan.get_pty()
my_chan.invoke_shell()
my_sftp = paramiko.SFTP.from_transport(my_t)

Now my_sftp is a paramiko sftp_client.
See paramiko's sftp_client.py to see what it can do.

Alan Isaac


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


need help with my append syntax

2005-08-12 Thread yaffa
dear folks,

i'm trying to append a semicolon to my addr string and am using the
syntax below.  for some reason the added on of the ; doesn't work.
when i print it out later on it only shows the original value of addr.

addr = incident.findNextSibling('td')
addr.append('%s;')

thanks

yaffa

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


Re: How do these Java concepts translate to Python?

2005-08-12 Thread Ray
bruno modulix wrote:
> Then wait until you discover what one can do with __magic_methods__,
> functions-as-objects, closures, callable objects, descriptors
> (properties on steroids), decorators, generators, and metaclasses...
> *Then* you'll know what power means !-)
>
> And more is to come...

... I've got a feeling that this Pythonic journey will expand my brain
so much ;)

>
> --
> 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: need help with my append syntax

2005-08-12 Thread Qiangning Hong
yaffa wrote:
> dear folks,
> 
> i'm trying to append a semicolon to my addr string and am using the
> syntax below.  for some reason the added on of the ; doesn't work.
> when i print it out later on it only shows the original value of addr.
> 
> addr = incident.findNextSibling('td')
> addr.append('%s;')

Is addr is really a string?  AFAIK, strings havn't an append methond.

use += to extend strings:

.>>> addr = 'abc'
.>>> addr += '%s;'
.>>> addr
'abc%s;'

-- 
Qiangning Hong

I'm usually annoyed by IDEs because, for instance, they don't use VIM
as an editor. Since I'm hooked to that, all IDEs I've used so far have
failed to impress me.
-- Sybren Stuvel @ c.l.python

Get Firefox!

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


Re: thread limit in python

2005-08-12 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
> and sorry to continue to post here.  since this is occurring in both c
> and python, i think there's no question i'm running into an os limit.

Probably, but I haven't yet seen anyone ask the real important question. 
  What possible use could you have for more than 1000 *simultaneously 
active* threads?  There are very likely several alternative approaches 
that will fit your use case and have better characteristics (e.g. higher 
performance, simpler code, safer architecture, etc).

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


Re: Text/IDE Python Editor?

2005-08-12 Thread Peter A.Schott
Also, it depends on what you're trying to do.  GUI, Web, Service-type apps, etc.

I have started using Stan's Python Editor (www.stani.be) because I like the
general features it offers.  It does require wxpython to run, though.  I've also
used Boa Constructor and DrPython - both pretty good environments.  I believe
that they are both dependent on wxpython as well.

Some people like Eric - now available for XP using PyQt under the Qt GPL'd
version.  I had a little trouble with it running correctly - probably due to a
config issue on my part.  I will admit to not spending a lot of time with it,
though.

If you don't need the GUI IDE, there are a whole bunch of options available.
More than I'm able to delve into properly.

Best answer is to play around a little with the different IDE's and find the one
that works for your coding style.  Also, check the archives for this group. This
topic has come up quite a bit recently.

-Pete

Simon Brunning <[EMAIL PROTECTED]> wrote:

> On 8/12/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > Any recommendations on a editior/IDE for programming in python?
> 
> http://wiki.python.org/moin/PythonEditors
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's Exception, and Capitalization

2005-08-12 Thread Steve M
You might find the Python Style Guide to be helpful:

http://www.python.org/doc/essays/styleguide.html

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


Re: need help with my append syntax

2005-08-12 Thread Michael Ekstrand
On 12 Aug 2005 09:31:08 -0700
"yaffa" <[EMAIL PROTECTED]> wrote:
> addr = incident.findNextSibling('td')
> addr.append('%s;')

addr += ';'

or 

addr2 = '%s;' % addr

Strings, being immutable, do not support appending like lists do. Also,
the %whatever specifiers are only in effect when used with the string
formatting operator (%).

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


Re: need help with my append syntax

2005-08-12 Thread Qiangning Hong
Do not discuss off-list, maybe others will have better solutions to your
question.  And also please do not top-posting, it makes me difficult to
trim the irrelevant text.

yaffa wrote:
> sorry addr is a variable.  how to i append to that?

I know addr is a variable (or better a name).  But what object do you
assign to it?  I mean, does incident.findNextSibling('td') return a
string or an object of another type?

If your code "addr.append('%s;')" doesn't raise an exception, it is
pretty sure what assigned to addr is not a string (maybe a list, which
has an "append" method).  You can use "print addr" or "print repr(addr)"
to determine that.


> - Original Message - From: "Qiangning Hong" <[EMAIL PROTECTED]>
> To: "yaffa" <[EMAIL PROTECTED]>
> Cc: 
> Sent: Friday, August 12, 2005 12:47 PM
> Subject: Re: need help with my append syntax
> 
> 
>> yaffa wrote:
>>
>>> dear folks,
>>>
>>> i'm trying to append a semicolon to my addr string and am using the
>>> syntax below.  for some reason the added on of the ; doesn't work.
>>> when i print it out later on it only shows the original value of addr.
>>>
>>> addr = incident.findNextSibling('td')
>>> addr.append('%s;')
>>
>>
>> Is addr is really a string?  AFAIK, strings havn't an append methond.
>>
>> use += to extend strings:
>>
>> .>>> addr = 'abc'
>> .>>> addr += '%s;'
>> .>>> addr
>> 'abc%s;'
>>
>> -- 
>> Qiangning Hong
>>
>> I'm usually annoyed by IDEs because, for instance, they don't use VIM
>> as an editor. Since I'm hooked to that, all IDEs I've used so far have
>> failed to impress me.
>>-- Sybren Stuvel @ c.l.python
>>
>> Get Firefox!
>> 
>>
> 


-- 
Qiangning Hong

I'm usually annoyed by IDEs because, for instance, they don't use VIM
as an editor. Since I'm hooked to that, all IDEs I've used so far have
failed to impress me.
-- Sybren Stuvel @ c.l.python

Get Firefox!

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


UCALC equivalent

2005-08-12 Thread Dark Cowherd
http://www.ucalc.com/mathparser/index.html

There is a great library called UCALC which allows you to set up an
expression and evaluate it
for e.g. you an define an expression by calling a function in UCALC
then call it with various values of x

for e.g. see this page
http://www.ucalc.com/mathparser/sample6.html


It is very fast. I have used it in VB when there is lot of number
crunching to be done.
Is there a Python equivalent.

I looked at numPy and SciPy sites (just skimmed through) did'nt seem
to have what I wanted.

Any pointers?


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


Re: How do these Java concepts translate to Python?

2005-08-12 Thread Steven Bethard
bruno modulix wrote:
>>but technically
>>speaking, there are no public, protected, or private things.
> 
> Yes there are:
> object.name is public
> object._name is protected
> object.__name is private

The double-underscore name-mangling is almost never worth it.  It's 
supposed to stop name collisions, but, while it does in some cases, it 
doesn't in all cases, so you shouldn't rely on this.  For example:

-- mod1.py --
class C(object):
 __x = 'mod1.C'
 @classmethod
 def getx(cls):
 return cls.__x
-

-- mod2.py --
import mod1
class C(mod1.C):
 __x = 'mod2.C'
-

py> import mod1, mod2
py> mod1.C.getx()
'mod1.C'
py> mod2.C.getx()
'mod2.C'

If double-underscore name-mangling worked like private variables, 
setting C.__x in mod2.C should not affect the value of C.__x in mod1.C.

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


How to build Python modules on windows?

2005-08-12 Thread .
Hi,

how can I build python modules on windows? I tried to build numarray[0] 
using Microsoft Visual C++ 2003 Toolkit, but got the following error:

---
error: Python was built with version 7.1 of Visual Studio, and 
extensions need to be built with the same version of the compiler, but 
it isn't installed.
---

So do I need to buy Visual Studio 7.1 to be able to build python modules 
on windows? That would explain why there are so few binary packages 
available. If this is true, has the python community considerred 
switching to compile the standard python distribution using the freely 
available compiler from Microsoft?

Thanks in advance for any hints!

Markus


[0]: I do not need to install numarray, but find a decent way to package 
and build self-made extensions and use numarray here as an example
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UCALC equivalent

2005-08-12 Thread Larry Bates
Python has built in eval function and doesn't require
a library.

Larry Bates

Dark Cowherd wrote:
> http://www.ucalc.com/mathparser/index.html
> 
> There is a great library called UCALC which allows you to set up an
> expression and evaluate it
> for e.g. you an define an expression by calling a function in UCALC
> then call it with various values of x
> 
> for e.g. see this page
> http://www.ucalc.com/mathparser/sample6.html
> 
> 
> It is very fast. I have used it in VB when there is lot of number
> crunching to be done.
> Is there a Python equivalent.
> 
> I looked at numPy and SciPy sites (just skimmed through) did'nt seem
> to have what I wanted.
> 
> Any pointers?
> 
> 

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


Re: __getattribute__ for class object

2005-08-12 Thread Steven Bethard
Dan wrote:
> Depending on what you want to do, it might be better to use properties
> instead:
> 
>   class Meta(type):
>  x = property(lambda klass: 'Called for '+str(klass))
> 
>   class Foo(object):
>  __metaclass__=Meta

Also worth noting that you can inline the metaclass if you don't need it 
anywhere else, e.g.:

class Foo(object):
 class __metaclass__(type):
 x = property(lambda klass: 'Called for '+str(klass))

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


Re: Supressing argument renaming in the Qt Designer -> pyuic workflow

2005-08-12 Thread Phil Thompson
On Thursday 11 August 2005 6:36 pm, Madhusudan Singh wrote:
> Hi
>
> Some of the functions I defined inside Qt Designer need to have some values
> passed to them.
>
> For instance :
>
> Code :
>
> void Form3::runningplot(n,plottitle,xname,x,y1name,y1,y2name,y2)
>
> is translated by pyuic to
>
> Python code :
>
> def runningplot(self,a0,a1,a2,a3,a4,a5,a6,a7):
>
> Now, while I understand that the first argument of the function has to be
> "self", the change in the names of the parameters in the function
> definition (and no corresponding change in the function body - which I
> would not expect anyways) messes up everything.
>
> Is there a way to tell pyuic to not translate plottitle -> a0, xname -> a1,
> etc., but keep the names as they are ?

No, there is no way to do this at the moment.

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


Re: Using globals with classes

2005-08-12 Thread Scott David Daniels
Madhusudan Singh wrote:
>  I am using qwtplot to display a running plot :
> 
> void Form3::runningplot(n,plottitle,xname,x,y1name,y1,y2name,y2)
> {
^^ I presume this is just some untranslated stuff ^^
> if n==1 :
> 
> plotkey1=self.runningqwtPlot.insertCurve(y1name,self.runningqwtPlot.xBottom,self.runningqwtPlot.yLeft)
> 
> plotkey2=self.runningqwtPlot.insertCurve(y2name,self.runningqwtPlot.xBottom,self.runningqwtPlot.yRight)
> self.runningqwtPlot.setTitle(plottitle)
> self.runningqwtPlot.setXGrid(True)
> self.runningqwtPlot.setAxisAutoScale(self.runningqwtPlot.yLeft)
> self.runningqwtPlot.setAxisAutoScale(self.runningqwtPlot.yRight)
> self.runningqwtPlot.setAxisAutoScale(self.runningqwtPlot.xBottom)
> self.runningqwtPlot.setAxisTitle(self.runningqwtPlot.yLeft,y1name)
> self.runningqwtPlot.setAxisTitle(self.runningqwtPlot.yRight,y2name)
> self.runningqwtPlot.setAxisTitle(self.runningqwtPlot.xBottom,xname)
> self.runningqwtPlot.setCurveData(plotkey1,x,y1,n)
> self.runningqwtPlot.setCurveData(plotkey2,x,y2,n)
> self.runningqwtPlot.replot()
> else :
>  self.runningqwtPlot.setCurveData(plotkey1,x,y1,n)
>  self.runningqwtPlot.setCurveData(plotkey2,x,y2,n)
>  self.runningqwtPlot.replot()
> }

The way I'd normally accomplish this is to separate the setup and use
by defining a class:

class CurvePlot(object):
 def __init__(self, plot, plottitle, xname, y1name, y2name,
  key1=None, key2=None):
 self.plot = plot
 if key1 is None:
 key1 = plot.insertCurve(y1name, plot.xBottom, plot.yLeft)
 self.key1 = key1
 if key2 is None:
 key2 = plot.insertCurve(y2name, plot.xBottom, plot.yRight)
 self.key2 = key2
 plot.setTitle(plottitle)
 plot.setXGrid(True)
 plot.setAxisAutoScale(plot.yLeft)
 plot.setAxisAutoScale(plot.yRight)
 plot.setAxisAutoScale(plot.xBottom)
 plot.setAxisTitle(plot.yLeft, y1name)
 plot.setAxisTitle(plot.yRight, y2name)
 plot.setAxisTitle(plot.xBottom, xname)

 def curve(self, x, y1, n)
 self.plot.setCurveData(self.key1, x, y1, n)
 self.plot.setCurveData(self.key2, x, y2, n)
 self.plot.replot()

And then calling it like:

 cplot = CurvePlot(self.runningqwtPlot, plottitle,
   xname, y1name, y2name)
 cplot.curve(n, x, y1, y2)

> I also have a global variable named "globaldebug" that when set to True,
> shows some diagnostic information as different slots are called. That too
> fails with the same error :
> 
> NameError: global name 'globaldebug' is not defined
What you probably don't understand is that "globals" are per-module, not
program-wide.  If you write a global from inside a function or method,
you need to declare "global varname" inside the function or method in
which you do the writing.  Simply using (reading) a global in a module
does not require the "global" declaration.

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


Re: How to build Python modules on windows?

2005-08-12 Thread Qiangning Hong
". <"@bag.python.org wrote:
> Hi,
> 
> how can I build python modules on windows? I tried to build numarray[0] 
> using Microsoft Visual C++ 2003 Toolkit, but got the following error:
> 
> ---
> error: Python was built with version 7.1 of Visual Studio, and 
> extensions need to be built with the same version of the compiler, but 
> it isn't installed.
> ---

Are you sure you have setup the environment variables before you build?

Here is a reference: "Building Python Extensions with the MS Toolkit
Compiler" (http://www.vrplumber.com/programming/mstoolkit/)

[snip]

-- 
Qiangning Hong

I'm usually annoyed by IDEs because, for instance, they don't use VIM
as an editor. Since I'm hooked to that, all IDEs I've used so far have
failed to impress me.
-- Sybren Stuvel @ c.l.python

Get Firefox!

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


Re: UCALC equivalent

2005-08-12 Thread max
Larry Bates <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Python has built in eval function and doesn't require
> a library.
> 
> Larry Bates
> 

Are you kidding? Read the original post a little more closely. The 
o.p. is looking for a library that evaluates mathematical expressions 
and is callable from python code.

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


Bug on Python2.3.4 [FreeBSD]?

2005-08-12 Thread Uwe Mayer


Hi,

AFAICT there seems to be a bug on FreeBSD's Python 2.3.4 open function. The
documentation states:

> Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+'
> truncates the file). Append 'b' to the mode to open the file in binary
> mode, on systems that differentiate between binary and text files (else it
> is ignored). If the file cannot be opened, IOError is raised.   

Consider:

$ cat test
lalala

$ python2.3
Python 2.3.4 (#2, Jan  4 2005, 04:42:43)
[GCC 2.95.4 20020320 [FreeBSD]] on freebsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('test', 'r+')
>>> f.read()
'lalala\n'
>>> f.write('testing')
>>> f.close()
>>>
[1]+  Stopped python2.3
$ cat test
lalala

-> write did not work; ok

$ fg
python2.3
>>> f = open('test', 'a+')
>>> f.read()
''

-> append mode does not read from file, *not ok*

>>> f = open('test', 'w+')
>>> f.read()
''
>>>
$ cat test

-> w+ truncated file, ok


Can anyone confirm that? Is there any other way of opening a file for
appending instead of a+? 

Thanks,
Ciao
Uwe

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


  1   2   >