Re: how to write thread-safe module ? and pytz

2005-08-13 Thread Stuart Bishop
nicolas_riesch wrote:
> Does someone know if the module pytz
> (http://sourceforge.net/projects/pytz/) is thread-safe ?
> I have not seen it explicitely stated, and just wanted to be sure, as I
> want to use it.

pytz is thread safe.

> That's because in the file pytz/tzinfo.py, I see global variables
> _timedelta_cache, _datetime_cache, _ttinfo_cache, which are
> dictionnaries and are used as cache.

> I always thought that you must protect shared data with locks when
> multithreading, but I don't see any lock anywhere in pytz.
> However, pytz seems to work well with multiple threads creating various
> timezone objects at the same time.
> I don't understand where the trick is, that allows multiple threads to
> access this module without any locking and that all this seems to work
> without any problem...

Thanks to the global interpreter lock, with the Python builtin types you
only need to maintain a lock if there is a race condition, or if you care
about the race condition. For example, the following is thread safe code:

>>> from threading import Thread
>>> import time
>>> stack = []
>>> stack2 = []
>>> def doit(i):
... stack.append(i)
... time.sleep(0.1)
... stack2.append(stack.pop())
...
>>> threads = [Thread(target=doit, args=(i,)) for i in range(0,100)]
>>> for t in threads: t.start()
...
>>> for t in threads: t.join()
...
>>> len(stack2)
100
>>> stack2
[99, 95, 98, 94, 93, 97, 92, 91, 96, 88, 87, 86, 85, 84, 83, 90, 79, 78, 77,
76, 74, 73, 72, 71, 70, 75, 82, 81, 80, 89, 69, 67, 66, 65, 64, 68, 60, 59,
58, 57, 56, 55, 63, 62, 61, 49, 54, 53, 52, 51, 46, 45, 44, 50, 48, 47, 29,
28, 35, 34, 33, 43, 42, 41, 40, 39, 38, 32, 37, 31, 30, 36, 27, 26, 25, 24,
23, 22, 21, 20, 19, 18, 17, 12, 16, 15, 14, 13, 11, 10, 9, 8, 7, 6, 4, 3, 2,
1, 0, 5]

Note that the value being appended to 'stack2' might not be the value that
was appended to 'stack' in any particular thread - in this case, we don't
care (but is the sort of thing you might need to watch out for).

In the code you mention in pytz, there *is* a race condition. However, if
this condition occurs the side effects are so trivial as to not worry about
locking. ie. if a number of threads call memorized_timedelta(seconds=60)
simultaneously, there is a slight chance that each thread will get a
different timedelta instance. This is extremely unlikely, and the rest of
the code doesn't care at all. If pytz compared the timedeltas using 'is'
instead of '==' at any point, it would be a bug (but it doesn't, so it isn't).

So you can write thread safe Python code without locks provided you are
using the builtin types, and keep a close eye out for race conditions. This
might sound error prone, but it is quite doable provided the critical areas
that are accessing shared objects are kept isolated, short and simple.

Here is an thread unsafe example. Here the mistake is made that the length
of stack will not change after checking it. Also because we don't use the
atomic stack.pop(), two threads might add the same value to stack2:

>>> from threading import Thread
>>> import time
>>> stack = range(0, 50)
>>> stack2 = []
>>> def doit():
... if len(stack) > 0:
... stack2.append(stack[-1])
... time.sleep(0.1)
... del stack[-1]
...
>>> threads = [Thread(target=doit) for i in range(0, 100)]
>>> for t in threads: t.start()
...
Exception in thread Thread-249:
Traceback (most recent call last):
  File "/usr/lib/python2.4/threading.py", line 442, in __bootstrap
self.run()
  File "/usr/lib/python2.4/threading.py", line 422, in run
self.__target(*self.__args, **self.__kwargs)
  File "", line 5, in doit
IndexError: list assignment index out of range



-- 
Stuart Bishop <[EMAIL PROTECTED]>
http://www.stuartbishop.net/


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

Testing

2005-08-13 Thread Rudi Grinberg
nothing to see 


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


py2exe: no exe produced?

2005-08-13 Thread guoxiaotian
I tried py2exe the latest version with python 2.4 on windows.

the setup script looks like this:
___

# setup.py
from distutils.core import setup
import py2exe

setup(name="Hello",
scripts=["f:\python\hello.py"],)



when I run the script, the output looks like

F:\Python>python setup.py py2exe
running py2exe
running build_scripts
creating F:\Python\dist
*** searching for required modules ***
*** parsing results ***
*** finding dlls needed ***
*** create binaries ***
*** byte compile python files ***
skipping byte-compilation of D:\Python24\lib\UserDict.py to
UserDict.pyc
skipping byte-compilation of D:\Python24\lib\atexit.py to atexit.pyc
skipping byte-compilation of D:\Python24\lib\copy.py to copy.pyc
skipping byte-compilation of D:\Python24\lib\copy_reg.py to
copy_reg.pyc
skipping byte-compilation of D:\Python24\lib\linecache.py to
linecache.pyc
skipping byte-compilation of D:\Python24\lib\macpath.py to macpath.pyc
skipping byte-compilation of D:\Python24\lib\ntpath.py to ntpath.pyc
skipping byte-compilation of D:\Python24\lib\os.py to os.pyc
skipping byte-compilation of D:\Python24\lib\os2emxpath.py to
os2emxpath.pyc
skipping byte-compilation of D:\Python24\lib\popen2.py to popen2.pyc
skipping byte-compilation of D:\Python24\lib\posixpath.py to
posixpath.pyc
skipping byte-compilation of D:\Python24\lib\re.py to re.pyc
skipping byte-compilation of D:\Python24\lib\repr.py to repr.pyc
skipping byte-compilation of D:\Python24\lib\sre.py to sre.pyc
skipping byte-compilation of D:\Python24\lib\sre_compile.py to
sre_compile.pyc
skipping byte-compilation of D:\Python24\lib\sre_constants.py to
sre_constants.pyc
skipping byte-compilation of D:\Python24\lib\sre_parse.py to
sre_parse.pyc
skipping byte-compilation of D:\Python24\lib\stat.py to stat.pyc
skipping byte-compilation of D:\Python24\lib\string.py to string.pyc
skipping byte-compilation of D:\Python24\lib\traceback.py to
traceback.pyc
skipping byte-compilation of D:\Python24\lib\types.py to types.pyc
skipping byte-compilation of D:\Python24\lib\warnings.py to
warnings.pyc
*** copy extensions ***
*** copy dlls ***
copying D:\Python24\w9xpopen.exe -> F:\Python\dist


when it's done only 2 files produced under dist dir:
library.zip
w95popen.exe

any ideas?
Thanks in advance!

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


Re: Standalone applications ?

2005-08-13 Thread Madhusudan Singh
Paolo Alexis Falcone wrote:

> On Sat, 13 Aug 2005 23:29:27 -0400, Madhusudan Singh wrote:
> 
>> Hi
>> 
>> I just finished developing an application using Qt Designer in Python
>> that uses pyqwt, gpib, etc. How does one create standalone executables
>> for applications such as these ?
> 
> Generally, you can't, as Python is an interpreted programming language.
> However, there are some projects like py2exe in Windows which approximates
> what you want to do - port the Python code into a stand-alone application.

I should have added that my platform is Linux.

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


Re: Standalone applications ?

2005-08-13 Thread Paolo Alexis Falcone
On Sat, 13 Aug 2005 23:29:27 -0400, Madhusudan Singh wrote:

> Hi
> 
> I just finished developing an application using Qt Designer in Python that
> uses pyqwt, gpib, etc. How does one create standalone executables for
> applications such as these ?

Generally, you can't, as Python is an interpreted programming language.
However, there are some projects like py2exe in Windows which approximates
what you want to do - port the Python code into a stand-alone application.

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


Standalone applications ?

2005-08-13 Thread Madhusudan Singh
Hi

I just finished developing an application using Qt Designer in Python that
uses pyqwt, gpib, etc. How does one create standalone executables for
applications such as these ?

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


Re: Bug on Python2.3.4 [FreeBSD]?

2005-08-13 Thread Terry Reedy
> I am now enlightened as to the usefulness of 'r+', as it starts the
> read fp at the begining of the file.

Both 'r+' and 'w+' let you write anywhere, whereas 'a+' is supposed to make 
all writes EOF appends.  'r+' (and 'r') requires an existing file while 
'w+' (like 'w') will open a new file or truncate an existing file.

Terry J. Reedy



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


Re: Spaces and tabs again

2005-08-13 Thread John Machin
Dan Sommers wrote:
> On Sun, 14 Aug 2005 01:04:04 GMT,
> Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> 
> 
>>On 13 Aug 2005 13:18:21 -0700, [EMAIL PROTECTED] declaimed the following
>>in comp.lang.python:
> 
> 
>>>Are you kidding? You are going to MANDATE spaces?
>>>
>>
>>  After the backlash, Python 4.0 will ban leading spaces and require
>>tabs 
> 
> 
> Why not petition the unicode people to include PYTHON INDENT and PYTHON
> DEDENT code points, and leave the display up to the text editors?  ;-)
> 

Good idea, Dan. And when you don't want the indented/dedented display, 
but a repr-like "what's actually there", they could be rendered as 
little icons of a snake and a ladder respectively.

[It's a joke, Joyce.]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket setdefaulttimeout

2005-08-13 Thread John Machin
Dennis Lee Bieber wrote:

> 
>   I've got the opposite problem -- I'm on a dial-up (well, for a few
> more weeks -- until the DSL gear arrives). For some reason DNS lookups
> seem to be low priority and, if I'm downloading messages in Agent (from
> three servers yet) and email (Eudora), Firefox often comes back with a
> "host not found"; enter the same URL/bookmark again, and it finds the
> page. It seems my system times out DNS requests when 1) I have a lot of
> traffic on the dial-up connection, 2) the request may need to be
> traversed (not cached on Earthlink)

Dragging the thread off-topic a little:

I was having a similar DNS problem (host not found, try again 
immediately, 2nd try successful) but even in a no-other-load situation, 
and with this set of gear:

* ADSL with Netgear DG834G v2 "wireless ADSL firewall router"
* both hardwired and wireless LAN connection to router
* Firefox, Thunderbird [normally]
* IE6, Outlook Express [just to test if it was a Mozilla problem]
* Windows XP Professional SP2, Windows 2000 SP4

The problem stopped after I upgraded the router firmware from version 
1.something to 2.something, but this may be yet another instance of the 
"waved a dead chicken at the volcano" syndrome :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spaces and tabs again

2005-08-13 Thread Dan Sommers
On Sun, 14 Aug 2005 01:04:04 GMT,
Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

> On 13 Aug 2005 13:18:21 -0700, [EMAIL PROTECTED] declaimed the following
> in comp.lang.python:

>> 
>> Are you kidding? You are going to MANDATE spaces?
>> 
>   After the backlash, Python 4.0 will ban leading spaces and require
> tabs 

Why not petition the unicode people to include PYTHON INDENT and PYTHON
DEDENT code points, and leave the display up to the text editors?  ;-)

Regards,
Dan

-- 
Dan Sommers

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


Changing data of xhtml document

2005-08-13 Thread Thanos Tsouanas
Hello list!

I've got a unicode string which holds an xhtml website, begining with

tag.  Also, it writes the  tag which I want to avoid at this
stage.

Are there any really easy solutions to this problem?
Any modules that could be helpful for slight modification of such
sgmlish files?  The downside of SGMLParser is that I have to override
all parser functions to actually leave everything intact instead of
doing nothing and override characters(data) to print the altered data.

Thanks in advance!

-- 
Thanos Tsouanas  .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wx.MessageDialog displayed without components inside

2005-08-13 Thread perchef
nope, I have put md.Destroy() away and it didn't change something.
I don't think that's the problem because ShowModal() is a blocking
method, execution is stop until you press YES or NO (in my case with
wx.YES_NO)

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


Re: Permutation Generator

2005-08-13 Thread Jim Washington
On Fri, 12 Aug 2005 12:39:08 -0700, Talin wrote:

> I'm sure I am not the first person to do this, but I wanted to share 
> this: a generator which returns all permutations of a list:
> 
> def permute( lst ):
> if len( lst ) == 1:
> yield lst
> else:
> head = lst[:1]
> for x in permute( lst[1:] ):
> yield head + x
> yield x + head
> return
> 
> -- Talin

If we are sharing permutation algorithms today, here's one.

The following likes to be in a file called "permutation.py" for __main__
to work. A couple of lines went over 80 characters, so you might have to
put those back together.

-Jim Washington

""" ***Reversible*** Permutations using factoradics.

factoradic concept at:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/permutations.asp

Why permutations?  Sometimes, you need to list your objects in a different 
order.
Maybe, when you are dealing with something persistent like Zope, you wish
your users to access things in a different order than other users.  Think
quizzes or photo galleries.

You think you want randomness, but what you really want is that different users
get different orderings of things, so that the first item is likely different
for each individual.  But you do not really want randomness; you want a
particular user always to get the same ordering.

One way would be to store for each individual the complete list in order,
This is another way that allows you to just store an index that refers to a
particular ordering.

For a list of n items, there are n factorial (n!) possible permutations.  So,
any number from 0 to n!-1  is a valid index to a unique ordering.

If you have

foo = Permutation(['a','Fred',23,None])

the possible indices are numbered 0 to 23 (0 to 4!-1)

sam = foo.permutation(10)
mary = foo.permutation(4)

sam is ['Fred', None, 'a', 23]
mary is ['a', None,'Fred', 23]

An interesting thing about the factoradic method is its reversibility.

If you have a list: ['a','Fred',23,None]

and you are presented with an ordering: [23,'a',None,'Fred']
the factoradic method can algorithmically determine that this ordering is
index 13 of 24 of the possible permutations, without going forward through
your generating algorithm to get there.

foo = Permutation(['a','Fred',23,None])
ix = foo.getPermutationIndex([23,'a',None,'Fred'])

ix is 13.

For the above example, I used a list of mixed items; you probably will not.
Reversibility does not work if items are repeated, since it cannot know the
original positions of repeated items.  If you have duplicated items, use their
list index instead of the items themselves.

"""
try:
import psyco
psyco.full()
except:
pass

import random


def factoradic(anInt,order=0):
"""calculate the factoradic on anInt

>>> factoradic(859)
[1, 1, 0, 3, 0, 1, 0]

>>> factoradic(1123322213455539988899978655326328)
[1, 9, 22, 2, 20, 20, 7, 14, 0, 19, 2, 13, 2, 5, 14, 18, 2, 0, 10, 1, 9, 3, 
11, 9, 9, 4, 1, 4, 0, 0, 1, 1, 0, 0]

>>> factoradic(0,4)
[0, 0, 0, 0]

>>> factoradic(1)
[1, 0]

>>> factoradic(1047)
[1, 2, 3, 2, 1, 1, 0]

>>> factoradic(5,4)
[0, 2, 1, 0]


"""

factoradic = []

z = 0
while anInt > 0:
z += 1
factoradic.append(int(anInt % z))
anInt /= z


factoradic.reverse()
if order:
while len(factoradic) < order:
factoradic.insert(0,0)

return factoradic

def factorial(anInt):
"""factorial

>>> factorial(3)
6
>>> factorial(0)
1
>>> factorial(1)
1
"""
if anInt == 0:
return 1
if anInt < 0:
raise ValueError, "Cannot factorialize negative numbers"
result = 1

while anInt > 1:
result = result * anInt
anInt -= 1
return result


def unfactoradic(aList):
"""from a factoradic list, calculate the integer

>>> unfactoradic([1, 1, 0, 3, 0, 1, 0])
859

"""
aList.reverse()
result = 0
for idx,val in enumerate(aList):
result += factorial(idx) * val
return result



class Permutation(object):
"""Base object for doing permutations.  Generally initialized with a list
of the items to do permutations on.  Works by the factoradic method,
which provides reversibility."""

_order = None

def __init__(self,data):
self.data = data

def getOrder(self):
if not self._order:
self._order = len(self.data)
return self._order

def permutationIndices(self,anInt):
"""calculate the permutation indices of self from anInt

>>> z = Permutation([1,2,3,4,5,6,7])
>>> z.permutationIndices(1047)
[1, 3, 5, 4, 2, 6, 0]
>>> z = Permutation([0,1,2,3])
>>> z.permutationIndices(5)
[0, 3, 2, 1]


"""
f = factoradic(anInt,self.order)
temp = []
for k in f:
temp.append(k + 1)

data = [1]
   

BiskyMisky

2005-08-13 Thread BiskyMisky.com
BiskyMisky

www.biskymisky.com

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


Re: thread limit in python

2005-08-13 Thread Bryan Olson
Peter Hansen wrote:
 > Bryan Olson wrote:
 >
 >> Peter Hansen wrote:
 >>  > My question was in the context of the OP's situation.  What
 >> possible use
 >>  > for 1000 OS threads could he have?
 >>
 >> Is this a language thing? Surely you realize that "what possible
 >> use could  be" carries an insinuation that  is not
 >> such a good idea.
 >
 > Obviously.  Is it no longer permissible to question someone's approach
 > to doing something?
 >
 > You're questioning my approach to inquiring after the OP's requirements,
 > and clearly you believe there is a better way to do it.  Wonderful.  You
 > may even be right.  It's also off-topic.

I'm just arguing against the notion that a couple thousands
threads is generally a bad idea; if you didn't mean to suggest
that, then I misread you. There are a lot of neat ways to do
things that use one-or-two threads per thing-they-can-support.
In days past such methods did not scale well, but on modern
systems that is no longer true.


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


Re: Zope, Python 2.4 pythonScripts import problem

2005-08-13 Thread Josef Meile
Hi,

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

You may then ask in a zope or plone list. This is a python specific
list. But I will answer you any way.

> After import a old Plone site from the following platform
> Zope-2-7-4, Python 2.3.3, Plone 2.0.3 to the new one, I get error when
> I visit PuthonScript in the ZMI.
 > "invalid syntax (Script (Python), line 1)"
 >
 > There 2 are examples of 1 line:
 > from DateTime import DateTime
 > and
 > request = container.REQUEST
 >
 > There is no syntax error!
 >
 > When I just save this script in ZMI then error disappers :)

So, you are exporting the plone site, then importing it? I had once some
problem like that and the solution was to call an script that compiled
all python scripts again. I'm not sure if this solves your problem, but
you may look at the first script here:

http://www.zope.org/Members/goppelt/2-4-3Upgrade

> What is the reason???

As I said, you may ask in a zope or plone list for a better answer. My
best guess is that somewhere there is some old compiled version of your
script.

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

I just have to warn you that some persons in the zope list are going to
tell you "Python 2.4 isn't a supported option for zope". So, you may use
it only for testing and not in a production environment.

Regards,
Josef

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


Re: Catching stderr output from graphical apps

2005-08-13 Thread Bryan Olson
Robert Kern wrote:
 > Christopher Subich wrote:
 >> If you can get a cross-platform solution, please re-annoucne it; this
 >> sounds like a really neat module to have handy for graphical programs.
 >
 >
 > Look at py.io[1]. It seems to have implemented a probably-cross-platform
 > solution. Please check it out and let c.l.py and the py mailing list
 > know if it works on Windows.
 >
 > [1] http://codespeak.net/py/current/doc/home.html

Thanks guys. I found I had a bootable Linux system. With some
stuff  from py.io, and *without* the fsync(), this one worked on
Windows and Linux in my not-so-extensive testing.

-- 
--Bryan



"""

 Import this module into graphical Python apps to provide a
 sys.stderr. No functions to call, just import it. It uses
 only facilities in the Python standard distribution.

 If nothing is ever written to stderr, then the module just
 sits there and stays out of your face. Upon write to stderr,
 it launches a new process, piping it error stream. The new
 process throws up a window showing the error messages.

"""

import sys
import os
import thread

import time

if __name__ == '__main__':

 from Tkinter import *
 import Queue
 queue = Queue.Queue(99)
 def read_stdin(app):
 fd = os.dup(sys.stdin.fileno())
 infile = os.fdopen(fd, 'r', 0)
 while 1:
 data = os.read(infile.fileno(), 2048)
 queue.put(data)
 if not data:
 break
 class Application(Frame):
 def __init__(self, master=None):
 Frame.__init__(self, master)
 self.master.title("Error Stream from run of %s" % sys.argv[-1])
 self.pack(fill=BOTH, expand=YES)
 self.logwidget = Text(self)
 self.logwidget.pack(side=TOP, fill=BOTH, expand=YES)
 # Disallow key entry, but allow copy with 
 self.logwidget.bind('', lambda x: 'break')
 self.logwidget.bind('', lambda x: None)
 self.after(200, self.start_thread, ())
 def start_thread(self, _):
 thread.start_new_thread(read_stdin, (self,))
 self.after(200, self.check_q, ())
 def check_q(self, _):
 go = True
 while go:
 try:
 data = queue.get_nowait()
 if not data:
 self.logwidget.configure(foreground ='#AA')
 data = "\n File Closed \n"
 go = False
 self.logwidget.insert(END, data)
 self.logwidget.see(END)
 except Queue.Empty:
 self.after(200, self.check_q, ())
 go = False
 app = Application()
 app.mainloop()

else:

 class ErrorPipe(object):
 def __init__(self):
 self.lock = thread.allocate_lock()
 self.pipe = None
 def on_first_write(self):
 command = "%s %s %s" % (sys.executable, __file__, sys.argv[0])
 self.rawpipe = os.popen(command, 'w')
 fd = os.dup(self.rawpipe.fileno())
 self.pipe = os.fdopen(fd, 'w', 0)
 def write(self, data):
 self.lock.acquire()
 try:
 if not self.pipe:
 self.on_first_write()
 self.pipe.write(data)
 finally:
 self.lock.release()
 sys.stderr = ErrorPipe()
 # sys.stdout = ErrorPipe()


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


Re: Dictionary inheritance

2005-08-13 Thread Elmo Mäntynen
On Fri, 12 Aug 2005 12:44:11 -0700, Talin wrote:

> I want to make a dictionary that acts like a class, in other words, 
> supports inheritance: If you attempt to find a key that isn't present, 
> it searches a "base" dictionary, which in turn searches its base, and so on.
> 
> Now, I realize its fairly trivial to code something like this using 
> UserDict, but given that classes and modules already have this behavior, 
> is there some built-in type that already does this?
> 
> (This is for doing nested symbol tables and such.)
> 
> ---

You could always do:

class nestedDict(dict):
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spaces and tabs again

2005-08-13 Thread sigzero
Ah!!! I read it and noticed the date "April 1st".  Doh!

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


Re: Spaces and tabs again

2005-08-13 Thread sigzero
That is rediculous. If that happens...Python comes of my list of
languages to use. Are they going to mandate 4 spaces as well?

Robert

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


Re: thread limit in python

2005-08-13 Thread Peter Hansen
Bryan Olson wrote:
> Peter Hansen wrote:
>  > My question was in the context of the OP's situation.  What possible use
>  > for 1000 OS threads could he have?
> 
> Is this a language thing? Surely you realize that "what possible
> use could  be" carries an insinuation that  is not
> such a good idea. 

Obviously.  Is it no longer permissible to question someone's approach 
to doing something?

You're questioning my approach to inquiring after the OP's requirements, 
and clearly you believe there is a better way to do it.  Wonderful.  You 
may even be right.  It's also off-topic.

I'm questioning why the OP thinks he needs more than 1000 threads, and 
I'm genuinely interested in his answer.  Not your answer, unless you 
have personal knowledge of his actual situation.

If it's merely a contrived example, I have no further interest in the 
thread, as I'm interested in practical matters.  If he thinks he has a 
real need, then I happen to believe there's very likely a better way to 
do it.  And _my_ question happens to be on topic...

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


Re: Bug on Python2.3.4 [FreeBSD]?

2005-08-13 Thread [EMAIL PROTECTED]
Using FreeBSD 4.10 and Python 2.3.4:


> uname -a
FreeBSD garner_ted 4.10-RELEASE FreeBSD 4.10-RELEASE #7: Thu Apr 28
22:44:58 CDT 2005

>python
Python 2.3.4 (#4, Nov 19 2004, 15:37:16)
[GCC 2.95.4 20020320 [FreeBSD]] on freebsd4
Type "help", "copyright", "credits" or "license" for more information.

using f.read('test','r+')
I get the existing data, and the
f.write('testing')
successfully appends the text in the file.

The 'a+'  mode works as described, i.e. I need to f.seek(0) to read the
data.

I am now enlightened as to the usefulness of 'r+', as it starts the
read fp at the begining of the file.

Curtis W. Rendon

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


Parsing a log file

2005-08-13 Thread CG
I am looking for a way to parse a simple log file to get the
information in a format that I can use.  I would like to use python,
but I am just beginning to learn how to use it.  I am not a programmer,
but have done some simple modifications and revisions of scripts.  I am
willing to attempt this on my own, if someone can point me in the right
direction (any example scripts that do similar things would be
helpful).  This doesn't have to be Python, but I need a cross-platform
solution (i.e. Perl or some other kind of script).  I just wanted to
try Python because I like the concept of it.

Here is my scenario:
I have a program that connects and disconnects to a server.  It writes
a simple log file like this:

08-13-2005  13:19:37:564 Program: CONNECTED to 'Server'
08-13-2005  15:40:08:313 Program: DISCONNECTED from 'Server'
08-13-2005  15:45:39:234 Program: CONNECTED to 'Server'
08-13-2005  15:55:18:113 Program: DISCONNECTED from 'Server'
08-13-2005  16:30:57:264 Program: CONNECTED to 'Server'
08-13-2005  16:59:46:417 Program: DISCONNECTED from 'Server'
08-13-2005  17:10:33:264 Program: CONNECTED to 'Server'
08-13-2005  18:25:26:316 Program: DISCONNECTED from 'Server'
08-13-2005  18:58:13:564 Program: CONNECTED to 'Server'
08-13-2005  19:29:10:715 Program: DISCONNECTED from 'Server'

What I basically want to do is end up with a text file that can be
easily imported into a database with a format like this (or I guess it
could be written in a SQL script form that could write directly to a
database like Mysql):

Connect_Date Connect_Time Disconnect_date Disconnect_time User
  --- --- ---
08-13-2005   13:19:37 08-13-2005  15:40:08John
08-13-2005   15:45:39 08-13-2005  15:55:18John
08-13-2005   16:30:57 08-13-2005  16:59:46John
08-13-2005   17:10:33 08-13-2005  18:25:26John
08-13-2005   18:58:13 08-13-2005  19:29:10John

Here are some notes about this:
* the username would come from the log file name (i.e.
John_Connect.log)
* I don't need the fractions of seconds in the timestamps
* I only need date, time, and connect or disconnect, the other info is
not important
* If it is possible to calculate the elapsed time between Connect and
Disconnect and create a new field with that data, that would help (but
I can easily do that with SQL queries)
* This log file layout seems to be consistent
* There may not be a "disconnect" statement if the log file is read
while connected, so the next time it would have to insert the
disconnect information.  The file will be read quite regularly, so this
is very likely.
* This would eventually need to be done without intervention (maybe
every 5 minutes).

I am open to other ideas or existing programs and am flexible about the
final solution.

Thanks,
Clint

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


Re: Spaces and tabs again

2005-08-13 Thread Jeff Schwab
Christopher Subich wrote:
> [EMAIL PROTECTED] wrote:
> 
>> Are you kidding? You are going to MANDATE spaces?
> 
> 
> Actually, future whitespace rules will be extensive.  See:
> http://64.233.187.104/search?q=cache:k1w9oZr767QJ:www.artima.com/weblogs/viewpost.jsp%3Fthread%3D101968
>  
> 
> (google cache of 
> http://www.artima.com/weblogs/viewpost.jsp?thread=101968 because it 
> seems to be down at the moment)
> 
> The only change from April 1, 2005 is that the enforcement is punted 
> until Python 3.0, because of the source-incompatible nature of the change.
> 
> "Lrf, vg'f na Ncevy Sbbyf' wbxr.".decode('rot13')

Downright unpythonic!

--
"""Va Nhthfg?  Gung'f pehry.  V nyzbfg jrag onpx gb Crey!

Univat arire frra "GBBJGQV" orsber abj, V nz fgvyy ynhtuvat cerggl uneq.
""".decode('rot13')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using globals with classes

2005-08-13 Thread Madhusudan Singh
Scott David Daniels wrote:

> Madhusudan Singh wrote:
>>  I am using qwtplot to display a running plot :
>>
> The way I'd normally accomplish this is to separate the setup and use
> by defining a class:
> 

How would one enable dynamic autoscaling of the axes ?

I am using setAxisAutoScale, and when the application ends, I do get
correctly autoscaled axes, but not while the measurement is in progress.
-- 
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2005-08-13 Thread gdcook
Can anyone help with this?

I am running:
Python 2.3.4
SWIG 1.3.23
openssl 0.9.8

Do I need to reconfig Python with certain ssl ciphers?

This is the output I receive when running alltests:

[EMAIL PROTECTED] tests]# python alltests.py
bind:
Address already in use
Ebind: Address already in use
Ebind: Address already in use
Ebind: Address already in use
Ebind: Address already in use
Ebind: Address already in use
E
==
ERROR: test_cipher_mismatch (test_ssl.SSLClientTestCase)
--
Traceback (most recent call last):
  File "/usr/local/src/m2crypto-0.13/tests/test_ssl.py", line 89, in
test_cipher_mismatch
ctx = SSL.Context()
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 41, in __init__
map()[self.ctx] = self
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 20, in __setitem__
self.map[key] = value
TypeError: unhashable type

==
ERROR: test_cipher_ok (test_ssl.SSLClientTestCase)
--
Traceback (most recent call last):
  File "/usr/local/src/m2crypto-0.13/tests/test_ssl.py", line 115, in
test_cipher_ok
ctx = SSL.Context()
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 41, in __init__
map()[self.ctx] = self
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 20, in __setitem__
self.map[key] = value
TypeError: unhashable type

==
ERROR: test_no_such_cipher (test_ssl.SSLClientTestCase)
--
Traceback (most recent call last):
  File "/usr/local/src/m2crypto-0.13/tests/test_ssl.py", line 102, in
test_no_such_cipher
ctx = SSL.Context()
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 41, in __init__
map()[self.ctx] = self
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 20, in __setitem__
self.map[key] = value
TypeError: unhashable type

==
ERROR: test_server_simple (test_ssl.SSLClientTestCase)
--
Traceback (most recent call last):
  File "/usr/local/src/m2crypto-0.13/tests/test_ssl.py", line 55, in
test_server_simple
ctx = SSL.Context()
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 41, in __init__
map()[self.ctx] = self
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 20, in __setitem__
self.map[key] = value
TypeError: unhashable type

==
ERROR: test_tls1_nok (test_ssl.SSLClientTestCase)
--
Traceback (most recent call last):
  File "/usr/local/src/m2crypto-0.13/tests/test_ssl.py", line 66, in
test_tls1_nok
ctx = SSL.Context('tlsv1')
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 41, in __init__
map()[self.ctx] = self
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 20, in __setitem__
self.map[key] = value
TypeError: unhashable type

==
ERROR: test_tls1_ok (test_ssl.SSLClientTestCase)
--
Traceback (most recent call last):
  File "/usr/local/src/m2crypto-0.13/tests/test_ssl.py", line 78, in
test_tls1_ok
ctx = SSL.Context('tlsv1')
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 41, in __init__
map()[self.ctx] = self
  File "/usr/local/lib/python2.3/site-packages/M2Crypto/SSL/Context.py",
line 20, in __setitem__
self.map[key] = value
TypeError: unhashable type

--
Ran 70 tests in 3.599s

FAILED (errors=6)

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


Re: Spaces and tabs again

2005-08-13 Thread Christopher Subich
[EMAIL PROTECTED] wrote:

> Are you kidding? You are going to MANDATE spaces?

Actually, future whitespace rules will be extensive.  See:
http://64.233.187.104/search?q=cache:k1w9oZr767QJ:www.artima.com/weblogs/viewpost.jsp%3Fthread%3D101968
(google cache of 
http://www.artima.com/weblogs/viewpost.jsp?thread=101968 because it 
seems to be down at the moment)

The only change from April 1, 2005 is that the enforcement is punted 
until Python 3.0, because of the source-incompatible nature of the change.

"Lrf, vg'f na Ncevy Sbbyf' wbxr.".decode('rot13')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Permutation Generator

2005-08-13 Thread David Isaac
"Talin" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I wanted to share
> this: a generator which returns all permutations of a list:


Try this instead:
def permuteg(lst): return ([lst[i]]+x
   for i in range(len(lst))
   for x in permute(lst[:i]+lst[i+1:])) \
   or [[]]

Alan Isaac


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


Re: Spaces and tabs again

2005-08-13 Thread sigzero

Aahz wrote:

> Python 3.0 will prohibit tabs.
> --
> Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/
>
> The way to build large Python applications is to componentize and
> loosely-couple the hell out of everything.

Are you kidding? You are going to MANDATE spaces?

Robert

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


Re: "Compile time" checking?

2005-08-13 Thread Benjamin Niemann
[EMAIL PROTECTED] wrote:

> On Fri, 12 Aug 2005 22:25:07 -0700
> Steve Jorgensen wrote:
> 
>> Since Python does not use manifest typing, there's not much you can do
>> about this, but typeless languages like this are great if you're using a
>> process
>> that finds the errors the compiler would otherwise find.  I'm referring,
>> of course, to Test Driven Development (TDD).
>> 
>> If you do TDD, you won't miss compile-time checking much.  In fact, the
>> extra kruft that manifest typing requires is an annoying burden when
>> doing TDD, so Python is a breath of fresh air in this regard.
> 
> What test should one implement to catch that kind of errors like in OP
> example?

A 'good' testsuite should run each line of the code at least once. There's
more to do for a good code coverage, but that's the most basic requirement.
So the faulty line will be executed by the testsuite and the runtime
checking will raise an exception.

Static typing is a very rudimentary type of code checking that is performed
by the compiler with 100% code coverage. Such test won't tell you, if your
code is actually doing what it is supposed to do (or anything sensible at
all) and are mostly useless. If you think that code quality is important,
you'll have to perform much more and more sophisticated tests. Such a
testsuite is usually (I can't think of cases where it is not) a superset of
static code checking - all type bugs are found be the testsuite even in the
absence if static type checking.

So you won't loose anything, if you drop static typing.

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: thread limit in python

2005-08-13 Thread Bryan Olson
Peter Hansen wrote:
 > My question was in the context of the OP's situation.  What possible use
 > for 1000 OS threads could he have?

Is this a language thing? Surely you realize that "what possible
use could  be" carries an insinuation that  is not
such a good idea. Possible uses are many and perfectly
reasonable, such as building a quick, responsive server like
MySQL.


 > Is the OP's situation IO-bound,
 > CPU-bound, or just an experiment to see how many threads he can pile on
 > the machine at one time?  The fact that these threads are all sleeping
 > implies the latter, though what he posted could have been a contrived
 > example.  I'm interested in the real requirements, and whether more than
 > 1000 threads in this day and age (not some imaginary future) might not
 > be a poor approach.

If you're interested in his requirements, why not just ask him
about his requirements?  Kind of premature to condemn his
approach.


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


Re: catching all exceptions [SOLVED]

2005-08-13 Thread a_geek
Hello,

Tomasz Lisowski wrote:
>> Well, actually the second statement doesn't even compile... any ideas
>> why I shouldn't be able to catch "anonymous" exceptions like this, or
>> whether and how I can (and only overlooked it)?

[ one of three suggestions: ]

> Try this:

Ok, so the answer simply was that I didn't see "it", although the
solution is in the manual.

Thank you!


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


Re: Spaces and tabs again

2005-08-13 Thread Aahz
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>
>I know that some people likes tabs, and other people likes spaces, so
>probably a single standard cannot be enforced, but I think the python
>compiler must generate an error (and stop compiling) when the
>sourcecode of a module contains both spaces and tabs to indent the
>lines of code (and comments lines too?).

Python 3.0 will prohibit tabs.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Re: catching all exceptions

2005-08-13 Thread Tomasz Lisowski
> Hello,
> 
> I'd like to catch all exeptions and be able to inspect them.
> 
> The simple case: I know which exceptions I'll get:
> 
> # standard textbook example:
> try:
> something()
> except ThisException, e:
> print "some error occurred: ", str(e)
> 
> 
> The not-so-simple case: Handling all other exceptions:
> 
> # nice-to-have:
> try:
> something()
> except *, e:
> print "some error occurred: ", type(e), str(e)
> 
> 
> Well, actually the second statement doesn't even compile... any ideas
> why I shouldn't be able to catch "anonymous" exceptions like this, or
> whether and how I can (and only overlooked it)?
> 
> 
> TIA!
> 
> 
> Kind Regards,
> Toni

Try this:

import sys

try:
   something()
except:
   info = sys.exc_info()
   ...

and you can inspect the tuple info, which contains the exception type, 
value, and traceback.

Best regards,
Tom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to append semicolon to a variable

2005-08-13 Thread Grant Edwards
On 2005-08-13, tiissa <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:

>> s = ';'.join([couch,price,sdate,city])
>> print s
>
> I'll risk myself with something like:
>
> s = ';'.join([tag.string for tag in [couch,price,sdate,city]])
>
> Of course, from the question I wouldn't have any clue. I just like doing 
> some guessing on problems I know nothing about. ;)
>
>>>p.s. i tried couch = couch + ';'
>>>and then i tried couch = couch + ";"
>> 
>> both of those should have worked fine.
>
> Not really. It seems to me the OP is using BeautifulSoup (or some other 
> SGML parser). In this case, couch and others are not strings but objects.

Seems like a reasonable guess.

> It may also be that strUrl is their parent (but I wouldn't know, how 
> would I?)

Nope. :)

-- 
Grant Edwards   grante Yow!  Are you mentally here
  at   at Pizza Hut??
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Compile time" checking?

2005-08-13 Thread Steve Jorgensen
On Sat, 13 Aug 2005 11:04:55 +0400, <[EMAIL PROTECTED]> wrote:

>On Fri, 12 Aug 2005 22:25:07 -0700
>Steve Jorgensen wrote:
>
>> Since Python does not use manifest typing, there's not much you can do about
>> this, but typeless languages like this are great if you're using a process
>> that finds the errors the compiler would otherwise find.  I'm referring, of
>> course, to Test Driven Development (TDD).
>> 
>> If you do TDD, you won't miss compile-time checking much.  In fact, the extra
>> kruft that manifest typing requires is an annoying burden when doing TDD, so
>> Python is a breath of fresh air in this regard.
>
>What test should one implement to catch that kind of errors like in OP
>example?
>
>> On 10 Aug 2005 08:53:15 -0700, "Qopit" <[EMAIL PROTECTED]> wrote:
>> 
>> >#
>> >def tester(a,b,c):
>> >  print "bogus test function",a,b,c
>> >tester(1,2,3)  #this runs fine
>> >tester(1,2)#this obviously causes a run-time TypeError exception
>> >#

None - other tests you would write would fail if other code in your system is
trying to call a procedure with the wrong number of parameters.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Compile time" checking?

2005-08-13 Thread en.karpachov
On Fri, 12 Aug 2005 22:25:07 -0700
Steve Jorgensen wrote:

> Since Python does not use manifest typing, there's not much you can do about
> this, but typeless languages like this are great if you're using a process
> that finds the errors the compiler would otherwise find.  I'm referring, of
> course, to Test Driven Development (TDD).
> 
> If you do TDD, you won't miss compile-time checking much.  In fact, the extra
> kruft that manifest typing requires is an annoying burden when doing TDD, so
> Python is a breath of fresh air in this regard.

What test should one implement to catch that kind of errors like in OP
example?

> On 10 Aug 2005 08:53:15 -0700, "Qopit" <[EMAIL PROTECTED]> wrote:
> 
> >#
> >def tester(a,b,c):
> >  print "bogus test function",a,b,c
> >tester(1,2,3)  #this runs fine
> >tester(1,2)#this obviously causes a run-time TypeError exception
> >#

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


COM access sooo slow !?

2005-08-13 Thread kowald
Hi everybody,

I'm using win32com.client.Dispatch() to access a COM object (a
database) from Python and in principle is works fine.

However, it is unbelievably slow :-(
It is 70 times slower than a C++ version of the same program !

Is this a well known problem of the Python COM interface or could it be
specific to this special COM object?

Any ideas?

Many thanks,

Axel

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


Re: catching all exceptions

2005-08-13 Thread Bengt Richter
On Sat, 13 Aug 2005 17:42:00 +0200, [EMAIL PROTECTED] wrote:

>Hello,
>
>I'd like to catch all exeptions and be able to inspect them.
>
>The simple case: I know which exceptions I'll get:
>
># standard textbook example:
>try:
>something()
>except ThisException, e:
>print "some error occurred: ", str(e)
>
>
>The not-so-simple case: Handling all other exceptions:
>
># nice-to-have:
>try:
>something()
>except *, e:
>print "some error occurred: ", type(e), str(e)
>
>
>Well, actually the second statement doesn't even compile... any ideas
>why I shouldn't be able to catch "anonymous" exceptions like this, or
>whether and how I can (and only overlooked it)?
>
>
>TIA!
>

 >>> def test(something):
 ... try:
 ... something()
 ... except Exception, e:
 ... print '%s: %s'% (e.__class__.__name__, e)
 ...
 >>> test(lambda: 1/0)
 ZeroDivisionError: integer division or modulo by zero
 >>> test(lambda: unk)
 NameError: global name 'unk' is not defined
 >>> test(lambda: open('unk'))
 IOError: [Errno 2] No such file or directory: 'unk'

All exceptions should derive from Exception, so the above should catch them,
although there are deprecated string exceptions that will not be caught.
You can catch these with a bare except, but it is probably better not to,
so you will know there's something to clean up.

If you do have to deal with them, you can then catch them by name individually,
or all with the bare except, e.g.,

 >>> def strexraiser(s): raise s
 ...
 >>> def test(something):
 ... try:
 ... something()
 ... except Exception, e:
 ... print '%s: %s'% (e.__class__.__name__, e)
 ... except 'ugh':
 ... print 'Caught "ugh"'
 ... except:
 ... print sys.exc_info()
 ...
 >>> import sys # forgot, will need when above executes ;-)
 >>>
 >>> test(lambda:strexraiser('ugh'))
 Caught "ugh"
 >>> test(lambda:strexraiser('gak'))
 ('gak', None, )
 >>> test(lambda:1/0)
 ZeroDivisionError: integer division or modulo by zero

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


Re: how to append semicolon to a variable

2005-08-13 Thread tiissa
Grant Edwards wrote:
> On 2005-08-13, yaffa <[EMAIL PROTECTED]> wrote:
> 
>>i have the following lines of python code:
>>
>>  couch = incident.findNextSibling('td')
>>  price = couch.findNextSibling('td')
>>  sdate = price.findNextSibling('td')
>>  city = sdate.findNextSibling('td')
>>  strUrl = addr.b.string
>>currently what this ends up doing is creating something like this
>>
>>couch3201/01/2004newyork
>>
>>now what i want to do is add a semicolon after the couch, price, sdate,
>>city so that i get something like this
>>
>>couch;32;01/01/2004;new york
> 
> 
> Try this:
> 
> s = ';'.join([couch,price,sdate,city])
> print s

I'll risk myself with something like:

s = ';'.join([tag.string for tag in [couch,price,sdate,city]])

Of course, from the question I wouldn't have any clue. I just like doing 
some guessing on problems I know nothing about. ;)

>>p.s. i tried couch = couch + ';'
>>and then i tried couch = couch + ";"
> 
> both of those should have worked fine.

Not really. It seems to me the OP is using BeautifulSoup (or some other 
SGML parser). In this case, couch and others are not strings but objects.
It may also be that strUrl is their parent (but I wouldn't know, how 
would I?)

> Perhaps you ought to read through the tutorial?

That's always useful.
However, the first thing is to put the minimal context in your question 
to help the people you want your answers from understanding your issue.
I would advise you to read tutorials and documentations on the modules 
you're using as well as learning to ask meaningful questions[1].


[1] http://www.catb.org/~esr/faqs/smart-questions.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to append semicolon to a variable

2005-08-13 Thread Bengt Richter
On 13 Aug 2005 08:14:32 -0700, "yaffa" <[EMAIL PROTECTED]> wrote:

>dear folks,
>
>i have the following lines of python code:
>
>couch = incident.findNextSibling('td')
>   price = couch.findNextSibling('td')
>   sdate = price.findNextSibling('td')
>   city = sdate.findNextSibling('td')
>   strUrl = addr.b.string
>currently what this ends up doing is creating something like this
>
>couch3201/01/2004newyork
>
>now what i want to do is add a semicolon after the couch, price, sdate,
>city so that i get something like this
>
>couch;32;01/01/2004;new york
>
>does anyone know how to do this?
>
>thanks
>
>yaffa
>
>p.s. i tried couch = couch + ';' and then i tried couch = couch + ";"
>and then i tried couch = couch.append ';'
>
Assuming all your findNextSibling calls result in strings, as in

 >>> couch = 'couch'
 >>> price = '32'
 >>> sdate = '01/01/2004'
 >>> city = 'newyork'
 >>>

You can put them in a list
 >>> [couch, price, sdate, city]
 ['couch', '32', '01/01/2004', 'newyork']

And join them with a string inserted between each successive pair of elements

 >>> ';'.join([couch, price, sdate, city])
 'couch;32;01/01/2004;newyork'

If you like a space after each ';', just include it in the joiner string

 >>> '; '.join([couch, price, sdate, city])
 'couch; 32; 01/01/2004; newyork'
 >>>

If all your items weren't string type, you'll have to convert first, e.g.,
 >>> price = 32
 >>> '; '.join([couch, price, sdate, city])
 Traceback (most recent call last):
   File "", line 1, in ?
 TypeError: sequence item 1: expected string, int found
 >>> '; '.join(map(str,[couch, price, sdate, city]))
 'couch; 32; 01/01/2004; newyork'

If you have 2.4 and don't like map, you can use a generator expression:

 >>> '; '.join(str(x) for x in (couch, price, sdate, city))
 'couch; 32; 01/01/2004; newyork'

or if you want the quoted strings

 >>> '; '.join(repr(x) for x in (couch, price, sdate, city))
 "'couch'; 32; '01/01/2004'; 'newyork'"

Note: if you want ';' appended to each item instead of just between items, you
can just add ';' to the whole thing

 >>> '; '.join(str(x) for x in (couch, price, sdate, city)) + ';'
 'couch; 32; 01/01/2004; newyork;'

Which avoids the trailing blank you would get if you appended '; ' to every item
before joining them, as in

 >>> ''.join(('%s; '%x) for x in (couch, price, sdate, city))
 'couch; 32; 01/01/2004; newyork; '

or

 >>> ''.join((str(x) + '; ') for x in (couch, price, sdate, city))
 'couch; 32; 01/01/2004; newyork; '

HTH

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


Re: wx.MessageDialog displayed without components inside

2005-08-13 Thread stas
On Sat, 13 Aug 2005 09:37:15 -0700, perchef wrote:

> Is there a reason why a wx.MessageDialog would be displayed without
> components inside ?
> 
> this :
> 
> md = wx.MessageDialog(None,'foo','bar',wx.YES_NO)
Here you create a dialog

> result = md.ShowModal()
Now you show it

> md.Destroy()
But right after showing it, you destroy it.
 
> In my application, give me :
> http://img252.imageshack.us/my.php?image=messagedialog6nw.jpg
> 
> This isn't a bug in wxPython because when I use the same code in
> pyshell I obtain the expected result. So, there must be a reason but I
> can't figure out why.
Because in the shell you first have to type the Destroy call
so the dialog has some time to live. :-)

Stas



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


Re: how to append semicolon to a variable

2005-08-13 Thread Grant Edwards
On 2005-08-13, yaffa <[EMAIL PROTECTED]> wrote:

> i have the following lines of python code:
>
>   couch = incident.findNextSibling('td')
>   price = couch.findNextSibling('td')
>   sdate = price.findNextSibling('td')
>   city = sdate.findNextSibling('td')
>   strUrl = addr.b.string
> currently what this ends up doing is creating something like this
>
> couch3201/01/2004newyork
>
> now what i want to do is add a semicolon after the couch, price, sdate,
> city so that i get something like this
>
> couch;32;01/01/2004;new york

Try this:

s = ';'.join([couch,price,sdate,city])
print s

> p.s. i tried couch = couch + ';'
> and then i tried couch = couch + ";"

both of those should have worked fine.

> and then i tried couch = couch.append ';'

 1) The append() method of a sequence doesn't return anything.

 2) You call methods using ()

 3) String are immutable, and therefore don't have an append
method.

Perhaps you ought to read through the tutorial?

-- 
Grant Edwards   grante Yow!  LOOK!!! I'm WALKING
  at   in my SLEEP again!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Aug 12)

2005-08-13 Thread Cameron Laird
QOTW:  "... So I started profiling the code and the slowdown was actually
taking place at places where I didn't expect it." -- Guyon Mor?e (and about
twenty-three thousand others)

"[A] suggestion from the world of 'agile development': stop making so many
decisions and start writing some actual code!" -- Peter Hansen


Scott David Daniels and others illustrate that the most common
answer for Python is, "It's (already) in there."  In the case at
hand the subject is primitive symbolic arithmetic:

http://groups.google.com/group/comp.lang.python/index/browse_frm/thread/13ed519653969e55/

Andy Smith rails against "frameworks":
http://an9.org/devdev/why_frameworks_suck?sxip-homesite=&checked=1  

"Porcupine is a [Python-based] Web application server that features
an embedded object database, the Porcupine Object Query Language,
XMLRPC support, and QuiX, an integrated JavaScript XUL motor."
http://www.innoscript.org

Getters and setters are (mostly) for other languages; Python has
properties (and descriptors!):

http://groups.google.com/group/comp.lang.python/browse_thread/thread/f903ab167c91e6ce/

Ramza Brown confusingly but helpfully repackages "the absolute
minimum libraries needed for Python to work with Win32":

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d0d4e4303e985729/

Paolino offers a technique for *pruning* attributes in a subclass:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/1805446521e8f34e/

Hard though it may be for some of us to accept, a zillion threads
might not be all bad.
http://www.usenix.org/events/hotos03/tech/vonbehren.html

Python helps win awards:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/c6190563601c437f/

Python fits on small machines, sort-of:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/834f5b571be0b5f6/



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

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

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

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

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

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

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

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

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

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

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Pyt

wx.MessageDialog displayed without components inside

2005-08-13 Thread perchef
Is there a reason why a wx.MessageDialog would be displayed without
components inside ?

this :

md = wx.MessageDialog(None,'foo','bar',wx.YES_NO)
result = md.ShowModal()
md.Destroy()

In my application, give me :
http://img252.imageshack.us/my.php?image=messagedialog6nw.jpg

This isn't a bug in wxPython because when I use the same code in
pyshell I obtain the expected result. So, there must be a reason but I
can't figure out why.

Thanks.

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


Re: catching all exceptions

2005-08-13 Thread Paolino
[EMAIL PROTECTED] wrote:
> Hello,
> 
> I'd like to catch all exeptions and be able to inspect them.
> 
> The simple case: I know which exceptions I'll get:
> 
> # standard textbook example:
> try:
> something()
> except ThisException, e:
> print "some error occurred: ", str(e)
> 
> 
> The not-so-simple case: Handling all other exceptions:
> 
> # nice-to-have:
> try:
> something()
> except *, e:
> print "some error occurred: ", type(e), str(e)
> 
> 
except Exception:# catch them all.

Then use moudule 'traceback' to inspect

Paolino





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


Re: thread limit in python

2005-08-13 Thread Peter Hansen
Bryan Olson wrote:
> Peter Hansen wrote:
>  > Probably, but I haven't yet seen anyone ask the real important question.
>  >  What possible use could you have for more than 1000 *simultaneously
>  > active* threads?  There are very likely several alternative approaches
>  > that will fit your use case and have better characteristics (e.g. higher
>  > performance, simpler code, safer architecture, etc).
> 
> Threading systems have come a long way in the last decade or so,
> and they're still advancing. 64-bit, multi-core processors make
> mega-threading even more attractive.
> 
> To read why zillions of threads are good, see:
>   http://www.usenix.org/events/hotos03/tech/vonbehren.html

Judging by the abstract alone, that article promotes "user-level" 
threads, not OS threads, and in any case appears (with a quick scan) to 
be saying nothing more than that threads are not *inherently* a bad 
idea, just that current implementations suffer from various problems 
which they believe could be fixed.

My question was in the context of the OP's situation.  What possible use 
for 1000 OS threads could he have?  (Not "could his requirements be 
answered with a non-existent proposed improved-performance 
implementation of threads?")

> Prediction: Ten years from now, someone will ask that same
> "What possible use..." question, except the number of threads
> will be a million.

Perhaps.  And in ten years it will still be a valid question whenever 
the context is not fully known.  Is the OP's situation IO-bound, 
CPU-bound, or just an experiment to see how many threads he can pile on 
the machine at one time?  The fact that these threads are all sleeping 
implies the latter, though what he posted could have been a contrived 
example.  I'm interested in the real requirements, and whether more than 
1000 threads in this day and age (not some imaginary future) might not 
be a poor approach.

(For the record, Bryan, I am a strong proponent of thread systems for 
many of the reasons the authors of that article put forth.  None of 
which means my question was without merit.)

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


catching all exceptions

2005-08-13 Thread a_geek
Hello,

I'd like to catch all exeptions and be able to inspect them.

The simple case: I know which exceptions I'll get:

# standard textbook example:
try:
something()
except ThisException, e:
print "some error occurred: ", str(e)


The not-so-simple case: Handling all other exceptions:

# nice-to-have:
try:
something()
except *, e:
print "some error occurred: ", type(e), str(e)


Well, actually the second statement doesn't even compile... any ideas
why I shouldn't be able to catch "anonymous" exceptions like this, or
whether and how I can (and only overlooked it)?


TIA!


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


Re: How to find Python path in Visual C++ install wizard

2005-08-13 Thread Philippe C. Martin
Thanks you all.


As my software has python "executables" and libraries + c++ libs, the
HKEY_LOCAL should be myt way out.

Best regards,

Philippe



Philippe C. Martin wrote:

> Hi,
> 
> I realize this is not really a Python question but ...
> 
> I am trying to setup an .msi for my software (Python code (.pyc) +
> drivers) to make installation easier for Windows users.
> 
> I am using the installer that comes with V. C++ 7.1.
> 
> I would like to find the way to make sure Python is installed and then
> copy automatically my files into its hierarchy.
> 
> 
> PS: for many reasons, I do not wish to use setup.py.
> 
> Best regards,
> 
> Philippe

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


Re: need help with my append syntax

2005-08-13 Thread bruno modulix
yaffa wrote:
> dear folks,

Dear Yaffa,

> i'm trying to append a semicolon to my addr string

Python strings don't have a 'append' method.

>  and am using the
> syntax below.  for some reason the added on of the ; doesn't work.

"doesn't work" is the worst possible description of a problem.
Please read
http://www.catb.org/~esr/faqs/smart-questions.html



> when i print it out later on it only shows the original value of addr.
> 
> addr = incident.findNextSibling('td')
> addr.append('%s;')

If you don't have an AttributeError here then addr is not bound to a string.

> thanks
> 
> yaffa
> 


-- 
bruno desthuilliers
ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p|
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')"
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary inheritance

2005-08-13 Thread bruno modulix
Talin wrote:
> I want to make a dictionary that acts like a class, in other words,
> supports inheritance: 

I must be missing your point here, since dict is a class and as such
support inheritence:

>>> class MyDict(dict):pass
...
>>> d = MyDict()
>>> d.items()
[]
>>>


> If you attempt to find a key that isn't present,
> it searches a "base" dictionary, which in turn searches its base, and so
> on.

That's not inheritence, that's contextual acquisition (Zope relies
heavily on this concept).

> Now, I realize its fairly trivial to code something like this using
> UserDict, 

If you want to specialize dict, why use UserDict ?

> but given that classes and modules already have this behavior,

Nope. Inheritence is not the solution - unless of course you want to
create a derived class for each and any of your 'nested dict' instances,
which would be a rather strange design...


Here you need composition/delegation:

class HierDict(dict):
def __init__(self, parent=None):
self._parent = parent

def __getitem__(self, name):
try:
return super(HierDict,self).__getitem__(name)
except KeyError, e:
if self._parent is None:
raise
return self._parent[name]

# to be continued according to your needs


if __name__ == "__main__":
d = HierDict(None)
d['test'] = 42
print d['test']

d2 = HierDict(d)
d2['dead'] = "parrot"

print d2['dead'] # found in d2
print d2['test'] # found in d


> 
> Also, on a completely different subject: Has there been much discussion
> about extending the use of the 'is' keyword to do type comparisons a la
> C# (e.g. "if x is list:") ?

I don't think there is much to discuss:

x = list
if x is list:
  print "x is list"

Remember that in Python,
1/ type information pertains to objects, not to identifiers
2/ types are objects too

So, the 'is' operator being the identity operator, there is no need to
'extend' it to do type comparisons:

x = []
if type(x) is type([]):
  print "x is a list"

But - even if useful in some special cases -, type comparisons  in
Python are rarely necessary and in most case worst than useless:

def get_foo(a_dict):
  if type(a_dict) is type({}):
foo = a_dict['foo']
  else:
raise TypeError, "expected a dict, got something else"

h = HierDict()
h['foo'] = 'bar'

get_foo(h)


...definitively worst than useless...

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


Re: Spaces and tabs again

2005-08-13 Thread Jeff Schwab
[EMAIL PROTECTED] wrote:
> Hello, I know this topic was discussed a *lot* in the past, sorry if it
> bores you...
> 
>>From the Daily Python-URL I've seen this interesting Floating Point
> Benchmark:
> http://www.fourmilab.ch/fourmilog/archives/2005-08/000567.html
> 
> This is the source pack:
> http://www.fourmilab.ch/fbench/fbench.zip
> 
> I've read its Python sourcecode, probably there few things that can be
> changed to speed it up some (like moving the main code in a function,
> using Psyco, or even vectorizing it with numarray), but I've had
> problems in changing the code because it mixes tabs and spaces for the
> indentations.
> I like a lot how Python uses indentations, I've never had problems with
> them in my programs, but I have big problems when I find a source that
> mixes them (I often need time to find how much spaces a tab is, to try
> to convert them all in spaces).
> I know that some people likes tabs, and other people likes spaces, so
> probably a single standard cannot be enforced, but I think the python
> compiler must generate an error (and stop compiling) when the
> sourcecode of a module contains both spaces and tabs to indent the
> lines of code (and comments lines too?).


What's wrong with mixing spaces and tabs?  Either way, it's pretty easy 
to convert back & forth.  In Vim:

:set expandtab
:%retab
-- 
http://mail.python.org/mailman/listinfo/python-list


how to append semicolon to a variable

2005-08-13 Thread yaffa
dear folks,

i have the following lines of python code:

couch = incident.findNextSibling('td')
price = couch.findNextSibling('td')
sdate = price.findNextSibling('td')
city = sdate.findNextSibling('td')
strUrl = addr.b.string
currently what this ends up doing is creating something like this

couch3201/01/2004newyork

now what i want to do is add a semicolon after the couch, price, sdate,
city so that i get something like this

couch;32;01/01/2004;new york

does anyone know how to do this?

thanks

yaffa

p.s. i tried couch = couch + ';' and then i tried couch = couch + ";"
and then i tried couch = couch.append ';'

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


Re: Archetype Permission Errors with CMFBoard 2.2

2005-08-13 Thread Yuan HOng
Ops. Sorry for posting the wrong list.

On 8/13/05, Yuan HOng <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I am trying to integrate the latest CMFBoard 2.2 with my Plone site
> (2.0.5 with Archetypes 1.3.3-final). I'd like to have my users to post
> anonymously with CMFBoard, so I added a forumNB of type 'open'.
> 
> However, when an anonymous user tries to added a new Topic to the
> board, a bunch of error messages were seen in the event.log as shown
> below.
> 
> As a result, I find the topic of a new forum topic can not be
> displayed in several locations.
> 
> Can someone explain what the various errors mean and how shall I set
> up my permission so CMFBoard will work correctly for anonymous users?
> 
> By the way, is CMFBoard 2.2 known to work stably with Archetype 1.3.3?
> So many warning/errors for just adding a simple topic make me really
> worry.
> 
> Below is the event.log transcript:
> 

-- 
Hong Yuan

大管家网上建材超市
装修装潢建材一站式购物
http://www.homemaster.cn
-- 
http://mail.python.org/mailman/listinfo/python-list

Archetype Permission Errors with CMFBoard 2.2

2005-08-13 Thread Yuan HOng
Hi,

I am trying to integrate the latest CMFBoard 2.2 with my Plone site
(2.0.5 with Archetypes 1.3.3-final). I'd like to have my users to post
anonymously with CMFBoard, so I added a forumNB of type 'open'.

However, when an anonymous user tries to added a new Topic to the
board, a bunch of error messages were seen in the event.log as shown
below.

As a result, I find the topic of a new forum topic can not be
displayed in several locations.

Can someone explain what the various errors mean and how shall I set
up my permission so CMFBoard will work correctly for anonymous users?

By the way, is CMFBoard 2.2 known to work stably with Archetype 1.3.3?
So many warning/errors for just adding a simple topic make me really
worry.

Below is the event.log transcript:

--
2005-08-08T03:53:07 INFO(0) Plone Debug
/opt/zope/client0/Products/CMFBoard/skins/cmfboard/forum_add_topic_form.cpt:
No default action specified for status success, content type ANY. 
Users of IE can submit pages using the return key, resulting in no
button in the REQUEST.  Please specify a default action for this case.
--
2005-08-08T03:53:36 ERROR(200) Archetypes caught Unauthorized on
discussiontool.overrideDiscussionFor(forum/forum/public/0001)
Traceback (most recent call last):
  File "/opt/zope/client0/Products/Archetypes/ExtensibleMetadata.py",
line 250, in allowDiscussion
dtool.overrideDiscussionFor(self, allowDiscussion)
  File "/opt/zope/client0/Products/CMFDefault/DiscussionTool.py", line
84, in overrideDiscussionFor
raise "Unauthorized"
Unauthorized
--
2005-08-08T03:53:36 ERROR(200) CMFBoard None
Traceback (most recent call last):
  File "/opt/zope/client0/Products/CMFBoard/utils.py", line 149, in
forum_stateChanged
sci.object.notifyStateChanged(sci)
TypeError: notifyStateChanged() takes exactly 1 argument (2 given)
--
2005-08-08T03:53:36 INFO(0) Archetypes
Products/Archetypes/Field.py[492]:writeable
User None tried to update ForumMessage:title but doesn't have enough
permissions.

--
2005-08-08T03:53:36 INFO(0) Archetypes User None tried to update
ForumMessage:authorname but doesn't have enough permissions.

--
2005-08-08T03:53:36 INFO(0) Archetypes User None tried to update
ForumMessage:message_icon but doesn't have enough permissions.

--
2005-08-08T03:53:36 INFO(0) Archetypes User None tried to update
ForumMessage:parsing_flag but doesn't have enough permissions.

--
2005-08-08T03:53:36 INFO(0) Archetypes User None tried to update
ForumMessage:text but doesn't have enough permissions.

--
2005-08-08T03:53:36 INFO(0) Archetypes User None tried to update
ForumMessage:signature but doesn't have enough permissions.

--
2005-08-08T03:53:36 INFO(0) Plone Debug
/opt/zope/client0/Products/CMFBoard/skins/cmfboard/forum_topic.cpt: No
default action specified for status success, content type ANY.  Users
of IE can submit pages using the return key, resulting in no button in
the REQUEST.  Please specify a default action for this case.
--
2005-08-08T03:53:36 INFO(0) Plone Debug
/opt/zope/client0/Products/CMFBoard/skins/cmfboard/forum_topic.cpt: No
default validators specified for content type ANY.  Users of IE can
submit pages using the return key, resulting in no button in the
REQUEST.  Please specify default validators for this case.
--
2005-08-08T03:53:36 INFO(0) Plone Debug
/opt/zope/client0/Products/CMFBoard/skins/cmfboard/forum_quickreply_widget.cpt:
No default action specified for status success, content type ANY. 
Users of IE can submit pages using the return key, resulting in no
button in the REQUEST.  Please specify a default action for this case.



-- 
Hong Yuan

大管家网上建材超市
装修装潢建材一站式购物
http://www.homemaster.cn
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: UCALC equivalent

2005-08-13 Thread Scott David Daniels
John Machin wrote:
> Scott David Daniels wrote:
>> max wrote:
>>> Larry Bates <[EMAIL PROTECTED]> wrote in
>> The python equivalent:
 >> ...
>> exec "def shl(x, y): return x * 2^y"
> 
> Perhaps this should be:
> exec "def shl(x, y): return x * 2 ** y"
> or
> exec "def shl(x, y): return x << y"
Exactly.
Demonstrating the problems of not actually running a test case
with known results.

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


Re: Dictionary inheritance

2005-08-13 Thread bruno modulix
Devan L wrote:
> Talin wrote:
> 
>>I want to make a dictionary that acts like a class, in other words,
>>supports inheritance: 
(snip)
> 
> Dictionaries aren't classes? 

They are.

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


Re: What are modules really for?

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

Oops ! Sorry, my misreading :(


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


Re: How to find Python path in Visual C++ install wizard

2005-08-13 Thread laurent
Hello,
there's a pretty solution. if the user  hasn't got python or don't want
to install python. You can  make your application executable without a
complete installation of python.

for this, look at project like py2exe or freeze. These tools make an
executable of your pyc files and produce some files : python.zip (for
python higher 2.3) and python.dll and other dll for application that
needs some dynamic python's extension.

regards,
Laurent

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


Re: What are modules really for?

2005-08-13 Thread Terry Reedy

"Mike Meyer" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Magnus Lycka <[EMAIL PROTECTED]> writes:

>> Terry Reedy wrote:
>>> However, everything is an instance of a class or type.

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

> [snip] Maybe the properly
> refined version of Terry's statement should be:
>
>Everything you can manipulate is an instance of a class or a
>type.

Yes and no.

First, the context of the statement was a previous claim that some things 
are class instances and some not.   So my point in that context was a) that 
adding 'or type' changes 'some' to 'every' and that new classes mostly 
eliminate the difference between class and type, making the addition 
eminently sensible.  So while I thought of a qualifier like that, I left it 
out as irrelevant and a distractions.

Second, any qualifier I can think of seems to have the danger of confusing 
as well as enlightening.  One might not realize, for instance, that 
functions are something you can manipulate and might therefore mistakenly 
think that the qualifier excludes functions.  I also thought of putting it 
as 'everything in Python's dataspace ...', but that has the same problem.

Perhaps 'every runtime entity...'. would work. That seems to excludes 
source code (and things within source code like comments and whitespace and 
operator symbols), unless the code or pieces thereof *are* turned into (or 
wrapped as) string instances.  Names might seem like an exception, but 
again, they are only accessible at runtime as string instances.  Or maybe a 
more direct statement 'except for source code, everything...' would be 
better.

So I have so far not settled on a 'best' context-free statement of the 
design principle.

Terry J. Reedy



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


Re: Printing literal text of an argument

2005-08-13 Thread Paul McGuire
Rex -

If what you are looking for is a monitor of calls to a certain
function, check out this decorator example from the Python Wiki:

http://wiki.python.org/moin/PythonDecoratorLibrary?highlight=%28Decorator%29#head-d4ce77c6d6e75aad25baf982f6fec0ff4b3653f4

This will allow you to very quickly turn on/off debugging for a given
routine, with no changes required in the calling code.

-- Paul

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


Re: Parallel port programming on windows XP / 2000

2005-08-13 Thread pdalet
I have written a python script with pyparallel pyDS1267 (W2K,
pyparallel 0.1, giveio_setup.exe, pythoncard), with no problems on this
OS.

I have not tested with pyparallel 0.2
pyDS1267, pyUltraISR

http://sourceforge.net/projects/gpib82357a/



[EMAIL PROTECTED]
lyp champollion
av pezet
46100 FIGEAC
FRANCE




Novice Experl a écrit :

> I'm still stuck... my script is finished and works just fine on win98 using 
> pyparallel, but I still haven't seen any sample code to do access the port in 
> XP / 2000.
>
> If I don't make progress soon, I'll need to find a solution in another 
> language, which I don't really want to do.
>
>
> --=  Posted using GrabIt  =
> --=  Binary Usenet downloading made easy =-
> -=  Get GrabIt for free from http://www.shemes.com/  =-

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


Re: Running one Python program from another as a different user

2005-08-13 Thread Alessandro Bottoni
Jeff Schwab wrote:

> [EMAIL PROTECTED] wrote:
>> Thanks, that looks very promising...
>> Is there a solution for pre-Python v2.4? I have to have code that works
>> on 2.x, 0<=x<=4. Do I just use the os.popen instead?
> 
> import os
> 
> def run_as(username):
>  pipe = os.popen("su %s" % username, 'w')
>  pipe.write("whoami")
> 
> 
> if __name__ == "__main__":
>  import sys
>  for user in sys.argv[1:]:
>  run_as(user)

Jeff, may I suggest you to write down a new recipe for the ASPN Python
Cookbook based on these code snippets? This is exactly the kind of thing
the people is happy to find at ASPN.

CU  
---
Alessandro Bottoni
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug on Python2.3.4 [FreeBSD]?

2005-08-13 Thread Terry Reedy

"Donn Cave" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Quoth "Terry Reedy" <[EMAIL PROTECTED]>:
> | Standard C, by Plauger & Brodie says that 'a' plus whatever else means 
> all
> | writes start at the current end-of-file.
>
> Of course, but the question was, where do reads start?

For 'a+', that book, and perhaps the standard, does not specify where an 
*initial* read starts.  It only says file position is set to end-of-file 
'before each write' and that reads after a write (and vice versa) 'must' 
follow an intervening file-positioning call (fflush, fseek, fsetpos, 
rewind).

> guess the GNU C library "innovated" on this point.

If there is a hole in the standard, 'innovation' is required.

Terry J. Reedy



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


Re: simpli int/str problem

2005-08-13 Thread sinan .
i thank you all, first of al ill change my dictinary variable name :)
then ill use %s and %d . and thanks for other examples,these examples
enchance my python-way thinking. :)

On 8/12/05, Scott David Daniels <[EMAIL PROTECTED]> wrote:
> Paolino wrote:
> > sinan . wrote:
> >
> >> hi all,
> >> i have a string and int values in same dictionary like this
> >> dict = {'str_name': 'etc' , 'int_name' : 112 }
> Bad idea to call this "dict" -- that is a system-defined name
> for the dictionary type. I'll use "holder" below.
> 
> >> the error occures when do this
> >> SQL = "INSERT INTO (`AH`, `BH` ) VALUES ('" + dict['str_name'] + "',
> >> '" + dict['int_name'] + "')"
> ^^ I suspect this should be:
> SQL = "INSERT INTO TABLENAME(AH, BH) VALUES (...
> >> cursor.execute(SQL)
> >> python does not accep dict['int_name'] in SQL variable but when i
> >> convert this variable to the str , python accepts but i cannot insert
> >> that into database because database only accept int in `BH `
> >> thanks.
> 
> > Try use:
> > SQL = "INSERT INTO (`AH`, `BH` ) VALUES
> > ('%s,%d)"%(dict['str_name'],dict['int_name'])
> This will work, but the DB interface allows you to leave the
> variable formatting to it.  Depending on the parameter style
> your DB interface supports, you may use at least one of:
> 
> cursor.execute("INSERT INTO TABLENAME(AH, BH) VALUES(?, ?)",
>[(holder['str_name'], holder['int_name'])])
> or
> cursor.execute("INSERT INTO TABLENAME(AH, BH) VALUES(:1, :2)",
>[(holder['str_name'], holder['int_name'])])
> ### I think, it _might_ be ...(0, :1)",
> or
> cursor.execute("INSERT INTO TABLENAME(AH, BH) "
>"VALUES(:str_name, :int_name)",
>holder)
> 
> --Scott David Daniels
> [EMAIL PROTECTED]
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find Python path in Visual C++ install wizard

2005-08-13 Thread Martin v. Löwis
Philippe C. Martin wrote:
> I am trying to setup an .msi for my software (Python code (.pyc) + drivers)
> to make installation easier for Windows users.
> 
> I am using the installer that comes with V. C++ 7.1.
> 
> I would like to find the way to make sure Python is installed and then copy
> automatically my files into its hierarchy.

You should look at (HKEY_LOCAL_MACHINE,HKEY_CURRENT_USER)/Software/Python.


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


Re: Parallel port programming on windows XP / 2000

2005-08-13 Thread Novice Experl
I'm still stuck... my script is finished and works just fine on win98 using 
pyparallel, but I still haven't seen any sample code to do access the port in 
XP / 2000.

If I don't make progress soon, I'll need to find a solution in another 
language, which I don't really want to do.


--=  Posted using GrabIt  =
--=  Binary Usenet downloading made easy =-
-=  Get GrabIt for free from http://www.shemes.com/  =-

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


Re: Spaces and tabs again

2005-08-13 Thread Torsten Bronger
Hallöchen!

[EMAIL PROTECTED] writes:

> [...]  I know that some people likes tabs, and other people likes
> spaces, so probably a single standard cannot be enforced, but I
> think the python compiler must generate an error (and stop
> compiling) when the sourcecode of a module contains both spaces
> and tabs to indent the lines of code (and comments lines too?).

I think the interpreter option -tt does this but I've never used it.

I agree that mixing spaces and tabs is a bad thing.  Unfortunately,
my default Emacs configuration did so, whyever.  I changed it a
couple of days ago.  However, the PEP 8 strongly dicourages it
anyway.

Tschö,
Torsten

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list

Spaces and tabs again

2005-08-13 Thread bearophileHUGS
Hello, I know this topic was discussed a *lot* in the past, sorry if it
bores you...

>From the Daily Python-URL I've seen this interesting Floating Point
Benchmark:
http://www.fourmilab.ch/fourmilog/archives/2005-08/000567.html

This is the source pack:
http://www.fourmilab.ch/fbench/fbench.zip

I've read its Python sourcecode, probably there few things that can be
changed to speed it up some (like moving the main code in a function,
using Psyco, or even vectorizing it with numarray), but I've had
problems in changing the code because it mixes tabs and spaces for the
indentations.
I like a lot how Python uses indentations, I've never had problems with
them in my programs, but I have big problems when I find a source that
mixes them (I often need time to find how much spaces a tab is, to try
to convert them all in spaces).
I know that some people likes tabs, and other people likes spaces, so
probably a single standard cannot be enforced, but I think the python
compiler must generate an error (and stop compiling) when the
sourcecode of a module contains both spaces and tabs to indent the
lines of code (and comments lines too?).

Bye,
bearophile

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


Re: Printing literal text of an argument

2005-08-13 Thread Reinhold Birkenfeld
Rex Eastbourne wrote:
> Thanks. I adapted it a bit:
> 
> def debug(foo):
> print foo, 'is:'
> exec('pprint.pprint(' + foo + ')')
> 
> But I'm getting "NameError: name 'foo' is not defined," since foo is
> not defined in this scope. (The function works beautifully when I'm
> dealing with global variables, which is very rarely).
> 
> Any way around this?

Eh, yes, but it's getting uglier...

def debug(foo):
print foo, 'is:'
frame = sys._getframe(-1)
exec 'pprint.pprint(%s)' % foo, frame.f_globals, frame.f_locals

Untested.

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


Re: breaking a loop

2005-08-13 Thread Mosti El
I think u need break before exit()
so if u want break from any loop just  add break

"el chupacabra" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi, I'm just learning Pythonthanks in advance...
>
> Do you get out of this loop?
>
> Problem: When I type 'exit' (no quotes) the program doesn't quit the
loop...it actually attemps to find entries that containt the 'exit' string.
>
> Desired behavior: when I type 'exit' the program should quit.
>
> def search():
> searchWhat = ""
> while searchWhat != 'exit':
> searchWhat = "%%%s%%" % raw_input ('Search for : ')
> cursor.execute("select * from TABLE where FIELD like %s",
(searchWhat))
> result = cursor.fetchall()
> print
'+--+'
> print '|  #   |Name   |
LastName  |'
> print
'+--+'
> for record in result:
> print  '  ', record[0], ' :  ', record[1], ' ==>  ',
record[2]
> print
'+--+'
> #end for statement, end of search
>
>
> --=  Posted using GrabIt  =
> --=  Binary Usenet downloading made easy =-
> -=  Get GrabIt for free from http://www.shemes.com/  =-
>


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


Re: Bug on Python2.3.4 [FreeBSD]?

2005-08-13 Thread Uwe Mayer
Saturday 13 August 2005 06:18 am Donn Cave wrote:

> Of course, but the question was, where do reads start?  I would
> guess the GNU C library "innovated" on this point.  But in the
> end it doesn't really matter unless Python is going to try to
> square that all up and make open() consistent across platforms.

Personally, I think Python should unify this difference across plattforms
and explicitly document the behaviour in the library reference.
But I don't know how a decision on that is going to be formed.

I will forward a request for taking this point up into the library
reference's file() function, perhaps a footnote pointing out the
end-of-file position on BSD and start-of-file on Linux.

Uwe

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


How to find Python path in Visual C++ install wizard

2005-08-13 Thread Philippe C. Martin
Hi,

I realize this is not really a Python question but ...

I am trying to setup an .msi for my software (Python code (.pyc) + drivers)
to make installation easier for Windows users.

I am using the installer that comes with V. C++ 7.1.

I would like to find the way to make sure Python is installed and then copy
automatically my files into its hierarchy.


PS: for many reasons, I do not wish to use setup.py.

Best regards,

Philippe




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


Re: Python Wireless Extension Module (pyiw)

2005-08-13 Thread Eric Nieuwland
Jeremy Moles wrote:

> I am mostly done with writing an extension module in C that wraps (and
> makes easier) interfacing with libiw (the library that powers iwconfig,
> iwlist, and friends on Linux). We're using this internally for a tool 
> to
> manage wireless connectivity. This is a million times better than
> hundreds of invocations of the iw* suite of tools. :)
>
> Would anyone else find something like this useful? I know a few distros
> maintain their own suite of config tools, but I don't think there is 
> yet
> an actual binding for python.
>
> Anyway, I am just curious... we plan on using it, at any rate. It's
> already made the code easier to read, faster, and more reliable.
>
> # example usage -
>
> wlan = pyiw.WirelessInfo("wlan0")
>
> nets = wlan.Scan()
>
> for net in nets:
>   print net.signal_quality
>
> wlan.essid
> wlan.key
> wlan.protocol
>
> wlan.essid = "LV-426"
>
> wlan.Reconfigure()

So cool! YES, I'd like to have that. Preferably as source code since I 
have quite a number of different Un*xes.

--eric

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


Re: socket setdefaulttimeout

2005-08-13 Thread Sheila King
Bryan: Thanks for the tips/suggestion.

I will definitely look into that. (It will be my first foray into
coding with threads...I do appreciate that you've laid a great deal of
it out. I will certainly refer to my references and do substantial
testing on this...)

Thanks!

-- 
Sheila King
http://www.thinkspot.net/sheila/

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