Re: basic threading question

2007-10-31 Thread [david]
[EMAIL PROTECTED] wrote:
> On Oct 30, 7:58 pm, "bambam" <[EMAIL PROTECTED]> wrote:
>> Are function variables thread safe?
>>
>> def f(a):
>> # whatever
>> return float(a)
>>
>> Is that OK?
>>
>> def f(a):
>> #whatever
>> b=a:
>> #whatever:
>> return float(b)
>>
>> Is that OK?
>>
>> Steve.
> 
> Huh?
> 
If I have 37 threads, all calling a large function 'f', are the formal 
parameters thread safe?

That is, will the formal parameters be trashed?  Do you need to use 
locks or semaphores before using formal parameters? Are the labels for
formal parameters static?

If I have 73 threads, all calling a large function 'f', are the local 
values thread safe? Does each thread maintain it's own stack? Are the 
labels for local values stack-based?

Steve.

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


Re: Python Interview Questions

2007-10-31 Thread konryd

> - string building...do they use "+=" or do they build a list
>and use .join() to recombine them efficiently


I'm not dead sure about that, but I heard recently that python's been
optimized for that behaviour. That means: using += is almost as fast
as joining list. Besides, "+=" is more obvious than the other choice
and since performance is not a problem until it's a problem, I'd
rather use it. Anyway: I wouldn't pick it for an interview question.

regards
Konrad

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


Re: jpeg image read class

2007-10-31 Thread Marc 'BlackJack' Rintsch
On Wed, 31 Oct 2007 06:48:18 +, [EMAIL PROTECTED] wrote:

> i am new to python and PIL and was trying to write a class to read and
> write RGB color model jpeg images..

PIL already offers such a class.

> i came up with this class below..i want to know if this is the way to
> read/write the RGB color model jpeg..if anyone can give feedback (esp
> on the methods  writeImage1( )  and writeImage2( )   it wd help my
> studies ..

Those are bad names.  What does 1 and 2 mean in them!?

> class JPGFile:
>   def __init__(self,filename):
>   self._filename=filename
>   self._height=0
>   self._width=0
>   self._mode=""

This will always be 'RGB' so why store it?

>   self._rgblist=[]
>   self._pixellist=[]
>   self._pixarray=None

In the end you store the image *three times* in different representations.
Is that really necessary?

>   self.readImage()

Is `readImage()` supposed to be called again later?  If not you might add
an underscore in front and give the file name as argument.  Then you could
drop `self._filename`.

>   def getheight(self):
>   return self._height
>   def getwidth(self):
>   return self._width
> 
>   def getpixellist(self):
>   return self._pixellist
> 
>   def getrgblist(self):
>   return self._rgblist

Maybe get rid of those trivial getters and the underscore in front of the
names.  That's a little "unpythonic".  Do a web search for "Python is not
Java".

>   def makepixval(self,(r,g,b)):
>   alpha=255
>   pixval=(alpha<<24)|(r<<16 )|( g<<8) | b
>   return pixval

Looks like an ordinary function to me.  `self` is not used.

>   def readImage(self):
>   im=Image.open(self._filename)
>   self._mode=im.mode
>   self._width,self._height=im.size
>   for y in range(self._height):
>   for x in range(self._width):
>   r,g,b=im.getpixel((x,y))
>   self._rgblist.append((r,g,b))
>   pval=self.makepixval((r,g,b))
>   self._pixellist.append(pval)
>   self._pixarray=array(self._pixellist,float)

Iterating over `im.getdata()` should be simpler and faster than the nested
loops.

>   def makergb(self,pixval):
>   alpha=pixval>>24
>   red=(pixval>>16 )&255
>   green=(pixval>>8 )&255
>   blue=(pixval)& 255
>   return red,green,blue

Again a simple function.

>   def writeImage1(self,fname,data,width,height):
>   imnew=Image.new(self._mode,(width,height))
>   newrgblist=[]
>   for i in range(len(data)):
>   r,g,b=self.makergb(data[i])
>   newrgblist.append((r,g,b))

If you have ``for i in range(len(something)):`` you almost always really
wanted to iterate over `something` directly.  That loop can be written as:

for pixval in data:
rgb = pixval2rgb(pixval)
rgbs.append(rgb)

Or even shorter in one line:

rgbs = map(pixval2rgb, data)

If the `numpy` array is what you want/need it might be more efficient to do
the RGB to "pixval" conversion with `numpy`.  It should be faster to shift
and "or" a whole array instead of every pixel one by one in pure Python.

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


Re: Readline and record separator

2007-10-31 Thread Johny
On Oct 30, 8:44 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Johny a écrit :
>
> > Is it possible to change record separator when using readline?
> > As far as I know readline reads characters until found '\n' and it is
> > the end of record for readline.
>
> This is not a "record" separator, but a newline. As the name implies,
> file.readline is about reading a text file line by line. For a
> definition of "line" being : "a chuk of text that starts either at the
> beginning of the document or after a newline" and for a definition of
> "newline" being "a platform-specific character or character sequence".
>
> > My problem is that my record consits several '\n' and when I use
> > readline it does NOT read the whole my record.
> > So If I could change '\n' as  a record separator for readline, it
> > would solve my problem.
> > Any idea?
>
> If you're dealing with (so-called) CSV files, you might want to have a
> look at the (oh surprise) CSV module (in the stdlib) instead.
>
> HTH

Bruno,
Thank you for your hint, but can you please be more specific when
saying
"look at the (oh surprise) CSV module (in the stdlib)" ?
Thanks
L

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

Re: object inheritance

2007-10-31 Thread praddy
On Oct 31, 8:26 am, Anand <[EMAIL PROTECTED]> wrote:
> On Oct 28, 1:16 am, Pradeep Jindal <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Friday 26 Oct 2007 6:21:57 pm Anand wrote:
>
> > > On Oct 26, 5:31 pm, "Pradeep Jindal" <[EMAIL PROTECTED]> wrote:
> > > > Can you tell any specific use case for doing this?
>
> > > I have many implementaions of a db interface.
>
> > > SimpleDB - simple implementation
> > > BetterDB - optimized implementation
> > > CachedDB - an implementation with caching of queries
> > > RestrictedDB - implementation with permissions
>
> > > Now, I want to combine these implementations and use.
> > > Typical use case scenarios are:
>
> > > db = RestrictedDB(CachedDB(SimpleDB()))
> > > db = RestrictedDB(SimpleDB())
> > > db = RestrictedDB(BetterDB())
> > > db = RestrictedDB(CachedDB(BetterDB())
> > > db = CachedDB(SimpleDB())
> > > etc..
>
> > I agree with Duncan. According to me, this should be called Delegation 
> > rather
> > than inheritance. And delegation should work without any conflicts of
> > identifier names and all that. I think, it should be all about several
> > objects implementing a protocol (interface) and that should work cleanly.
>
> I don't think so. It is not as simple as delegation.
>
> In the example that I gave previously, call to self.say in A.foo
> calls B.say not A.say, which I think is not possible with delegation.

Let me explain what I meant, its all about several objects (e.g. "a")
implementing a protocol, in your case the "say" method, and some
object (e.g. "b") extending those objects by adding some more
functionality but requiring that those objects, that it extends from,
follow a specific protocol ("a" must have say method). Also note that,
"B" or "b" is partial implementation of what its meant for, I mean,
calling "b"'s "say" will not work if "b" has not yet extended from "a"
or any other object implementing the same protocol.

Less time, can't get into more details. Bye for now.

Thanks
-Pradeep

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


Re: basic threading question

2007-10-31 Thread Bryan Olson
[david] wrote:
> If I have 37 threads, all calling a large function 'f', are the formal 
> parameters thread safe?
> 
> That is, will the formal parameters be trashed?  Do you need to use 
> locks or semaphores before using formal parameters? Are the labels for
> formal parameters static?
> 
> If I have 73 threads, all calling a large function 'f', are the local 
> values thread safe? Does each thread maintain it's own stack? Are the 
> labels for local values stack-based?

Yes. Each thread has its own stack, and that's where the parameter
bindings live.

Of course if you pass the same mutable object in multiple threads,
that's a different issue.


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


dynamically generating temporary files through python/cgi

2007-10-31 Thread Miss Pfeffe
How do you make a python out of a banana?!-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Readline and record separator

2007-10-31 Thread Bruno Desthuilliers
Johny a écrit :
> On Oct 30, 8:44 pm, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
>> Johny a écrit :
>>
>>> Is it possible to change record separator when using readline?
>>> As far as I know readline reads characters until found '\n' and it is
>>> the end of record for readline.
>> This is not a "record" separator, but a newline. As the name implies,
>> file.readline is about reading a text file line by line. For a
>> definition of "line" being : "a chuk of text that starts either at the
>> beginning of the document or after a newline" and for a definition of
>> "newline" being "a platform-specific character or character sequence".
>>
>>> My problem is that my record consits several '\n' and when I use
>>> readline it does NOT read the whole my record.
>>> So If I could change '\n' as  a record separator for readline, it
>>> would solve my problem.
>>> Any idea?
>> If you're dealing with (so-called) CSV files, you might want to have a
>> look at the (oh surprise) CSV module (in the stdlib) instead.
>>
>> HTH
> 
> Bruno,
> Thank you for your hint, but can you please be more specific when
> saying
> "look at the (oh surprise) CSV module (in the stdlib)" ?

You used the term "record" instead of "line", which is to me a clear 
indication that you're not using the appropriate tools here. If your 
file is a (so-called) CSV[1] file, there's a module for this (named 
'csv') in the standard lib.

And even if your file format is not CSV-compatible, there may be some 
answers to your problem in this module's source code (hint : one of 
these answers is "don't use line-oriented APIs when not appropriate").


[1] Coma Separated Values - but the separator can be almost anything.

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


Re: why did these companies choose Tcl over Python

2007-10-31 Thread Eddie Corns
chewie54 <[EMAIL PROTECTED]> writes:

>Hello,

>As an electronics engineer I use some very expensive EDA CAD tool
>programs that are scriptable using Tcl.  I was wondering why these
>companies have choose to use Tcl instead of Python.   Some of these
>are:

>   Mentor Graphics ModelTech VHDL and Verilog simulator
>   Synopsys  Design Compiler and Primetime Static Timing Analyzer
>   Actel FPGA tools.

>Tcl seems to very popular in my business as the scripting language of
>choice.

>I'm in the process of deciding to use Tcl or Python for a CAD tool
>program that I have been working on.Most of the core of the
>program,  the database,   will be done is C as an extension to either
>Tcl or Python,   but I intend to use Tk or wxPthon for the GUI.   I do
>need publishing quality outputs from drawings done on a graphics
>device that are scaled to standard printer paper sizes.


>I would prefer to use Python but can't deny how popular Tcl is,  as
>mentioned above,  so my question is why wasn't Python selected by
>these companies as the choice of scripting languages for their
>product?

Having abandoned TCL for Python years ago, my thought is:

If you expect your users to write (and maintain) large scripts - have mercy on
them and don't give them TCL.

For larger programs/scripts having proper data structures, readable syntax,
etc. is a very significant factor.  (Of course TCL may have improved beyond
all recognition since I last used it).  Try putting together some sample
scripts in both languages and see how easily others can understand them (and
yourself in a few months).

When I want something nimbler than Python I use Lua.

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


Re: Python and SQLite release cycles

2007-10-31 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Hi,
> 
> Official Python distro is very stable, with release cycle of around 1
> year. However, to include the new version of SQLite, which has a much
> shorter release cycle, one has to rebuild the main Python distribution
> (to compile with the new SQLite headers) - this is from Python docs.
> Therefore, inclusion of PySQLite in Python-2.5.1 distro effectively
> shrinks the Python release cycle to that of SQLite. I would not have
> minded, except that we have many workstations and pretty arcane
> deployment procedure, making frequent redeployment of Python quite
> painful.
> Has anyone considered this problem and maybe a work-around?

I think you misrepresent horse and rider here: python release cycles are
independent of SQLites. I'm pretty sure they might contain new versions if
these are API-compatible (remember, python's shipped SQLite won't be
allowed to break existing stuff).

In all cases, you can decouple them easily (the same way with element-tree):
just install sqlite explicitly as a module. It's under a different name
(not sure which right out of my head), so they don't conflict.

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


Re: setting variables in outer functions

2007-10-31 Thread Dustan
On Oct 30, 11:29 am, Duncan Booth <[EMAIL PROTECTED]>
wrote:
> Neil Cerutti <[EMAIL PROTECTED]> wrote:
> > It's allows a standard programming idiom which provides a
> > primitive form of object oriented programming using closures to
> > represent state.
>
> > def account(opening_balance):
> >   balance = opening_balance
> >   def get_balance():
> > nonlocal balance
> > return balance
> >   def post_transaction(x):
> > nonlocal balance
> > balance += x
> >   return balance, post_transaction
>
> > fred_balance, fred_post = account(1500)
> > joe_balance, joe_post = account(12)
> > fred_post(20)
> > joe_post(-10)
> > fred_balance()
>
> TypeError: 'int' object is not callable
>
> > 1520
> > joe_balance()
>
> TypeError: 'int' object is not callable
>
> > 2
>
> > Python classes will of course nearly always win, though the idiom
> > looks like it might be faster (I don't have Python 3000 to try it
> > out).
>
> Python classes might be less error prone.

Why would using classes make your code any less prone to typographical
errors?

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


help with pyparsing

2007-10-31 Thread Neal Becker
I'm just trying out pyparsing.  I get stack overflow on my first try.  Any
help?

#/usr/bin/python

from pyparsing import Word, alphas, QuotedString, OneOrMore, delimitedList

first_line = '[' + delimitedList (QuotedString) + ']'

def main():
string = '''[ 'a', 'b', 'cdef']'''
greeting = first_line.parseString (string)
print greeting

if __name__ == "__main__":
main()

/usr/lib/python2.5/site-packages/pyparsing.py:2727: SyntaxWarning: Cannot
add element of type  to ParserElement
  return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
/usr/lib/python2.5/site-packages/pyparsing.py:1008: SyntaxWarning: Cannot
add element of type  to ParserElement
  return other + self
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/tmp/python-k3AVeY.py", line 5, in 
first_line = '[' + delimitedList (QuotedString) + ']'
  File "/usr/lib/python2.5/site-packages/pyparsing.py", line 2727, in
delimitedList
return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
  File "/usr/lib/python2.5/site-packages/pyparsing.py", line 1008, in
__radd__
return other + self
  File "/usr/lib/python2.5/site-packages/pyparsing.py", line 1008, in
__radd__
return other + self


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


py2exe (or other exe builder) on Vista system for Vista/XP install targets.

2007-10-31 Thread Michael
I'm trying to build a exe on a vista system using py2exe. It will
deploy to vista and XP systems. If it matters, the application uses
pyserial, as well. I have VS Studio 2005 installed on this laptop as
well. I've found this so far that seems to be identical to what I'm
seeing (for non-python programs): 
http://www.thescripts.com/forum/thread611031.html

When I attempt to run, I get "The procedure entry point
_except_handler4_common could not be located in the dynamic link
library mscvrt.dll."  Apparently vista has one more
_except_handler#_common function than XP does.

I've used py2exe several times before (however not recenty, as it was
before Vista came out). I'm using a very basic setup file right now:
from distutils.core import setup
import py2exe

setup(console=['responderbot.py'])

Are there any ways to either py2exe work or any other exe builder for
my build environment and deployment scenario? I don't really want to
dig around in py2exe/pyserial internals to force it to use the dll's
that the MS support person said it should be using. Will any automated
exe builder work where I am?

I've heard IronPython can compile down to an exeis it a valid
alternative? Should my CPython utility be compatible with ipy? I only
use the random,time,sys, and serial modules. I really know very little
about ipy.

  --Michael

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


Re: setting variables in outer functions

2007-10-31 Thread Duncan Booth
Dustan <[EMAIL PROTECTED]> wrote:

> On Oct 30, 11:29 am, Duncan Booth <[EMAIL PROTECTED]>
> wrote:
>> Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> > It's allows a standard programming idiom which provides a
>> > primitive form of object oriented programming using closures to
>> > represent state.
>>
>> > def account(opening_balance):
>> >   balance = opening_balance
>> >   def get_balance():
>> > nonlocal balance
>> > return balance
>> >   def post_transaction(x):
>> > nonlocal balance
>> > balance += x
>> >   return balance, post_transaction
>>
>> > fred_balance, fred_post = account(1500)
>> > joe_balance, joe_post = account(12)
>> > fred_post(20)
>> > joe_post(-10)
>> > fred_balance()
>>
>> TypeError: 'int' object is not callable
>>
>> > 1520
>> > joe_balance()
>>
>> TypeError: 'int' object is not callable
>>
>> > 2
>>
>> > Python classes will of course nearly always win, though the idiom
>> > looks like it might be faster (I don't have Python 3000 to try it
>> > out).
>>
>> Python classes might be less error prone.
> 
> Why would using classes make your code any less prone to typographical
> errors?
> 
> 
Lots of reasons: shorter and clearer code being high on the list. The 
class equivalent would be:


>>> class Account(object):
   def __init__(self, opening_balance):
   self.balance = opening_balance

   def post_transaction(self, x):
self.balance += x


>>> fred = Account(1500)
>>> joe = Account(12)
>>> fred.post_transaction(20)
>>> joe.post_transaction(-10)
>>> fred.balance
1520
>>> joe.balance
2

There is no scope for the particular error I highlighted: you no longer 
have the duplication of declaring the functions and then returning them.
Also you don't need the accessor function at all (and if at some point 
in the future you do want it you can make it a property).

You don't have to invent separate names for each of the returned 
functions: the dot notation suddenly makes that a no brainer.

Also the class is easier to extend: you no longer have to find and 
change every call to account() if you want to add another method: just 
add it.

BTW, I put both the original code with corrections, and the class 
version into a file and timed them running with Python 3 alpha 1, the 
nested scope version is slightly faster: 5.03usec per loop against 
5.77usec for the class version, but minor changes to the code can skew 
the result either way (put in more attribute accesses and the class 
wins, add in more method calls and the function wins).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a temporary file in Python

2007-10-31 Thread Diez B. Roggisch
looping wrote:

> Hi,
> 
> I want to create a temporary file, read it in an external command and
> finally delete it (in Windows XP).
> 
> I try to use tempfile module but it doesn't work, the file couldn't be
> open by my other process (error like: SP2-0310: unable to open file "c:
> \docume~1\looping\locals~1\temp\tmpau81-s.sql")
> Is there a way to make it work or I have to manually manage
> everything ?
> 
> My non working code:
> 
> f = tempfile.NamedTemporaryFile(suffix='.sql')
> f.write(txt)
> f.flush()
> p = subprocess.Popen([SQL_PLUS, '-s', dsn, '@', SQL_PLUS_SCRIPT,
> f.name],
>   stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
> p.wait()
> f.close()

I'm not an expert, but I think you need to close the file first - you under
windows here, which can be picky about such stuff AFAIK. Or maybe there is
some other mode-specifier.

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


Creating a temporary file in Python

2007-10-31 Thread looping
Hi,

I want to create a temporary file, read it in an external command and
finally delete it (in Windows XP).

I try to use tempfile module but it doesn't work, the file couldn't be
open by my other process (error like: SP2-0310: unable to open file "c:
\docume~1\looping\locals~1\temp\tmpau81-s.sql")
Is there a way to make it work or I have to manually manage
everything ?

My non working code:

f = tempfile.NamedTemporaryFile(suffix='.sql')
f.write(txt)
f.flush()
p = subprocess.Popen([SQL_PLUS, '-s', dsn, '@', SQL_PLUS_SCRIPT,
f.name],
  stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p.wait()
f.close()

Thanks for your help.

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


Re: A Python 3000 Question

2007-10-31 Thread Neil Cerutti
On 2007-10-30, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Tue, 30 Oct 2007 15:25:54 GMT, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>>On 2007-10-30, Eduardo O. Padoan <[EMAIL PROTECTED]> wrote:
>>> This is a FAQ:
>>> http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm
>>
>>Holy Airy Persiflage Batman!
>>
>>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] 
>>on
>>win32
>>Type "help", "copyright", "credits" or "license" for more information.
> import timeit
> timeit.Timer('len(seq)', 'seq = range(100)').timeit()
>>0.20332271187463391
> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
>>0.48545737364457864
>
> Not sure what you're trying to demonstrate.  

That len as a builtin can be faster than len as an attribute, and
doesn't need any further explanation than that.

> Here's another pointless transcript, though:
>
> [EMAIL PROTECTED]:~$ python -m timeit -s '
> seq = range(100)
> ' 'len(seq)'
> 100 loops, best of 3: 0.211 usec per loop
> [EMAIL PROTECTED]:~$ python -m timeit -s '
> seq = range(100)
> ' 'seq.__len__()'
> 100 loops, best of 3: 0.317 usec per loop
> [EMAIL PROTECTED]:~$ python -m timeit -s '
> class X(object):
>   def __len__(self): return 100
> seq = X()
> ' 'seq.__len__()'
> 100 loops, best of 3: 0.427 usec per loop
> [EMAIL PROTECTED]:~$ python -m timeit -s '
> class X(object):
>   def __len__(self): return 100
> seq = X()
> ' 'len(seq)'
> 100 loops, best of 3: 0.701 usec per loop
> [EMAIL PROTECTED]:~$
>
> I guess we've learned that sometimes something is faster than
> something else, and other times the contrary.

It demonstratess that len is faster than __len__ for lists (and
probably for all builtin types) but not for user defined type X
(and probably not for any user defined type).

Or it may demonstrate that I'm all wet. If so, I've brought my
shampoo.

But if I'm wrong about the performance benefits then I guess I'm
still in the dark about why len is a builtin. The only compelling
thing in the linked explation was the signatures of the guys who
wrote the artible. (Guido does admit he would, "hate to lose it
as a builtin," but doesn't explain why that should be a bad
thing).

-- 
Neil Cerutti
It isn't pollution that is hurting the environment; it's the impurities in our
air and water that are doing it. --Dan Quayle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Python 3000 Question

2007-10-31 Thread Neil Cerutti
On 2007-10-30, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Oct 30, 11:25 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> On 2007-10-30, Eduardo O. Padoan <[EMAIL PROTECTED]> wrote:
>>
>> > This is a FAQ:
>> >http://effbot.org/pyfaq/why-does-python-use-methods-for-some-function...
>>
>> Holy Airy Persiflage Batman!
>>
>> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] 
>> on
>> win32
>> Type "help", "copyright", "credits" or "license" for more information.>>> 
>> import timeit
>> >>> timeit.Timer('len(seq)', 'seq = range(100)').timeit()
>> 0.20332271187463391
>> >>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
>>
>> 0.48545737364457864
>
> Common mistake; try this instead:
>
> timeit.Timer('seqlen()',
>  'seq = range(100); seqlen=seq.__len__').timeit()

Why would I want to do that?

-- 
Neil Cerutti
These people haven't seen the last of my face. If I go down, I'm going down
standing up. --Chuck Person
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a temporary file in Python

2007-10-31 Thread looping
On Oct 31, 2:16 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

> I'm not an expert, but I think you need to close the file first - you under
> windows here, which can be picky about such stuff AFAIK. Or maybe there is
> some other mode-specifier.
>
> Diez

Actually closing the file delete it without any chance to use it...

Well I changed my code this way:

filename = tempfile.mktemp(suffix='.sql')
f = open(filename, 'wb')
try:
f.write(txt.encode('cp1252'))
f.close()
p = Popen([SQL_PLUS, '-s', dsn,
'@', SQL_PLUS_SCRIPT, f.name],
stdout=PIPE, stderr=STDOUT)
p.wait()
finally:
os.remove(filename)

I understand the security issues of temporary file (as explained in
Python doc) but maybe standard lib need a NamedTemporaryFile that
could be used by another process.

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


Re: A Python 3000 Question

2007-10-31 Thread George Sakkis
On Oct 31, 8:44 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-10-30, George Sakkis <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Oct 30, 11:25 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> >> On 2007-10-30, Eduardo O. Padoan <[EMAIL PROTECTED]> wrote:
>
> >> > This is a FAQ:
> >> >http://effbot.org/pyfaq/why-does-python-use-methods-for-some-function...
>
> >> Holy Airy Persiflage Batman!
>
> >> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
> >> (Intel)] on
> >> win32
> >> Type "help", "copyright", "credits" or "license" for more information.>>> 
> >> import timeit
> >> >>> timeit.Timer('len(seq)', 'seq = range(100)').timeit()
> >> 0.20332271187463391
> >> >>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
>
> >> 0.48545737364457864
>
> > Common mistake; try this instead:
>
> > timeit.Timer('seqlen()',
> >  'seq = range(100); seqlen=seq.__len__').timeit()
>
> Why would I want to do that?


To realize that __len__ is actually faster than len in this case; your
second timing is dominated by the time to do attribute lookup.


George

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


Re: Creating a temporary file in Python

2007-10-31 Thread Diez B. Roggisch
looping wrote:

> On Oct 31, 2:16 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> 
>> I'm not an expert, but I think you need to close the file first - you
>> under windows here, which can be picky about such stuff AFAIK. Or maybe
>> there is some other mode-specifier.
>>
>> Diez
> 
> Actually closing the file delete it without any chance to use it...
> 
> Well I changed my code this way:
> 
> filename = tempfile.mktemp(suffix='.sql')
> f = open(filename, 'wb')
> try:
> f.write(txt.encode('cp1252'))
> f.close()
> p = Popen([SQL_PLUS, '-s', dsn,
> '@', SQL_PLUS_SCRIPT, f.name],
> stdout=PIPE, stderr=STDOUT)
> p.wait()
> finally:
> os.remove(filename)
> 
> I understand the security issues of temporary file (as explained in
> Python doc) but maybe standard lib need a NamedTemporaryFile that
> could be used by another process.

As I said: that most likely is a limitation of your operating system, not
Python.

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


Re: py2exe (or other exe builder) on Vista system for Vista/XP install targets.

2007-10-31 Thread Bjoern Schliessmann
Michael wrote:
[py2exe on Vista and XP]
> When I attempt to run, I get "The procedure entry point
> _except_handler4_common could not be located in the dynamic link
> library mscvrt.dll."  Apparently vista has one more
> _except_handler#_common function than XP does.

Strange -- it works for me. I compile in Vista and deploy in Vista
and XP (SP2). I'm using Twisted 2.5 and wxWidgets 2.8.

I'm sorry that I cannot help more. I dropped py2exe recently because
I had a similar missing symbol problem with a Windows 2000
computer; so I installed Python and the modules directly on all my
machines.
 
Regards,


Björn

-- 
BOFH excuse #223:

The lines are all busy (busied out, that is -- why let them in to
begin with?).

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


Re: Creating a temporary file in Python

2007-10-31 Thread Sion Arrowsmith
looping  <[EMAIL PROTECTED]> wrote:
>I want to create a temporary file, read it in an external command and
>finally delete it (in Windows XP).
>
>I try to use tempfile module but it doesn't work, the file couldn't be
>open by my other process (error like: SP2-0310: unable to open file "c:
>\docume~1\looping\locals~1\temp\tmpau81-s.sql")

You're using NamedTemporaryFile. The tempfile documentation
(http://docs.python.org/lib/module-tempfile.html) says:

" [ ... ] Whether the name can be used to open the file a second time,
while the named temporary file is still open, varies across platforms
(it can be so used on Unix; it cannot on Windows NT or later)."

You probably want to use tempfile.mkstemp and explicitly close
(before running the external command) and delete it.

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

Re: marshal vs pickle

2007-10-31 Thread Bjoern Schliessmann
Evan Klitzke wrote:
> Can anyone elaborate more on the difference between marshal and
> pickle. In what conditions would using marshal be unsafe? If one
> can guarantee that the marshalled objects would be created and
> read by the same version of Python, is that enough?

Just use pickle. From the docs:

| The marshal module exists mainly to support reading and writing
| the ``pseudo-compiled'' code for Python modules of .pyc files.
| Therefore, the Python maintainers reserve the right to modify the
| marshal format in backward incompatible ways should the need
| arise. If you're serializing and de-serializing Python objects,
| use the pickle module instead. 
 
Regards,


Björn

-- 
BOFH excuse #421:

Domain controller not responding

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


Re: marshal vs pickle

2007-10-31 Thread Aaron Watters
On Oct 31, 3:31 am, "Evan Klitzke" <[EMAIL PROTECTED]> wrote:
> Can anyone elaborate more on the difference between marshal and
> pickle. In what conditions would using marshal be unsafe? If one can
> guarantee that the marshalled objects would be created and read by the
> same version of Python, is that enough?

Yes, I think that's enough.  I like to use
marshal a lot because it's the absolutely fastest
way to store and load data to/from Python. Furthermore
because marshal is "stupid" the programmer has complete
control.  A lot of the overhead you get with the
pickles which make them generally much slower than
marshal come from the cleverness by which pickle will
recognized shared objects and all that junk.  When I
serialize, I generally don't need
that because I know what I'm doing.

For example both gadfly SQL

   http://gadfly.sourceforge.net

and nucular full text/fielded search

   http://nucular.sourceforge.net

use marshal as the underlying serializer.  Using cPickle
would probably make serialization worse than 2x slower.
This is one of the 2 or 3 key tricks which make these
packages as fast as they are.

   -- Aaron Watters

===
http://www.xfeedme.com/nucular/gut.py/go?FREETEXT=halloween

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


Re: python in academics?

2007-10-31 Thread Floris Bruynooghe
On Oct 30, 3:39 am, sandipm <[EMAIL PROTECTED]> wrote:
> seeing posts from students on group. I am curious to know, Do they
> teach python in academic courses in universities?

In Southampton Uni (UK) they do teach (some) Python to Engineering
undergrads (aero, mech, ship, maybe more) thanks to one lecturer
pushing it afaik.

Regards
Floris

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


Re: A Python 3000 Question

2007-10-31 Thread Duncan Booth
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> But if I'm wrong about the performance benefits then I guess I'm
> still in the dark about why len is a builtin. The only compelling
> thing in the linked explation was the signatures of the guys who
> wrote the artible. (Guido does admit he would, "hate to lose it
> as a builtin," but doesn't explain why that should be a bad
> thing).

With most of the builtin functions there is an advantage since they wrap 
a bit of extra logic round the implementation: e.g. getattr hooks to 
__getattr__ or __getattribute__.

With len that doesn't really apply, as the only extra logic seems fairly 
pointless: sequences and mappings implement length differently so you 
could have a type which acts as both and returns different lengths for 
each. Also the result returned from __len__ is cast from a Python object 
to a C value and back again so you can't return a length which is too 
large to convert.

The main benefit that I can think of is that it avoids namespace 
pollution: most Python special methods (the ones you aren't supposed to 
call directly) have the double-underscores flagging them as separate 
from user methods. This is a good thing: you can create a class which 
acts like a builtin sequence, but which has any attributes you fancy: 
the obvious example being the classic "it's a tuple but all the elements 
are also accessible as attributes" returned from time.localtime(), 
os.stat(). Try this in a language like Javascript and nasty things 
happen when your attribute names clash with internal attribute names.

So that's my conclusion: it is a builtin function rather than a method 
in order to avoid polluting the user attribute space of user-defined 
classes.

Obviously it isn't an absolute thing: lists and dictionaries do have 
other methods in the user namespace, so the decision to keep len out of 
that namespace is partly a judgement call, and partly historical (I 
think tuples didn't used to have any methods at all).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Python 3000 Question

2007-10-31 Thread Neil Cerutti
On 2007-10-31, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Oct 31, 8:44 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> On 2007-10-30, George Sakkis <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>> > On Oct 30, 11:25 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> >> On 2007-10-30, Eduardo O. Padoan <[EMAIL PROTECTED]> wrote:
>>
>> >> > This is a FAQ:
>> >> >http://effbot.org/pyfaq/why-does-python-use-methods-for-some-function...
>>
>> >> Holy Airy Persiflage Batman!
>>
>> >> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
>> >> (Intel)] on
>> >> win32
>> >> Type "help", "copyright", "credits" or "license" for more information.>>> 
>> >> import timeit
>> >> >>> timeit.Timer('len(seq)', 'seq = range(100)').timeit()
>> >> 0.20332271187463391
>> >> >>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
>>
>> >> 0.48545737364457864
>>
>> > Common mistake; try this instead:
>>
>> > timeit.Timer('seqlen()',
>> >  'seq = range(100); seqlen=seq.__len__').timeit()
>>
>> Why would I want to do that?
>
> To realize that __len__ is actually faster than len in this
> case; your second timing is dominated by the time to do
> attribute lookup.

I knew that going in. Making len a builtin saves us from writing
our own seqlen functions. ;)

-- 
Neil Cerutti
He's a guy who gets up at six o'clock in the morning regardless of what time
it is. --Lou Duva
-- 
http://mail.python.org/mailman/listinfo/python-list


Namespace question

2007-10-31 Thread Frank Aune
Hello,

Is it possible writing custom modules named the same as modules in the 
standard library, which in turn use the same module from the standard 
library?

Say I want my application to have a random.py module, which in turn must 
import the standard library random.py module also, to get hold of the randint 
function for example.

My attempts so far only causes my random.py to import itself instead of the 
standard library random.py

Receipt for disaster? :)



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


Re: A Python 3000 Question

2007-10-31 Thread Neil Cerutti
On 2007-10-31, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Obviously it isn't an absolute thing: lists and dictionaries do
> have other methods in the user namespace, so the decision to
> keep len out of that namespace is partly a judgement call, and
> partly historical (I think tuples didn't used to have any
> methods at all).

Thanks for the interesting note. I didn't know that tuples
originally had no methods. That made len mandatory, I suppose.

-- 
Neil Cerutti
The Pastor would appreciate it if the ladies of the congregation would lend
him their electric girdles for the pancake breakfast next Sunday morning.
--Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread jelle
the subject pretty much says it all.
if I check a string for for a substring, and this substring isn't found, 
should't the .find method return 0 rather than -1?
this breaks the 

if check.find('something'):
do(somethingElse)

idiom, which is a bit of a pity I think.

cheers,

-jelle

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


Fwd: Namespace question

2007-10-31 Thread Andrii V. Mishkovskyi
2007/10/31, Frank Aune <[EMAIL PROTECTED]>:
> Hello,
>
> Is it possible writing custom modules named the same as modules in the
> standard library, which in turn use the same module from the standard
> library?
>
> Say I want my application to have a random.py module, which in turn must
> import the standard library random.py module also, to get hold of the randint
> function for example.
>
> My attempts so far only causes my random.py to import itself instead of the
> standard library random.py
>
> Receipt for disaster? :)

You mean something like this:

>>>import random
>>>def foo():
...print '42'
>>>random.randit = foo
>>>random.randit()
42

am I right?
--
Wbr, Andrii Mishkovskyi.

He's got a heart of a little child, and he keeps it in a jar on his desk.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: _tkinter installation in python 2.5 on mandriva with a default 2.4

2007-10-31 Thread Martin v. Löwis
> however make still complains of the non existance of the the Tcl/Tk
> libs and/or headers

So where it tk.h located?

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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Martin Marcher
2007/10/31, jelle <[EMAIL PROTECTED]>:
> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found,
> should't the .find method return 0 rather than -1?
> this breaks the

IMHO "0" would mean the substring starts at index 0 of the iterable.

If that changes it should return "None" in python instead of a int anyway, no?

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Andrii V. Mishkovskyi
2007/10/31, jelle <[EMAIL PROTECTED]>:
> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found,
> should't the .find method return 0 rather than -1?
> this breaks the
>
> if check.find('something'):
> do(somethingElse)
>
> idiom, which is a bit of a pity I think.
>
> cheers,
>
> -jelle
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

'foo'.find('f') returns 0

What's your point? :/
-- 
Wbr, Andrii Mishkovskyi.

He's got a heart of a little child, and he keeps it in a jar on his desk.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread jelle feringa
>
> What's your point? :/


that of making sure before you post and cause public emberassement?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Interview Questions

2007-10-31 Thread Steven Bethard
konryd wrote:
>> - string building...do they use "+=" or do they build a list
>>and use .join() to recombine them efficiently
> 
> 
> I'm not dead sure about that, but I heard recently that python's been
> optimized for that behaviour. That means: using += is almost as fast
> as joining list.

For some simple cases, this is true.  But it only works in CPython, not 
say Jython.  So it's a better practice to continue using .join().

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


Re: A Python 3000 Question

2007-10-31 Thread Duncan Booth
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> On 2007-10-31, Duncan Booth <[EMAIL PROTECTED]> wrote:
>> Obviously it isn't an absolute thing: lists and dictionaries do
>> have other methods in the user namespace, so the decision to
>> keep len out of that namespace is partly a judgement call, and
>> partly historical (I think tuples didn't used to have any
>> methods at all).
> 
> Thanks for the interesting note. I didn't know that tuples
> originally had no methods. That made len mandatory, I suppose.
> 
Only if you think tuples are a sequence rather than a record. :)

Come to think of it, strings didn't have methods either, so len needed to 
be a function to get the length of a string.

I'm not sure when tuples sprouted methods. Strings grew methods in 1.6, but 
I think numbers and tuples may not have got any methods until the 
introduction of new-style classes (Python 2.2)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Luis Zarrabeitia

> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found, 
> should't the .find method return 0 rather than -1?

I belive str.find should return the first position where the substring appears.
If "string".find("ugh") were to return 0, how would you differentiate from
"ugh".find("ugh")? That one *should* return 0.


> this breaks the 
> 
> if check.find('something'):
> do(somethingElse)
> 
> idiom, which is a bit of a pity I think.

It breaks the idiom because you are speaking the wrong language.

You should be doing:

if "something" in "string":
do(something())

wich is clearer IMHO.
 
> cheers,
> 
> -jelle

See ya,

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

 


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

--
"Al mundo nuevo corresponde la Universidad nueva"
UNIVERSIDAD DE LA HABANA
280 aniversario 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why did these companies choose Tcl over Python

2007-10-31 Thread Roy Smith
chewie54 <[EMAIL PROTECTED]> wrote:

> I would prefer to use Python but can't deny how popular Tcl is,  as
> mentioned above,  so my question is why wasn't Python selected by
> these companies as the choice of scripting languages for their
> product?
> 
> Are there any obvious advantages like:
> 
> performance,
> memory footprint,
> better cross-platform support,
> ease of use,

I used to work on a project which was written mostly in Tcl.  Not a huge 
project, but not a trivial one either.  Perhaps a few 10's of KLOC over 100 
Tcl source files.  The domain was network monitoring using SNMP.  No 
graphics.  We also used a commercially available network simulator (Mimic) 
which was written in Tcl (or, at least, has Mimic as its scripting 
language).

For us, the biggest thing was the quick learning curve (i.e. ease of use).  
Most of the programmers on the team were network jocks, not programmers.  
Getting them up to speed on enough Tcl to do their jobs was very quick.  
Performance was not an issue, since the application was rate limited by the 
network (i.e. waiting for SNMP replies to come back).

We also had lots of hooks into C code.  Doing that is trivial in Tcl.  Yes, 
I know you can extend/embed Python, but it's a LOT easier in Tcl.  
Embedding a Tcl interpreter in a C program is literally one line of code.  
I sat down with the book to figure out how to do it, and had a running 
interpreter going in 10 minutes.  Part of what makes it so easy is that 
everything in Tcl is a string (no need to support multiple data types).

I don't think I would want to write a huge system in Tcl.  For one thing, 
it's not object oriented (I have no direct experience with incr Tcl, so 
that may not be a fair critisism).  It's also slow (even slower than 
Python).  Of course, in both Tcl and Python, the key to a fast application 
is to do all the CPU-intensive parts in C and just script the glue code.

Anyway, I like Tcl.  It's certainly worth considering seriously as a 
scripting language.  As for "which is better, Tcl or Python", there's no 
one right answer to that.  Evaluate both and decide which fits your needs 
better.  Often, questions like that will be decided by things which have 
little to do with language technology.  Is your company re-organizing and 
there's a development group who are used to working in language X who are 
looking for a new project?  Guess which language they're going to pick?  
Got a major customer (or prospect) who expresses an interest in language X 
for scripting extensions?  Guess which language you're going to use?
-- 
http://mail.python.org/mailman/listinfo/python-list


Python bug tracker now secret?

2007-10-31 Thread John Nagle
I'm now getting messages like this from the Python bug tracker on
SourceForge:

  Artifact: This Artifact Has Been Made Private. Only Group Members Can
  View  Private ArtifactTypes.

I'm being denied access to bug reports I submitted, such as

https://sourceforge.net/tracker/?func=detail&aid=1651995&group_id=5470&atid=105470

This is only happening for Python bugs; bugs in non-Python areas are still
accessable.  So it's not a general SourceForge bug.

Is this a dumb policy change or a dumb administrator action?

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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Simon Brunning
On 10/31/07, jelle <[EMAIL PROTECTED]> wrote:
> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found,
> should't the .find method return 0 rather than -1?
> this breaks the
>
> if check.find('something'):
> do(somethingElse)

print 'ughughugh'.find('ugh')

;-)

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Marc 'BlackJack' Rintsch
On Wed, 31 Oct 2007 13:31:06 +, jelle wrote:

> if I check a string for for a substring, and this substring isn't found, 
> should't the .find method return 0 rather than -1?
> this breaks the 
> 
> if check.find('something'):
> do(somethingElse)
> 
> idiom, which is a bit of a pity I think.

And what should ``'string'.find('str')`` return?  How do you distinguish
the not found at all case from the found at the very beginning case!?

The simple test you want can be written this way:

if 'something' in check:
do(something_else)

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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Carsten Haese
On Wed, 2007-10-31 at 13:31 +, jelle wrote:
> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found, 
> should't the .find method return 0 rather than -1?
> this breaks the 
> 
> if check.find('something'):
> do(somethingElse)
> 
> idiom, which is a bit of a pity I think.

You're using the wrong tool for the job. You only care *whether* the
substring is in the string, but you're asking *where* it is, so you have
to do extra work to translate the answer you get into the answer you
need.

To ask the right question in the first place, use "in" or "not in":

if 'something' in check:
do(somethingElse)

Also, if string.find returned 0 to say "substring not found", what
should it return for "spam salad".find("spam")?

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Hrvoje Niksic
jelle <[EMAIL PROTECTED]> writes:

> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found, 
> should't the .find method return 0 rather than -1?

How would you treat the case of 'something' being at the beginning of
the string?  After all, find returns the index.

> this breaks the 
>
> if check.find('something'):
> do(somethingElse)
>
> idiom, which is a bit of a pity I think.

if 'something' in check:
do(somethingElse)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread jelle feringa
There is a subtle point though.
If the substring is not found '_'.find(' '), will return -1
Semanticly, I was expecting the that if the substring was not found, the
conditional statement would not be found.
However, python evaluates -1 to True, so that is what I do find confusing.
So, I was arguing that '_'.find(' ') might return 0, however that is
obviously ambigious, since 0 might be an index as well.

So, perhaps I should rephrase and ask, why if -1 evaluates to True?
I think that's pretty ugly...

cheers,

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

Re: Python bug tracker now secret?

2007-10-31 Thread Jean-Paul Calderone
On Wed, 31 Oct 2007 07:53:01 -0700, John Nagle <[EMAIL PROTECTED]> wrote:
>I'm now getting messages like this from the Python bug tracker on
>SourceForge:
>
>  Artifact: This Artifact Has Been Made Private. Only Group Members Can
>  View  Private ArtifactTypes.
>
>I'm being denied access to bug reports I submitted, such as
>
>https://sourceforge.net/tracker/?func=detail&aid=1651995&group_id=5470&atid=105470
>
>This is only happening for Python bugs; bugs in non-Python areas are still
>accessable.  So it's not a general SourceForge bug.
>
>Is this a dumb policy change or a dumb administrator action?
>

I don't know why they chose to make the sf tracker private.  Maybe that
was the only way to remove write access.  Python bugs are now tracked
at http://bugs.python.org/.

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


capturing output of command line in an array

2007-10-31 Thread amjadcsu
Hi

I am trying to execute a command using os.system. this command lists
the number of nodes alive in a cluster. I would like to capture the
output in list/array in python. IS it possible.?/

Here is my command
 gstat -a
node13 2 (0/   56) [  0.00,  0.00,  0.00] [   0.0,   0.0,
0.1,  99.9,   0.0] OFF
node12 2 (1/   63) [  0.99,  0.97,  0.91] [  46.6,   0.0,
3.7,  49.8,   0.0] OFF
node8 2 (1/   59) [  0.99,  0.97,  0.91] [  47.5,   0.0,
2.8,  49.7,   0.0] OFF
node2 2 (1/   59) [  0.99,  0.97,  0.91] [  46.6,   0.0,
3.7,  49.7,   0.0] OFF
node1 2 (1/   59) [  0.99,  0.97,  0.91] [  46.6,   0.0,
3.7,  49.7,   0.0] OFF
node7 2 (1/   58) [  0.99,  0.97,  0.91] [  49.8,   0.0,
0.6,  49.7,   0.0] OFF
node11 2 (1/   59) [  0.99,  0.97,  0.91] [  46.6,   0.0,
3.8,  49.6,   0.0] OFF
node4 2 (1/   59) [  1.00,  1.00,  0.93] [  46.6,   0.0,
3.7,  49.7,   0.0] OFF
node10 2 (1/   59) [  1.00,  1.00,  0.94] [  46.7,   0.0,
3.7,  49.7,   0.0] OFF
node5 2 (1/   59) [  1.00,  1.00,  0.92] [  49.8,   0.0,
0.4,  49.7,   0.0] OFF
node6 2 (1/   59) [  1.00,  1.00,  0.94] [  49.5,   0.0,
0.9,  49.7,   0.0] OFF

I would like to have an array where each element contains the nodes

for example
a=[node13,node12,node2,node8,node1,node7,node 11]

any help would be appreciated

thanks

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


dictionary

2007-10-31 Thread Beema shafreen
hi everybody,
  I have a file

2709852  2709911A_16_P21360207405-59
  2710316  2710367A_14_P136880-42-51
  2710325  2710384A_16_P21360209876-59
  2711260  2711319A_16_P21360210-22-59
  2711297  2711356A_16_P03641959254-59
  2711610  2711659A_16_P03641960982-49
  2712641  2712696A_16_P036419621011-55
  2713707  2713765A_16_P4156364843-58
  2713808  2713861A_16_P03641963-16-53
  2713845  2713893A_16_P415636493460-48
  2717353  2717412A_16_P03641964214-59
  2717626  2717685A_16_P4156365525-59
  2717710  2717754A_16_P036419651250-44
  2719004  2719063A_16_P03641966-36-59

I need the result like this A_16_P21360207 [405 ,   -59 , -42]
 A_14_P136880 [42 ,   -51,
876]
 A_16_P21360209[876  ,  -59,
-22] That is the list has an overlapping with the next lines .
My script:
d = {}
fh = open('final_lenght_probe_span','r')
while fh:
a, b, c, span,len = fh.readline().strip().split('\t')
a1,b1,c1,span1,len1 = fh.readline().strip().split('\t')
probe_id = c
d[probe_id] = []
d[probe_id] = [span,len,span1]
for key in d.keys():
print key, d[key]
but i am not able to achive at my result what should i do for it.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Tim Chase
> if I check a string for for a substring, and this substring isn't found, 
> should't the .find method return 0 rather than -1?
> this breaks the 
> 
> if check.find('something'):
> do(somethingElse)
> 
> idiom, which is a bit of a pity I think.

That idiom is spelled:

   if 'something' in check:
 do(somethingElse)

Unless you really do need to start at a particular offset where 
you use the additional parameters of find(), such as 
find('something', 3, 42).  In that case, you can slice your target:

  if 'something' in check[3:42]:
do(somethingElse)

The above is untested, so check for fencepost errors, but the 
theory holds.

So pretty much, I'd never consider using find() :)

-tkc


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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread J. Clifford Dyer
On Wed, Oct 31, 2007 at 03:55:49PM +0100, jelle feringa wrote regarding Re: 
shouldn't 'string'.find('ugh') return 0, not -1 ?:
> 
>There is a subtle point though.
> 
>If the substring is not found '_'.find(' '), will return -1
> 
>Semanticly, I was expecting the that if the substring was not found,
>the conditional statement would not be found.
> 
>However, python evaluates -1 to True, so that is what I do find
>confusing.
> 
>So, I was arguing that '_'.find(' ') might return 0, however that is
>obviously ambigious, since 0 might be an index as well.
> 
> 
> 
>So, perhaps I should rephrase and ask, why if -1 evaluates to True?
> 
>I think that's pretty ugly...
> 
> 

It is ugly, but there's no alternative.  In essence, you can't do a truth-test 
on it, because you're not testing the truth of the find statement.  The 
statement that you want to test the truth of is s.find(q) >= 0.  In other 
words, you want to see that the substring was found at a valid (non-negative) 
location. As someone else pointed out, it would make more sense to use None 
instead of -1.  You still couldn't use `if s.find(q):` because you'd get a 
false result for a substring found at the beginning of the string, but the 
return value would make more intuitive sense.  

Witness also the problem of actually using the result of find:

s[s.find(q)]

will yield a valid part of the string (the last character) when q is not found. 
 If it evaluated to none, you'd get a respectable TypeError instead.

But you still wouldn't--and never will--be able to say `if s.find(q)`, because 
valid array indices can be either true or false.

Cheers,
Cliff



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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Carl Banks
On Oct 31, 9:31 am, jelle <[EMAIL PROTECTED]> wrote:
> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found,
> should't the .find method return 0 rather than -1?
> this breaks the
>
> if check.find('something'):
> do(somethingElse)
>
> idiom, which is a bit of a pity I think.

string.find has always been kind of a wart in Python; that's why
they're getting rid of it.  For testing for the presence of a
substring, use the in operator:

if "something" in check:
do(somethingElse)

When you need the position of a substring, using the index methods:

i = check.index("something")

index returns an exception of the substring is not there, so no need
to worry about what it returns.

Finally, it really won't kill you to do this:

if check.find("something") >= 0:
do(somethingElse)


Carl Banks


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


Re: help with pyparsing

2007-10-31 Thread Paul McGuire
On Oct 31, 6:59 am, Neal Becker <[EMAIL PROTECTED]> wrote:
> I'm just trying out pyparsing.  I get stack overflow on my first try.  Any
> help?
>
> #/usr/bin/python
>
> from pyparsing import Word, alphas, QuotedString, OneOrMore, delimitedList
>
> first_line = '[' + delimitedList (QuotedString) + ']'
>
> def main():
> string = '''[ 'a', 'b', 'cdef']'''
> greeting = first_line.parseString (string)
> print greeting
>
> if __name__ == "__main__":
> main()
>
> /usr/lib/python2.5/site-packages/pyparsing.py:2727: SyntaxWarning: Cannot
> add element of type  to ParserElement
>   return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
> /usr/lib/python2.5/site-packages/pyparsing.py:1008: SyntaxWarning: Cannot
> add element of type  to ParserElement
>   return other + self
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/tmp/python-k3AVeY.py", line 5, in 
> first_line = '[' + delimitedList (QuotedString) + ']'
>   File "/usr/lib/python2.5/site-packages/pyparsing.py", line 2727, in
> delimitedList
> return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
>   File "/usr/lib/python2.5/site-packages/pyparsing.py", line 1008, in
> __radd__
> return other + self
>   File "/usr/lib/python2.5/site-packages/pyparsing.py", line 1008, in
> __radd__
> return other + self

Oh!  You are so close!

QuotedString is a class.  delimitedList does not accept a class, but
an expression, which is usually created using instances of the
pyparsing classes.  quotedString is an expression, defining a pretty
complex quoted string syntax (single or double-quoted string).

Just change QuotedString to quotedString throughout your script, and
try again.

-- Paul

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


Re: A Python 3000 Question

2007-10-31 Thread Carl Banks
On Oct 31, 8:44 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-10-30, George Sakkis <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Oct 30, 11:25 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> >> On 2007-10-30, Eduardo O. Padoan <[EMAIL PROTECTED]> wrote:
>
> >> > This is a FAQ:
> >> >http://effbot.org/pyfaq/why-does-python-use-methods-for-some-function...
>
> >> Holy Airy Persiflage Batman!
>
> >> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
> >> (Intel)] on
> >> win32
> >> Type "help", "copyright", "credits" or "license" for more information.>>> 
> >> import timeit
> >> >>> timeit.Timer('len(seq)', 'seq = range(100)').timeit()
> >> 0.20332271187463391
> >> >>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
>
> >> 0.48545737364457864
>
> > Common mistake; try this instead:
>
> > timeit.Timer('seqlen()',
> >  'seq = range(100); seqlen=seq.__len__').timeit()
>
> Why would I want to do that?

If your point is to measure the time of just the operation as
accurately as possible, you don't want the extra dict lookup in
seq.__len__ affecting things.  Though it seems to me that if your
intention is to determine if builtin or method style is faster, it's
not such a great idea to replace the method call with a builtin call.

As for what benefit there is for len to be a builtin:

Python considers len to be an operator for all intents and purposes.
Python chose to spell this operator like a regular function, but it
could easily have given a special syntax to the length operation (for
instance, $#x).

Do you think that, if the length operation had its own syntax, people
would be saying "No, length shouldn't be an operator, it should be a
method"?  I don't think so; length is a fundamental and ubiquitous
operation and it wouldn't be unreasonable to give it its own syntax.

That suggests to me that, when people complain that len should be a
method, their complaint is a superficial complaint about spelling.
They are not considering whether len is important enough to be an
operator or not.


Carl Banks

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


RE: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Looney, James B
I believe most programming languages evaluate 0 to mean False, and
anything else to be True (for the purposes of boolean evaluation).
Python is no exception.




From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On
Behalf Of jelle feringa
Sent: Wednesday, October 31, 2007 8:56 AM
To: Luis Zarrabeitia
Cc: python-list@python.org
Subject: Re: shouldn't 'string'.find('ugh') return 0, not -1 ?


There is a subtle point though.
If the substring is not found '_'.find(' '), will return -1
Semanticly, I was expecting the that if the substring was not
found, the conditional statement would not be found.
However, python evaluates -1 to True, so that is what I do find
confusing.
So, I was arguing that '_'.find(' ') might return 0, however
that is obviously ambigious, since 0 might be an index as well.
 
So, perhaps I should rephrase and ask, why if -1 evaluates to
True?
I think that's pretty ugly...
 
cheers,
 
-jelle

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

Re: Python bug tracker now secret?

2007-10-31 Thread John Nagle
Jean-Paul Calderone wrote:
> On Wed, 31 Oct 2007 07:53:01 -0700, John Nagle <[EMAIL PROTECTED]> wrote:
>> I'm now getting messages like this from the Python bug tracker on
>> SourceForge:
>>
>>  Artifact: This Artifact Has Been Made Private. Only Group Members Can
>>  View  Private ArtifactTypes.
>>
>> I'm being denied access to bug reports I submitted, such as
>>
>> https://sourceforge.net/tracker/?func=detail&aid=1651995&group_id=5470&atid=105470
>>  
>>
>>
>> This is only happening for Python bugs; bugs in non-Python areas are 
>> still
>> accessable.  So it's not a general SourceForge bug.
>>
>> Is this a dumb policy change or a dumb administrator action?
>>
> 
> I don't know why they chose to make the sf tracker private.  Maybe that
> was the only way to remove write access.  Python bugs are now tracked
> at http://bugs.python.org/.
> 
> Jean-Paul

 There are bug reports in the SourceForge tracker that aren't in the
"bugs.python.org" tracker, so that move was botched.

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


shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread jelle feringa
Hi Tim,

Well, I this is another idiom in itself, right?
Your checking if something is part of an iterable.
I'm checking truth before entering a conditional expression.
The latter is considered to be pythonic, right?

-jelle


 On 10/31/07, Tim Chase <[EMAIL PROTECTED]> wrote:
>
> > if I check a string for for a substring, and this substring isn't found,
> > should't the .find method return 0 rather than -1?
> > this breaks the
> >
> > if check.find('something'):
> > do(somethingElse)
> >
> > idiom, which is a bit of a pity I think.
>
> That idiom is spelled:
>
>   if 'something' in check:
> do(somethingElse)
>
> Unless you really do need to start at a particular offset where
> you use the additional parameters of find(), such as
> find('something', 3, 42).  In that case, you can slice your target:
>
> if 'something' in check[3:42]:
>do(somethingElse)
>
> The above is untested, so check for fencepost errors, but the
> theory holds.
>
> So pretty much, I'd never consider using find() :)
>
> -tkc
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: why did these companies choose Tcl over Python

2007-10-31 Thread Kevin Walzer
chewie54 wrote:
> Hello,
> 
> As an electronics engineer I use some very expensive EDA CAD tool
> programs that are scriptable using Tcl.  I was wondering why these
> companies have choose to use Tcl instead of Python.   Some of these
> are:
> 
>Mentor Graphics ModelTech VHDL and Verilog simulator
>Synopsys  Design Compiler and Primetime Static Timing Analyzer
>Actel FPGA tools.
> 
> Tcl seems to very popular in my business as the scripting language of
> choice.
> 
> I'm in the process of deciding to use Tcl or Python for a CAD tool
> program that I have been working on.Most of the core of the
> program,  the database,   will be done is C as an extension to either
> Tcl or Python,   but I intend to use Tk or wxPthon for the GUI.   I do
> need publishing quality outputs from drawings done on a graphics
> device that are scaled to standard printer paper sizes.
> 
> 
> I would prefer to use Python but can't deny how popular Tcl is,  as
> mentioned above,  so my question is why wasn't Python selected by
> these companies as the choice of scripting languages for their
> product?
> 
> Are there any obvious advantages like:
> 
> performance,
> memory footprint,
> better cross-platform support,
> ease of use,
> 
> 
> Thanks in advance for your thoughts about this.
> 

One of the reasons Tcl has stayed around for so long is that it has 
found several niche's/domains where it has proven extremely useful. 
VDHL/Verilog is one of these areas: Tcl became the preferred solution 
for embedding and scripting, and has proven hard to dislodge. Network 
automation/scripting (via Tcl's Expect solution) is another problem 
domain where Tcl is widely used. GUI programming (with Tk) is yet another.

Developers tend to forget about Tcl as a viable programming language, 
and one of the reasons is that the problem domains where it has gained 
traction tend to be highly specialized.

I do GUI programming in Tk with both Python and Tcl. Doing sophisticated 
GUI's in Tk tends to be harder in Python than Tcl, because some of the 
current, modern Tk GUI libraries haven't been wrapped via Python. 
Understanding Tcl helps because I can drop into Tcl to customize a Tk 
widget as needed, then call the customized bits from Python.

In terms of suitability as a general purpose programming language, 
Python's biggest advantage over Tcl is the size of its standard library 
(Tcl is much smaller at its core, by design), its more singular approach 
to object-oriented programming if you use that method (Tcl has several 
different OO systems), and the size of its community--the larger number 
of Python programmers out there make it much more likely that you will 
find an open-source solution for your needs. Tcl's community is much 
smaller, its development moves more slowly, and Tcl does not compete in 
several major "hot" areas of development (no web frameworks like Django 
or Ruby on Rails).

Hope this helps,
Kevin

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread jelle feringa
>  The statement that you want to test the truth of is s.find(q) >= 0.  In
> other words, you want to see that the substring was found at a valid
> (non-negative) location. As someone else pointed out, it would make more
> sense to use None instead of -1.


I agree, that would be nice.

  You still couldn't use `if s.find(q):` because you'd get a false result
> for a substring found at the beginning of the string, but the return value
> would make more intuitive sense.


I'm sorry, but is that so?
>>>None == 0
False

Since the start of the string is indicated by 0 and not None, that should
work, right?

Witness also the problem of actually using the result of find:
>
> s[s.find(q)]
>
> will yield a valid part of the string (the last character) when q is not
> found.  If it evaluated to none, you'd get a respectable TypeError instead.
>
> But you still wouldn't--and never will--be able to say `if s.find(q)`,
> because valid array indices can be either true or false.


Yes, but that is the issue here. If the substring is not found, still find()
returns -1, which is a valid indice.
That I think is ugly. I can't think of a case where it would be prefereble
to have find() return -1 rather than None.
Formally speaking, -1 is an ambigious answer, since a perfectly valid
indice.

the '_'.find(' ') might actually make a nice idiom while parsing for
ignoring irrelevant lines, and processing lines that are of interest in the
conditional expression.

Cheers,

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

Re: Python bug tracker now secret?

2007-10-31 Thread Martin v. Löwis
> I don't know why they chose to make the sf tracker private.  Maybe that
> was the only way to remove write access. 

That, plus removing it means that people won't browse outdated information.

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


Re: Creating a temporary file in Python

2007-10-31 Thread looping
On Oct 31, 2:16 pm, Sion Arrowsmith <[EMAIL PROTECTED]>
wrote:
> " [ ... ] Whether the name can be used to open the file a second time,
> while the named temporary file is still open, varies across platforms
> (it can be so used on Unix; it cannot on Windows NT or later)."

I didn't notice this limitation when reading the doc, thanks to point
me to it.

So for the future newbie that look something like this, here is my
final code:

fd, filename = tempfile.mkstemp(suffix='.sql')
f = os.fdopen(fd, 'wb')
try:
f.write(txt.encode('cp1252'))
f.close()
p = Popen([SQL_PLUS, '-s', dsn,
'@', SQL_PLUS_SCRIPT, filename],
stdout=PIPE, stderr=STDOUT)
p.wait()
finally:
os.remove(filename)


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


Re: why did these companies choose Tcl over Python

2007-10-31 Thread Paddy
On Oct 30, 10:47 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > I would prefer to use Python but can't deny how popular Tcl is,  as
> > mentioned above,  so my question is why wasn't Python selected by
> > these companies as the choice of scripting languages for their
> > product?
>
> I think this question needs to be answered on a case-by-case basis,
> but my guess is that it is in most cases historical. Work on Tcl
> started in 1988, and it was the first (major?) embeddable scripting
> language (that is also free software etc). Python wasn't released
> until 1991, and wasn't first recognized as being just as easily
> embeddable (and I think early releases weren't as easily embeddable
> as today's Python is).
>
> Tcl's original objective was to support circuit design, so people
> in that field clearly knew that Tcl worked, but they were likely
> unaware of any alternatives (or else the future of these alternatives
> may have been uncertain).
>
> So at that time, Tcl would have been the obvious (because only)
> choice. Now these products are stuck with Tcl, and redoing all
> the work (including the existing extension modules!) in a different
> programming language would be a lot of work.
>
> Regards,
> Martin

Here is TCL's author talking about its roots: 
http://www.tcl.tk/about/history.html
The Electronic Design Automation industry was in some ways ahead of
other industries in adopting TCL as its major scripting language but
because of this I think it might now be suffering because, as capable
as TCL is, current EDA tools would benefit from reflecting what is
increasingly an object oriented compiled language core, as Python
objects for user manipulation.

- Paddy.

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

Re: Python bug tracker now secret?

2007-10-31 Thread Martin v. Löwis
> There are bug reports in the SourceForge tracker that aren't in the
> "bugs.python.org" tracker, so that move was botched.

Which one in particular?

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


Re: Help with pyparsing and dealing with null values

2007-10-31 Thread avidfan
On Mon, 29 Oct 2007 05:45:26 -0700, Paul McGuire <[EMAIL PROTECTED]>
wrote:

>On Oct 29, 1:11 am, avidfan <[EMAIL PROTECTED]> wrote:
>> Help with pyparsing and dealing with null values
>>
>> I am trying to parse a log file (web.out) similar to this:
>>
>> ---
>>
>> MBeanName: "mtg-model:Name=mtg-model_managed2,Type=Server"
>> AcceptBacklog: 50
>
>> ExpectedToRun: false
>> ExternalDNSName:
>> ExtraEjbcOptions:
>> ExtraRmicOptions:
>> GracefulShutdownTimeout: 0
>>
>> ---
>>
>> and I need the indented values (eventually) in a dictionary.  As you
>> can see, some of the fields have a value, and some do not.  It appears
>> that the code I have so far is not dealing with the null values and
>> colons as I had planned.
>>
>
>This is a very good first cut at the problem.  Here are some tips to
>get you going again:
>
>1. Literal("\n") wont work, use LineEnd() instead.  Literals are for
>non-whitespace literal strings.
>
>
>2. "all = SkipTo(end)" can be removed, use restOfLine instead of all.
>("all" as a variable name masks Python 2.5's "all" builtin function.)
>
>
>3. In addition to identity, you might consider defining some other
>known value types:
>
>boolean = oneOf("true false")
>boolean.setParseAction(lambda toks: toks[0]=="true")
>
>integer = Combine(Optional("-") + Word(nums))
>integer.setParseAction(lambda toks: int(toks[0]))
>
>These will do data conversion for you at parse time, so that the
>values are already in int or bool form when you access them later.
>
>
>4. The significant change is to this line (I've replaced all with
>restOfLine):
>
>pairs = Group(identity + colon + Optional(identity) + restOfLine)
>
>What gives us a problem is that pyparsing's whitespace-skipping will
>read an identity, even if it's not on the same line.  So for keys that
>have no value given, you end up reading past the end-of-line and read
>the next key name as the value for the previous key.  To work around
>this, define the value as something which must be on the same line,
>using the NotAny lookahead, which you can abbreviate using the ~
>operator.
>
>pairs = Group(identity + colon + Optional(~end + (identity |
>restOfLine) ) + end )
>
>If we add in the other known value types, this gets a bit unwieldy, so
>I recommend you define value separately:
>
>value = boolean | integer | identity | restOfLine
>pairs = Group(identity + colon + Optional(~end + value) + end )
>
>At this point, I think you have a working parser for your log data.
>
>
>5. (Extra Credit) Lastly, to create a dictionary, you are all set to
>just add pyparsing's Dict class.  Change:
>
>logEntry = MBeanName + ServerName("servername") + OneOrMore(pairs)
>
>to:
>
>logEntry = MBeanName + ServerName("servername") +
>Dict(OneOrMore(pairs))
>
>(I've also removed ".setResultsName", using the new shortened form for
>setting results names.)
>
>Dict will return the parsed tokens as-is, but it will also define
>results names using the tokens[0] element of each list of tokens
>returned by pairs - the values will be the tokens[1:], so that if a
>value expression contains multiple tokens, they all will be associated
>with the results name key.
>
>Now you can replace the results listing code with:
>
>for t in tokens:
>   print t
>
>with
>
>print tokens.dump()
>
>And you can access the tokens as if they are a dict, using:
>
>print tokens.keys()
>print tokens.values()
>print tokens["ClasspathServletDisabled"]
>
>If you prefer, for keys that are valid Python identifiers (all of
>yours appear to be), you can just use object.attribute notation:
>
>print tokens.ClasspathServletDisabled
>
>Here is some sample output, using dump(), keys(), and attribute
>lookup:
>
>tokens.dump() -> ['MBeanName:', '"mtg-model:Name=mtg-
>model_managed2,Type=Server"', ['AcceptBacklog', 50],
>['AdministrationPort', 0], ['AutoKillIfFailed', False],
>['AutoRestart', True], ['COM', 'mtg-model_managed2'], ['COMEnabled',
>False], ['CachingDisabled', True], ['ClasspathServletDisabled',
>False], ['ClientCertProxyEnabled', False], ['Cluster', 'mtg-model-
>cluster'], ['ClusterRuntime', 'mtg-model-cluster'], ['ClusterWeight',
>100], ['CompleteCOMMessageTimeout', -1],
>['CompleteHTTPMessageTimeout', -1], ['CompleteIIOPMessageTimeout',
>-1], ['CompleteMessageTimeout', 60], ['CompleteT3MessageTimeout', -1],
>['CustomIdentityKeyStoreFileName'],
>['CustomIdentityKeyStorePassPhrase'],
>['CustomIdentityKeyStorePassPhraseEncrypted'],
>['CustomIdentityKeyStoreType'], ['CustomTrustKeyStoreFileName'],
>['CustomTrustKeyStorePassPhrase'],
>['CustomTrustKeyStorePassPhraseEncrypted'],
>['CustomTrustKeyStoreType'], ['DefaultIIOPPassword'],
>['DefaultIIOPPasswordEncrypted'], ['DefaultIIOPUser'],
>['DefaultInternalServletsDisabled', False], ['DefaultProtocol', 't3'],
>['DefaultSecureProtocol', 't3s'], ['DefaultTGIOPPassword'],
>['DefaultTGIOPP

Re: Python bug tracker now secret?

2007-10-31 Thread Jean-Paul Calderone
On Wed, 31 Oct 2007 08:26:06 -0700, John Nagle <[EMAIL PROTECTED]> wrote:
>Jean-Paul Calderone wrote:
>> On Wed, 31 Oct 2007 07:53:01 -0700, John Nagle <[EMAIL PROTECTED]> wrote:
>>> I'm now getting messages like this from the Python bug tracker on
>>> SourceForge:
>>>
>>>  Artifact: This Artifact Has Been Made Private. Only Group Members Can
>>>  View  Private ArtifactTypes.
>>>
>>> I'm being denied access to bug reports I submitted, such as
>>>
>>> https://sourceforge.net/tracker/?func=detail&aid=1651995&group_id=5470&atid=105470
>>>
>>>
>>> This is only happening for Python bugs; bugs in non-Python areas are
>>> still
>>> accessable.  So it's not a general SourceForge bug.
>>>
>>> Is this a dumb policy change or a dumb administrator action?
>>>
>>
>> I don't know why they chose to make the sf tracker private.  Maybe that
>> was the only way to remove write access.  Python bugs are now tracked
>> at http://bugs.python.org/.
>>
>> Jean-Paul
>
> There are bug reports in the SourceForge tracker that aren't in the
>"bugs.python.org" tracker, so that move was botched.
>

You should probably send a message to python-dev about that.

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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread jelle

>if 'something' in check:
>  do(somethingElse)

Tim, you're absolutely right that the above makes far more sense in my case.
Thanks for pointing that out.

-jelle

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


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread Tim Chase
> Well, I this is another idiom in itself, right?
> Your checking if something is part of an iterable.
> I'm checking truth before entering a conditional expression.

I'm not sure I follow.  I simply replaced your

   if check.find('something')

with

   if 'something' in check:

which (1) is more readable (2) is more pythonic (especially as I 
understand that find() is going away), and (3) works like I 
understand you want from your description.

For strings, they're the same behavior.  However, it also works 
for testing membership in other container classes (sets, lists, 
tuples, dicts, etc).

Your original code's behavior would be analog to

   if not check.startswith('something')

which is not at all what I think you meant.  This 
misinterpretation alone is reason enough to give the find() 
method the boot.

> The latter is considered to be pythonic, right?

Clarity is pythonic.  The find() call returns an offset, or -1 if 
not found (because the beginning-of-string is offset=0).  It 
would also make sense if this returned None instead of -1. 
Either way, find() should be used for returning index values.  If 
you're testing for the presence of a substring, use the

   if 'something' in check:

to do the test.  And as for the start/end parameters to find, 
they are interpreted as slice endpoints, so

   if check.find('something', start) != -1:

would be the same as

   if 'something' in check[start:]:

and

   if check.find('something', start, end) != -1:

would be the same as

   if 'something' in check[start:end]:

both of which are far more readable than their find() variants.

Hope this helps clarify,

-tkc




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


Re: Python bug tracker now secret?

2007-10-31 Thread Jean-Paul Calderone
On Wed, 31 Oct 2007 16:42:48 +0100, "\"Martin v. Löwis\"" <[EMAIL PROTECTED]> 
wrote:
>> I don't know why they chose to make the sf tracker private.  Maybe that
>> was the only way to remove write access.
>
>That, plus removing it means that people won't browse outdated information.
>

Though it also means all old links are broken and there's no obvious pointer to
the new information.

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

Re: capturing output of command line in an array

2007-10-31 Thread Lee Capps

On Oct 31, 2007, at 11:01 AM, [EMAIL PROTECTED] wrote:

> I am trying to execute a command using os.system. this command lists
> the number of nodes alive in a cluster. I would like to capture the
> output in list/array in python. IS it possible.?/
>
> Here is my command
>  gstat -a
> node13 2 (0/   56) [  0.00,  0.00,  0.00] [   0.0,   0.0,
> 0.1,  99.9,   0.0] OFF
> node12 2 (1/   63) [  0.99,  0.97,  0.91] [  46.6,   0.0,
> 3.7,  49.8,   0.0] OFF
> node8 2 (1/   59) [  0.99,  0.97,  0.91] [  47.5,   0.0,
> 2.8,  49.7,   0.0] OFF
> node2 2 (1/   59) [  0.99,  0.97,  0.91] [  46.6,   0.0,
> 3.7,  49.7,   0.0] OFF
> node1 2 (1/   59) [  0.99,  0.97,  0.91] [  46.6,   0.0,
> 3.7,  49.7,   0.0] OFF
> node7 2 (1/   58) [  0.99,  0.97,  0.91] [  49.8,   0.0,
> 0.6,  49.7,   0.0] OFF
> node11 2 (1/   59) [  0.99,  0.97,  0.91] [  46.6,   0.0,
> 3.8,  49.6,   0.0] OFF
> node4 2 (1/   59) [  1.00,  1.00,  0.93] [  46.6,   0.0,
> 3.7,  49.7,   0.0] OFF
> node10 2 (1/   59) [  1.00,  1.00,  0.94] [  46.7,   0.0,
> 3.7,  49.7,   0.0] OFF
> node5 2 (1/   59) [  1.00,  1.00,  0.92] [  49.8,   0.0,
> 0.4,  49.7,   0.0] OFF
> node6 2 (1/   59) [  1.00,  1.00,  0.94] [  49.5,   0.0,
> 0.9,  49.7,   0.0] OFF
>
> I would like to have an array where each element contains the nodes
>
> for example
> a=[node13,node12,node2,node8,node1,node7,node 11]
>
> any help would be appreciated
>

You might try os.popen to read in the output of your command.

It would be helpful to have more information about what you'd like to  
do with your list.  Do you just want to put the text of the  
individual node lines from gstat into the list?  If so, os.popen  
should work for you.  Or  do you need to parse the lines and store  
them in, say dictionaries?  Tuples?  If you need to parse it, you  
could use module re, or even just string methods, depending on what  
you're trying to do . . . .

HTH,

---
Lee Capps
Technology Specialist
CTE Resource Center
[EMAIL PROTECTED]



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


Re: why did these companies choose Tcl over Python

2007-10-31 Thread Hrvoje Niksic
Roy Smith <[EMAIL PROTECTED]> writes:

> We also had lots of hooks into C code.  Doing that is trivial in Tcl.  Yes, 
> I know you can extend/embed Python, but it's a LOT easier in Tcl.
> Embedding a Tcl interpreter in a C program is literally one line of
> code.

Have you tried both or just Tcl?  I've seen examples of both and they
look about equally simple to set up.
http://docs.python.org/ext/high-level-embedding.html shows a Python
high-level example.  Many companies use the kind of simple embedding
shown there in real-world projects.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shouldn't 'string'.find('ugh') return 0, not -1 ?

2007-10-31 Thread jelle feringa
Thanks for your in-depth explanation Tim.
Which is impossible to disagree with!


On 10/31/07, Tim Chase <[EMAIL PROTECTED]> wrote:
>
> > Well, I this is another idiom in itself, right?
> > Your checking if something is part of an iterable.
> > I'm checking truth before entering a conditional expression.
>
> I'm not sure I follow.  I simply replaced your
>
>   if check.find('something')
>
> with
>
>   if 'something' in check:
>
> which (1) is more readable (2) is more pythonic (especially as I
> understand that find() is going away), and (3) works like I
> understand you want from your description.
>
> For strings, they're the same behavior.  However, it also works
> for testing membership in other container classes (sets, lists,
> tuples, dicts, etc).
>
> Your original code's behavior would be analog to
>
>   if not check.startswith('something')
>
> which is not at all what I think you meant.  This
> misinterpretation alone is reason enough to give the find()
> method the boot.
>
> > The latter is considered to be pythonic, right?
>
> Clarity is pythonic.  The find() call returns an offset, or -1 if
> not found (because the beginning-of-string is offset=0).  It
> would also make sense if this returned None instead of -1.
> Either way, find() should be used for returning index values.  If
> you're testing for the presence of a substring, use the
>
>   if 'something' in check:
>
> to do the test.  And as for the start/end parameters to find,
> they are interpreted as slice endpoints, so
>
>   if check.find('something', start) != -1:
>
> would be the same as
>
>   if 'something' in check[start:]:
>
> and
>
>   if check.find('something', start, end) != -1:
>
> would be the same as
>
>   if 'something' in check[start:end]:
>
> both of which are far more readable than their find() variants.
>
> Hope this helps clarify,
>
> -tkc
>
>
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list

PyCon 2008 - Call for Tutorials

2007-10-31 Thread Greg Lindstrom
PyCon 2008 is being held in Chicago this year. The general conference is
March 14-16 with the proceeding day, March 13th, being the traditional
"tutorial day".  We have had a lot of input on topics to cover and now we
are looking for qualified instructors to sign up to present the sessions.
Tutorials are 3 hours long (with break) and instructors are paid for their
effort ($1000.00 + conference registration).

PyCon is planned and run by volunteers just like you.  Why not get involved?

Pop on over to us.pycon.org  for conference
details or email us at [EMAIL PROTECTED] and let us know what you
would like to present as a tutorial.

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

Re: _tkinter installation in python 2.5 on mandriva with a default 2.4

2007-10-31 Thread wyleu

> So where it tk.h located?


tk.h is now in just about every directory called include that could in
anyway be connected with this and indeed it does appear in the make
file printout:

/usr/bin/install -c -m 644 ./Include/sysmodule.h /usr/local/include/
python2.5
/usr/bin/install -c -m 644 ./Include/timefuncs.h /usr/local/include/
python2.5
/usr/bin/install -c -m 644 ./Include/tk.h /usr/local/include/python2.5
/usr/bin/install -c -m 644 ./Include/token.h /usr/local/include/
python2.5
/usr/bin/install -c -m 644 ./Include/traceback.h /usr/local/include/
python2.5

however it still generates the same error message,
I've tried debugging setup.py in the distribution directory with idle
( python2.4.3 versions ) but not surprisingly that doesn't do anything
too impressive, as you would expect.
Short of stuffing lots of print statements in there to actual try and
locate the file names it's failing on I'm at a loss to see where to go
next.

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


Re: why did these companies choose Tcl over Python

2007-10-31 Thread Robin Becker
Martin v. Löwis wrote:
...
> I think this question needs to be answered on a case-by-case basis,
> but my guess is that it is in most cases historical. Work on Tcl
> started in 1988, and it was the first (major?) embeddable scripting
> language (that is also free software etc). Python wasn't released
> until 1991, and wasn't first recognized as being just as easily
> embeddable (and I think early releases weren't as easily embeddable
> as today's Python is).
..
in the 70's many of the people I knew in engineering were using forth as an 
embedded language. Of course the embedding was the final application as the 
controlling computers were really puny eg pdp8/9/11.

At that time the concept of free software hadn't even arisen. I believe forth 
was proprietary, but it was widely available to academics and many machine 
tools 
and similar control applications used it.
-- 
Robin Becker

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


Re: _tkinter installation in python 2.5 on mandriva with a default 2.4

2007-10-31 Thread Martin v. Löwis
> tk.h is now in just about every directory called include that could in
> anyway be connected with this and indeed it does appear in the make
> file printout:
> 
> /usr/bin/install -c -m 644 ./Include/tk.h /usr/local/include/python2.5

How did you get tk.h into the Include directory? You shouldn't manually
copy files around; this will surely break your system and installation
procedures if you don't know exactly what you are doing.

What is the location that your Mandriva package installed tk.h to?

> Short of stuffing lots of print statements in there to actual try and
> locate the file names it's failing on I'm at a loss to see where to go
> next.

tk.h is searched-for in detect_tkinter. Check whether tklib, tcllib,
tcl_includes and tk_includes all get set. This should take only
a single print statement.

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


Re: Python bug tracker now secret?

2007-10-31 Thread Martin v. Löwis
> Though it also means all old links are broken and there's no obvious
> pointer to the new information.

Not all of them, no. For a long time, people could use links of the
form www.python.org/sf/, and these links continue to work.
Most other links on www.python.org have been fixed.

I believe most people had little or no problems finding the new bug
tracker, in particular if they had seen the announcement.

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


Re: Fwd: Namespace question

2007-10-31 Thread Frank Aune
On Wednesday 31 October 2007 15:19:25 Andrii V. Mishkovskyi wrote:
> You mean something like this:
> >>>import random
> >>>def foo():
>
> ...print '42'
>
> >>>random.randit = foo
> >>>random.randit()
>
> 42
>
> am I right?
> --

I was thinking more of the line:

random.py: (my custom random.py module)

---
import random # this is the std lib random module

def someFunc():
print random.randint()
---

When I try this, the import statement in the above module will import itself, 
and not the std lib random.py

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


Re: simple? embedding question

2007-10-31 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
> it works!
> could i cache maindict pointer in a global var or am i condemned to
> call
> PyObject* mainmod = PyImport_AddModule("__main__");
> assert(mainmod);
> PyObject* maindict = PyModule_GetDict(mainmod);
> assert(maindict);
> every time i want to PyRun_String?
> i call Py_Finalize only atexit.
> 
> i also found boost library docs of some help:
> http://service-spi.web.cern.ch/service-spi/external/Boost/1.30.0/rh73_gcc32/libs/python/doc/tutorial/doc/using_the_interpreter.html
> 
> btw what kind of object is returned in case i use Py_file_input
> in PyRun_String?
> 

Yes, you can keep a reference to maindict if you wish, but make sure you 
increment the reference count since PyModule_GetDict() returns a 
borrowed reference.

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


Method needed for skipping lines

2007-10-31 Thread Gustaf
Hi all,

Just for fun, I'm working on a script to count the number of lines in source 
files. Some lines are auto-generated (by the IDE) and shouldn't be counted. The 
auto-generated part of files start with "Begin VB.Form" and end with "End" 
(first thing on the line). The "End" keyword may appear inside the 
auto-generated part, but not at the beginning of the line.

I imagine having a flag variable to tell whether you're inside the 
auto-generated part, but I wasn't able to figure out exactly how. Here's the 
function, without the ability to skip auto-generated code:

# Count the lines of source code in the file
def count_lines(f):
  file = open(f, 'r')
  rows = 0
  for line in file:
rows = rows + 1
  return rows

How would you modify this to exclude lines between "Begin VB.Form" and "End" as 
described above? 

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


Building libraries that my extensions can use. [distutils]

2007-10-31 Thread [EMAIL PROTECTED]
Hello all,
I want to create a shared object that my extension modules can
dynamically load with intact symbols across modules. Searching the
documentation lead me to distutils.ccompiler. Quite frankly
comprehending this has been difficult for the newbie in me. I did
google (..and krugle) for setup scripts that use this but they seem to
be designed for medium to large projects. Mine is quite small to
modify the ccompiler class.

 o (foo.so)
/ \
   /   \
  / \
 /   \
  bar.c   baz.c

So in my setup script i would like to have 'foo' under the libraries
list in setup(). Is there a dummy' guide for this, or atleast a pretty
basic example which I might pick upon given the simplicity.

I did try this

libraries=[("foo", {'sources'=src_dir, 'include_dirs'=dir, 'libraries'
= some_external_thingy})]

And it seems to build fine but I find that symbols in the object file
are not visible to the others..

Am I in a state of confusion or what...=(, Anyone please guide me out
of this by pointing me to a  trivial example..

Thanks,
Sudharshan S

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


permuting over nested dicts?

2007-10-31 Thread Christian Meesters
Hoi,

I have the following data structure (of variable size actually, to make
things simple, just that one):
d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
 'b': {'x':[7,8,9], 'y':[10,11,12]}}
This can be read as a dict of possibilities: The entities 'a' and 'b' have
the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
3. Does anybody know a convenient (and fast) way to permute over all
possible nested dicts like
{'a': {'x':1, 'y':4},
 'b': {'x':7, 'y':10}}
and
{'a': {'x':2, 'y':4},
 'b': {'x':7, 'y':10}}
and so forth?

Any link or snippet is appreciated.

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


Re: Method needed for skipping lines

2007-10-31 Thread Marc 'BlackJack' Rintsch
On Wed, 31 Oct 2007 18:02:26 +0100, Gustaf wrote:

> Just for fun, I'm working on a script to count the number of lines in
> source files. Some lines are auto-generated (by the IDE) and shouldn't be
> counted. The auto-generated part of files start with "Begin VB.Form" and
> end with "End" (first thing on the line). The "End" keyword may appear
> inside the auto-generated part, but not at the beginning of the line.
> 
> I imagine having a flag variable to tell whether you're inside the
> auto-generated part, but I wasn't able to figure out exactly how. Here's
> the function, without the ability to skip auto-generated code:
> 
> # Count the lines of source code in the file def count_lines(f):
>   file = open(f, 'r')
>   rows = 0
>   for line in file:
> rows = rows + 1
>   return rows
> 
> How would you modify this to exclude lines between "Begin VB.Form" and
> "End" as described above? 

Introduce the flag and look up the docs for the `startswith()` method on
strings.

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


Re: marshal vs pickle

2007-10-31 Thread Raymond Hettinger
On Oct 31, 6:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote:
>  I like to use
> marshal a lot because it's the absolutely fastest
> way to store and load data to/from Python. Furthermore
> because marshal is "stupid" the programmer has complete
> control.  A lot of the overhead you get with the
> pickles which make them generally much slower than
> marshal come from the cleverness by which pickle will
> recognized shared objects and all that junk.  When I
> serialize,

I believe this FUD is somewhat out-of-date.  Marshalling
became smarter about repeated and shared objects.  The
pickle module (using mode 2) has a similar implementation
to marshal and both use the same tricks, but pickle is
much more flexible in the range of objects it can handle
(i.e. sets became marshalable only recently while deques
can pickle but not marshal)

For the most part, users are almost always better-off
using pickle which is version independent, fast, and
can handle many more types of objects than marshal.

Also FWIW, in most applications of pickling/marshaling,
the storage or tranmission times dominate computation
time. I've gotten nice speed-ups by zipping the pickle
before storing, transmitting, or sharing (RPC apps
for example).


Raymond

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


Re: Python bug tracker now secret?

2007-10-31 Thread Terry Reedy

"John Nagle" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| I'm now getting messages like this from the Python bug tracker on
| SourceForge:
|
|  Artifact: This Artifact Has Been Made Private. Only Group Members Can
|  View  Private ArtifactTypes.

This message actually comes from SourceForge.  It is not at all what Python 
people would prefer (a proper forwarding message).  Such lack of control 
helped motivate the switch to our own tracker ;-). 



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


Re: Metaclass vs Class factory

2007-10-31 Thread [EMAIL PROTECTED]
On Oct 30, 10:46 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:

> The same as the difference between a class and a function that returns
> an instance.

Thanks Bruno.

Lorenzo

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


Re: _tkinter installation in python 2.5 on mandriva with a default 2.4

2007-10-31 Thread wyleu

> tk.h is searched-for in detect_tkinter. Check whether tklib, tcllib,
> tcl_includes and tk_includes all get set. This should take only
> a single print statement.
>
> Regards,
> Martin

Ok I've cleared my increasingly frantic copies out

[EMAIL PROTECTED] python2.5]# find / -name tk.h
/usr/include/tk.h
/usr/include/tk8.4.13/generic/tk.h

The slightly more verbose setup.py now reports

lib_dir:['/usr/local/lib', '/lib64', '/usr/lib64', '/lib', '/usr/lib']
Inc_dir: ['./Include', '.', '/usr/local/include', '/home/chris/
Python-2.5.1/Include', '/home/chris   /Python-2.5.1', '/usr/
include']
 Those TK libraries  tcllib=None tklib=None tcl_includes=None
tk_includes=None
INFO: Can't locate Tcl/Tk libs and/or headers

I don't understand why the headers report None as the file tk.h is
in   /usr/include ... or is the lack of the word generic more of a
problem?

I also can't work out what the name of the actual libraries are: which
doesn't help much.

The fact that None is reported for everything is a bit confusing.




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


Re: py2exe (or other exe builder) on Vista system for Vista/XP install targets.

2007-10-31 Thread Michael
Björn, what library files end up being in your dist directory for that
project? Would you mind posting a copy of the output of dir?

I'm curious to see if there is a discrepancy.

--Michael

On Oct 31, 9:22 am, Bjoern Schliessmann  wrote:
> Michael wrote:
>
> [py2exe on Vista and XP]
>
> > When I attempt to run, I get "The procedure entry point
> > _except_handler4_common could not be located in the dynamic link
> > library mscvrt.dll."  Apparently vista has one more
> > _except_handler#_common function than XP does.
>
> Strange -- it works for me. I compile in Vista and deploy in Vista
> and XP (SP2). I'm using Twisted 2.5 and wxWidgets 2.8.
>
> I'm sorry that I cannot help more. I dropped py2exe recently because
> I had a similar missing symbol problem with a Windows 2000
> computer; so I installed Python and the modules directly on all my
> machines.
>
> Regards,
>
> Björn
>
> --
> BOFH excuse #223:
>
> The lines are all busy (busied out, that is -- why let them in to
> begin with?).


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

Re: permuting over nested dicts?

2007-10-31 Thread Paddy
On Oct 31, 5:21 pm, Christian Meesters <[EMAIL PROTECTED]> wrote:
> Hoi,
>
> I have the following data structure (of variable size actually, to make
> things simple, just that one):
> d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
>  'b': {'x':[7,8,9], 'y':[10,11,12]}}
> This can be read as a dict of possibilities: The entities 'a' and 'b' have
> the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
> 3. Does anybody know a convenient (and fast) way to permute over all
> possible nested dicts like
> {'a': {'x':1, 'y':4},
>  'b': {'x':7, 'y':10}}
> and
> {'a': {'x':2, 'y':4},
>  'b': {'x':7, 'y':10}}
> and so forth?
>
> Any link or snippet is appreciated.
>
> TIA
> Christian

from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502199
import comb2
# (I wish)!

for xa,ya,xb,yb in comb2([1,2,3], [4,5,6], [7,8,9], [10,11,12]):
print {'a': {'x': xa, 'y': ya},
   'b': {'x': xb, 'y': yb}}

Should work although untested.

- Paddy.

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


PyCon 2008 - Tutorial HowTo

2007-10-31 Thread Greg Lindstrom
Thinking about presenting a tutorial at PyCon 2008?  Here's a link with
everything you would ever want to know.

http://us.pycon.org/2008/tutorials/proposals/


PyCon simply would not exist without volunteers like YOU.  Get involved
today!

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

Re: _tkinter installation in python 2.5 on mandriva with a default 2.4

2007-10-31 Thread Martin v. Löwis
>  Those TK libraries  tcllib=None tklib=None tcl_includes=None
> tk_includes=None

This also contradicts your earlier statement that you have libtk8.4.so
on your machine.


> I don't understand why the headers report None as the file tk.h is
> in   /usr/include ... or is the lack of the word generic more of a
> problem?

Please read detect_tkinter in detail: if it already fails to find
tklib or tcllib, it won't check for header files at all.

You should now trace through find_library_file with
print statements. Check whether compiler.find_library_file
returns not None, if yes, report what it returns. Otherwise,
annotate compiler.find_library_file. Print compiler.find_library_file
to see what specific function it is; likely something in
unixccompiler.py.

If so, print out shared, dylib, static, and os.path.exists of each one.

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


Dictionary help

2007-10-31 Thread Steve
I'm currently working on a little database type program is which I'm 
using a dictionary to store the information. The key is a component a and 
the definition is a list of parts that make up the component. My problem 
is I need to list out several components, but not all, and there 
associated parts to a printer. Not having any luck. I can list them to 
the screen but not the printer. Any help/ideas would be appreciated.

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


Re: why did these companies choose Tcl over Python

2007-10-31 Thread chewie54
On Oct 31, 3:06 am, Tim Roberts <[EMAIL PROTECTED]> wrote:
> chewie54 <[EMAIL PROTECTED]> wrote:
>
> >As an electronics engineer I use some very expensive EDA CAD tool
> >programs that are scriptable using Tcl.  I was wondering why these
> >companies have choose to use Tcl instead of Python.   Some of these
> >are:
>
> >   Mentor Graphics ModelTech VHDL and Verilog simulator
> >   Synopsys  Design Compiler and Primetime Static Timing Analyzer
> >   Actel FPGA tools.
>
> Well, I recently did a development contract for Mentor, and the RFQ gave me
> the choice of doing the library binding and diagnostic GUI in either Tcl or
> Python.  Naturally, I chose Python (and wxPython), and both the client and
> I are quite happy with the result.
>
> (Actually, I did a Tcl binding for them as well, and just writing the text
> scripts reinforced my dislike for it...)
> --
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.

Hi Tim,

I would like to use Python and C and wxWidgets for my EDA CAD program.
I want
to put most of the program core in an Python extension and GUI in
wxWidgets.

I do need to get publishing quality vector graphics outputs from this
program so
one of my concerns is if the wxWidgets will work for this or will I
have to use
something like openGL or Cairo.

Did your work for Mentor include a high quality graphics output?

Thanks,






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


Re: marshal vs pickle

2007-10-31 Thread Aaron Watters
On Oct 31, 1:37 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> On Oct 31, 6:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote:
>
> >  I like to use
> > marshal a lot because it's the absolutely fastest
> > way to store and load data to/from Python
>
> I believe this FUD is somewhat out-of-date.  Marshalling
> became smarter about repeated and shared objects.  The
> pickle module (using mode 2) has a similar implementation
> to marshal

Raymond: happy days!  We are both right!
I just ran some tests from the test suite for
http://nucular.sourceforge.net with marshalling
and pickling switched in and out and to my
surprise I didn't find too much difference
on the "load" end (marshalling 10% faster),
but for the "bigLtreeTest.py" I found that
the build ("dump") process was about 1/3
slower with cPickle (mode 2/python2.4).  For
the more complex tests (mondial and gutenberg)
I found that the speed up for using marshal was
in the 1-2% range (and sometimes inverted
because of processor load I think, on a shared
hosting machine).

I'm pretty sure things were much worse for cPickle
many moons ago.  Nice to see that some things
get better :).  It makes sense that the
"dump" side would be slower because that's
where you need to remember all the objects
in case you see them again...

Anyway since it's easy and makes sense I think
the next version of nucular will have a
switchable option between marshal and cPickle
for persistant storage.

Thanks!  -- Aaron Watters

===
The pursuit of hypothetical performance
improvements is the root of all evil.
   -- Bill Tutt
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=tutt

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


Re: why did these companies choose Tcl over Python

2007-10-31 Thread Chris Mellon
On Oct 31, 2007 2:01 PM, chewie54 <[EMAIL PROTECTED]> wrote:
> On Oct 31, 3:06 am, Tim Roberts <[EMAIL PROTECTED]> wrote:
> > chewie54 <[EMAIL PROTECTED]> wrote:
> >
> > >As an electronics engineer I use some very expensive EDA CAD tool
> > >programs that are scriptable using Tcl.  I was wondering why these
> > >companies have choose to use Tcl instead of Python.   Some of these
> > >are:
> >
> > >   Mentor Graphics ModelTech VHDL and Verilog simulator
> > >   Synopsys  Design Compiler and Primetime Static Timing Analyzer
> > >   Actel FPGA tools.
> >
> > Well, I recently did a development contract for Mentor, and the RFQ gave me
> > the choice of doing the library binding and diagnostic GUI in either Tcl or
> > Python.  Naturally, I chose Python (and wxPython), and both the client and
> > I are quite happy with the result.
> >
> > (Actually, I did a Tcl binding for them as well, and just writing the text
> > scripts reinforced my dislike for it...)
> > --
> > Tim Roberts, [EMAIL PROTECTED]
> > Providenza & Boekelheide, Inc.
>
> Hi Tim,
>
> I would like to use Python and C and wxWidgets for my EDA CAD program.
> I want
> to put most of the program core in an Python extension and GUI in
> wxWidgets.
>
> I do need to get publishing quality vector graphics outputs from this
> program so
> one of my concerns is if the wxWidgets will work for this or will I
> have to use
> something like openGL or Cairo.
>

wxWidgets has a vector graphics implementations which is a wrapper for
native vector graphics. Look at wxGraphicsContext. It's not perfect
and you may want to use Cairo directly, especially if you need to
render to PDF or postscript for output.
-- 
http://mail.python.org/mailman/listinfo/python-list


3 number and dot..

2007-10-31 Thread Abandoned
Hi..
I want to do this:
for examle:
12332321 ==> 12.332.321

How can i do?

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


Re: Namespace question

2007-10-31 Thread Chris M
On Oct 31, 10:06 am, Frank Aune <[EMAIL PROTECTED]> wrote:
> Hello,
>
> Is it possible writing custom modules named the same as modules in the
> standard library, which in turn use the same module from the standard
> library?
>
> Say I want my application to have a random.py module, which in turn must
> import the standard library random.py module also, to get hold of the randint
> function for example.
>
> My attempts so far only causes my random.py to import itself instead of the
> standard library random.py
>
> Receipt for disaster? :)
>
> Regards,
> Frank

Read up on absolute imports (In Python 2.5, from __future__ import
absolute_imports) is required. You can load your random.py with
import .random, which can import the standard lib with import random.

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


Re: 3 number and dot..

2007-10-31 Thread Paul McNett
Abandoned wrote:

> Hi..
> I want to do this:
> for examle:
> 12332321 ==> 12.332.321
> 
> How can i do?


Assuming that the dots are always in the 3rd and 7th position in the string:

def conv(s, sep="."):
   l = [s[0:3], s[3:6], s[6:]]
   return sep.join(l)

print conv("12332321")


-- 
pkm ~ http://paulmcnett.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3 number and dot..

2007-10-31 Thread Abandoned
On Oct 31, 10:18 pm, Paul McNett <[EMAIL PROTECTED]> wrote:
> Abandoned wrote:
> > Hi..
> > I want to do this:
> > for examle:
> > 12332321 ==> 12.332.321
>
> > How can i do?
>
> Assuming that the dots are always in the 3rd and 7th position in the string:
>
> def conv(s, sep="."):
>l = [s[0:3], s[3:6], s[6:]]
>return sep.join(l)
>
> print conv("12332321")
>
> --
> pkm ~http://paulmcnett.com

But it's starts from the end..
print conv("12332321")
123.323.21
This is wrong it would be 12.332.321

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


XML DOM, but in chunks

2007-10-31 Thread Sean Davis
I have some very large XML files that are basically recordsets.  I
would like to access each record, one-at-a-time, and I particularly
like the ElementTree library for accessing the data.  Is there a way
to have ElementTree read only one record of the data at a time?
Alternatively, are there other ways that would allow one to parse out
a record at a time and maintain some nice ways of accessing the
elements within the record?

Thanks,
Sean

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


Re: 3 number and dot..

2007-10-31 Thread Paul McGuire
On Oct 31, 2:58 pm, Abandoned <[EMAIL PROTECTED]> wrote:
> Hi..
> I want to do this:
> for examle:
> 12332321 ==> 12.332.321
>
> How can i do?

>>> x = (12332321,)
>>> while (x[0]>0): x=divmod(x[0],1000)+x[1:]
...
>>> x
(0, 12, 332, 321)
>>> ".".join(map(str,x[1:]))
'12.332.321'

-- Paul

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


  1   2   >