Re: Python Threads and C Semaphores

2007-01-16 Thread Dejan Rodiger
Jeremy said the following on 16.1.2007 8:27:
> Hello,
> 
> I have a fat C++ extension to a Python 2.3.4 program. In all, I count
> five threads. Of these, two are started in Python using
> thread.start_new_thread(), and both of these wait on semaphores in the C++
> extension using sem_wait(). There also are two other Python threads and one 
> thread running wholly in
> the extension.
> 
> I notice that when one of the Python threads calls the extension and waits
> on a semaphore, all but the C++ thread halt even when not waiting on any
> semaphore. How do we get this working right?

Check the Global Interpreter Lock

-- 
Dejan Rodiger - PGP ID 0xAC8722DC
Delete wirus from e-mail address
-- 
http://mail.python.org/mailman/listinfo/python-list


why scipy cause my program slow?

2007-01-16 Thread HYRY
Why the exec time of test(readdata()) and test(randomdata()) of
following program is different?
my test file 150Hz10dB.wav has 2586024 samples, so I set randomdata
function
to return a list with 2586024 samples.
the exec result is:
2586024

10.8603842736
2586024

2.16525233979
test(randomdata()) is 5x faster than test(readdata())
if I remove "from scipy import *" then I get the following result:
2586024

2.21851601473
2586024

2.13885042216

So, what the problem with scipy?
Python 2.4.2, scipy ver. 0.5.1


import wave
from scipy import *
from time import *
import random
from array import array

def readdata():
f = wave.open("150Hz10dB.wav", "rb")
t = f.getparams()
SampleRate = t[2]
data = array("h", f.readframes(t[3]))
f.close()
left = data[0::2]
mean = sum(left)/float(len(left))
left = [abs(x-mean) for x in left]
return left

def randomdata():
return  [random.random()*32768.0 for i in xrange(2586024)]

def test(data):
print len(data)
print type(data)
envelop = []
e = 0.0
ga, gr = 0.977579425259, 0.999773268338
ga1, gr1 = 1.0 - ga, 1.0 - gr
start = clock()
for x in data:
if e < x:
e *= ga
e += ga1*x
else:
e *= gr
e += gr1*x
envelop.append(e)
print clock() - start
return envelop

test(readdata())
test(randomdata())

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


Re: why scipy cause my program slow?

2007-01-16 Thread Robert Kern
HYRY wrote:
> Why the exec time of test(readdata()) and test(randomdata()) of
> following program is different?
> my test file 150Hz10dB.wav has 2586024 samples, so I set randomdata
> function
> to return a list with 2586024 samples.
> the exec result is:
> 2586024
> 
> 10.8603842736
> 2586024
> 
> 2.16525233979
> test(randomdata()) is 5x faster than test(readdata())
> if I remove "from scipy import *" then I get the following result:
> 2586024
> 
> 2.21851601473
> 2586024
> 
> 2.13885042216
> 
> So, what the problem with scipy?

You're importing (through scipy) numpy's sum() function. The result type of that
function is a numpy scalar type. The set of scalar types was introduced for a
number of reasons, mostly having to do with being able to represent the full
range of numerical datatypes that Python does not have builtin types for.
Unfortunately, the code paths that get executed when arithmetic is performed
sith such scalars are still suboptimal; I believe they are still going through
the full ufunc machinery.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: installing/maintaining modules for multiple versions of python

2007-01-16 Thread Daniel Nogradi
> I have a suse box that has by default python 2.4 running and I have a
> 2.5 version installed
> in /reg/python2.5. How do I install new modules for only 2.5 without
> disturbing the 2.4 default
> installation.

If you do 'python2.5 setup.py install' on a new module supporting
distutils it will only effect the 2.5 installation. If the new module
has no setup.py you can just copy it to /reg/python2.5/site-packages
and it will also only effect the 2.5 installation.

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


Re: for v in l:

2007-01-16 Thread Peter Otten
Gert Cuykens wrote:

> is there a other way then this to loop trough a list and change the values
> 
> i=-1
> for v in l:
> i=i+1
> l[i]=v+x
> 
> something like
> 
> for v in l:
> l[v]=l[v]+x

Be generous, create a new list:

items = [value + delta for value in items]

That will require some extra peak memory, but is faster.
Also, code relying on lists not being changed in place tends to be more
robust (and better looking) than code relying on lists being changed in
place :-)

If you cannot rebind the list variable, use slices:

items[:] = [value + delta for value in items]

If the list is huge and you have to economize memory, use enumerate():

for index, value in enumerate(items):
   items[index] = value + delta

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


Re: why scipy cause my program slow?

2007-01-16 Thread HYRY
Thanks, by your hint, I change type(data) to type(data[0]), and I get


So, calculate with float is about 5x faster numpy.float64.

Robert Kern wrote:
> HYRY wrote:
> > Why the exec time of test(readdata()) and test(randomdata()) of
> > following program is different?
> > my test file 150Hz10dB.wav has 2586024 samples, so I set randomdata
> > function
> > to return a list with 2586024 samples.
> > the exec result is:
> > 2586024
> > 
> > 10.8603842736
> > 2586024
> > 
> > 2.16525233979
> > test(randomdata()) is 5x faster than test(readdata())
> > if I remove "from scipy import *" then I get the following result:
> > 2586024
> > 
> > 2.21851601473
> > 2586024
> > 
> > 2.13885042216
> >
> > So, what the problem with scipy?
>
> You're importing (through scipy) numpy's sum() function. The result type of 
> that
> function is a numpy scalar type. The set of scalar types was introduced for a
> number of reasons, mostly having to do with being able to represent the full
> range of numerical datatypes that Python does not have builtin types for.
> Unfortunately, the code paths that get executed when arithmetic is performed
> sith such scalars are still suboptimal; I believe they are still going through
> the full ufunc machinery.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>  that is made terrible by our own mad attempt to interpret it as though it had
>  an underlying truth."
>   -- Umberto Eco

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


Re: html + javascript automations = [mechanize + ?? ] or something else?

2007-01-16 Thread Benjamin Niemann
Hello,

John wrote:

> John wrote:
>> I have to write a spyder for a webpage that uses html + javascript. I
>> had it written using mechanize
>> but the authors of the webpage now use a lot of javascript. Mechanize
>> can no longer do the job.
>> Does anyone know how I could automate my spyder to understand
>> javascript? Is there a way
>> to control a browser like firefox from python itself? How about IE?
>> That way, we do not have
>> to go thru something like mechanize?
> 
> I am curious about the webbrowser module. I can open up firefox
> using webbrowser.open(), but can one control it? Say enter a
> login / passwd on a webpage? Send keystrokes to firefox?
> mouse clicks?

Not with the webbrowser module - it can only launch a browser.

On the website of mechanize you will also find DOMForm
, which is a webscraper with
basic JS support (using the SpiderMonkey engine from the Mozilla project).
But note that DOMForm is in a early state and not developed anymore
(according to the site, never used it myself).

You could try to script IE (perhaps also FF, dunno..) using COM. This can be
done using the pywin32 module .
How this is done in detail is a windows issue. You may find help and
documentation in win specific group/mailing list, msdn, ... You can usually
translate the COM calls from VB, C#, ... quite directly to Python.


HTH

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


How to convert float to sortable integer in Python

2007-01-16 Thread shellon
Hi all:
I want to convert the float number to sortable integer, like the
function float2rawInt() in java, but I don't know the internal
expression of float, appreciate your help!

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


Re: How naive is Python?

2007-01-16 Thread skip
> "John" == John Machin <[EMAIL PROTECTED]> writes:

John> [EMAIL PROTECTED] wrote:
John> Sorry, Skip, but I find that very hard to believe. The foo()
John> function would take quadratic time if it were merely adding on
John> pieces of constant size -- however len(str(i)) is not a constant,
John> it is O(log10(i)), so the time should be super-quadratic.
>> 
me> Sorry, I should have pointed out that I'm using the latest version
me> of Python.  I believe += for strings has been optimized to simply
me> extend s when there is only a single reference to it.

John> Sorry, I should have pointed out that you need to read up about
John> time.time() -- what is its resolution on your box? -- and
John> time.clock() and the timeit module.

time.time() should be plenty good enough for this particular task on my
machine (Mac OSX).  time.time() has plenty of resolution:

>>> import time
>>> t = time.time() ; print time.time()-t
3.79085540771e-05
>>> t = time.time() ; print time.time()-t
5.00679016113e-06
>>> t = time.time() ; print time.time()-t
5.96046447754e-06
>>> t = time.time() ; print time.time()-t
5.00679016113e-06

It's time.clock() on Unix-y systems that is too coarse:

>>> t = time.clock() ; print time.clock()-t
0.0
>>> t = time.clock() ; print time.clock()-t
0.0
>>> t = time.clock() ; print time.clock()-t
0.0
>>> t = time.clock() ; print time.clock()-t
0.0
>>> t = time.clock() ; print time.clock()-t
0.0

I ran the size of the loop to 2**24 and still only saw linear growth in the
later versions of Python.  The machine (my Mac laptop) was otherwise idle.
I only reduced the loop length in what I posted before because of the
quadratic growth in Python 2.2 and 2.3.  It took so long to run my script
using 2.2 and 2.3 I made a slight change so that it bailed out of the larger
loops:

#!/usr/bin/env python

from __future__ import division

def foo(kcount):
s = ''
for i in xrange(kcount) :
s += str(i) + ' '

import time

for i in xrange(5,25):
t = time.time()
foo(2**i)
t = time.time() - t
print "2**%d"%i, 2**i, t, t/2**i
if t > 200:
break

I then ran it using this shell command:

for v in 2.6 2.5 2.4 2.3 2.2 ; do
echo $v
time python$v strcopy.py
done 2>&1 \
| tee strcopy.out

The output is:

2.6
2**5 32 0.000240802764893 7.52508640289e-06
2**6 64 0.000278949737549 4.3585896492e-06
2**7 128 0.000599145889282 4.68082726002e-06
2**8 256 0.0087895574 3.43350693583e-05
2**9 512 0.00221586227417 4.32785600424e-06
2**10 1024 0.00433588027954 4.23425808549e-06
2**11 2048 0.00897288322449 4.38129063696e-06
2**12 4096 0.0197570323944 4.82349423692e-06
2**13 8192 0.0359501838684 4.38845017925e-06
2**14 16384 0.0721030235291 4.40081930719e-06
2**15 32768 0.146120071411 4.45923069492e-06
2**16 65536 0.292731046677 4.46672129328e-06
2**17 131072 0.692205905914 5.2895308e-06
2**18 262144 1.20644402504 4.60221872345e-06
2**19 524288 3.34210991859 6.37456878394e-06
2**20 1048576 6.86596488953 6.54789437249e-06
2**21 2097152 10.0534589291 4.79386278585e-06
2**22 4194304 21.4015710354 5.1025321568e-06
2**23 8388608 40.8173680305 4.86580944425e-06
2**24 16777216 84.5512800217 5.039649011e-06

real2m50.195s
user2m26.258s
sys 0m2.998s
2.5
2**5 32 0.000205039978027 6.40749931335e-06
2**6 64 0.000274896621704 4.29525971413e-06
2**7 128 0.000594139099121 4.64171171188e-06
2**8 256 0.00110697746277 4.32413071394e-06
2**9 512 0.00236988067627 4.62867319584e-06
2**10 1024 0.0045051574707 4.39956784248e-06
2**11 2048 0.00938105583191 4.58059366792e-06
2**12 4096 0.0197520256042 4.82227187604e-06
2**13 8192 0.0375790596008 4.58728754893e-06
2**14 16384 0.0780160427094 4.76172135677e-06
2**15 32768 0.148911952972 4.54443215858e-06
2**16 65536 0.307368040085 4.69006408821e-06
2**17 131072 0.703125953674 5.36442530574e-06
2**18 262144 1.22114300728 4.6582908908e-06
2**19 524288 2.62232589722 5.00168971485e-06
2**20 1048576 5.06462287903 4.8376201e-06
2**21 2097152 10.3055510521 4.9140696774e-06
2**22 4194304 24.6841719151 5.88516519429e-06
2**23 8388608 42.5984380245 5.07812953288e-06
2**24 16777216 89.6156759262 5.34151052989e-06

real2m58.236s
user2m29.354s
sys 0m2.978s
2.4
2**5 32 0.000231981277466 7.24941492081e-06
2**6 64 0.000316858291626 4.95091080666e-06
2**7 128 0.000571966171265 4.46848571301e-06
2**8 256 0.00112700462341 4.40236181021e-06
2**9 512 0.00228881835938 4.47034835815e-06
2**10 1024 0.00619387626648 6.04870729148e-06
2**11 2048 0.00927710533142 4.52983658761e-06
2**12 4096 0.0188140869141 4.593282938e-06
2**13

Re: How to convert float to sortable integer in Python

2007-01-16 Thread Steven D'Aprano
On Tue, 16 Jan 2007 01:21:52 -0800, shellon wrote:

> Hi all:
> I want to convert the float number to sortable integer, like the
> function float2rawInt() in java, but I don't know the internal
> expression of float, appreciate your help!

Google says:

Your search - float2rawInt - did not match any documents. 

Are you sure about that function? What's a sortable integer?


-- 
Steven.

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


Re: Maths error

2007-01-16 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
|>
|> [ Interval arithmetic ]
|>
|> > |> For people just getting into it, it can be shocking to realize just how
|> > |> wide the interval can become after some computations.
|> >
|> > Yes.  Even when you can prove (mathematically) that the bounds are
|> > actually quite tight :-)
|> 
|> This sounds like one of those pesky:
|> "but you should be able to do better" - kinds of things...

It's worse :-(

It is rather like global optimisation (including linear programming
etc.)  The algorithms that are guaranteed to work are so catastrophically
slow that they are of theoretical interest only, but almost every
practical problem can be solved "well enough" with a hack, IF it is
coded by someone who understands both the problem and global
optimisation.

This is why the "statistical" methods (so disliked by Kahan) are used.
In a fair number of cases, they give reasonable estimates of the error.
In others, they give a false sense of security :-(


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


Re: Segfault with tktreectrl on python-2.5 on linux

2007-01-16 Thread klappnase
Anton Hartl schrieb:


>
> Solutions:
>
> a) convince Python developers to prefix ALL new (wrt. 2.5)
>global symbols with a prefix like "_PyAST_" or equivalent;
>this would be consistent with how it is done anyway,
>unfortunately the new AST symbols deviate from this practise
>(there are symbols like "Assert", "If", "Then", ...)
>
>  or b) apply an equivalent rule to the global symbols in
>tktreectrl that are global by accident, i.e. because
>of the way the library is structured and built
>

Anton, you're cool,

actually renaming Ellipsis to Py_Ast_Ellipsis in ast.c and Python-ast.c
seems to fix this.
What I don't understand, isn't it very likely that such things will
happen when names like "Ellipsis" or "Slice" and "Index" (which I also
found in Python-ast.c) are being used, or are the treectrl people doing
something they should avoid?
I think the answer to this might be important when deciding to whom I
should send a bug report :)

Thanks and best regards

Michael

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


Re: I wrote a C++ code generator in Python, would anyone please help me to review the code? :)

2007-01-16 Thread Vineeth Kashyap
Hi,
I am interested in your proposal. I am basically a C/C++ programmer,
but recently fell in love with python. Please send more details on
fgen. We could probably start working. :)
Kevin Wan wrote:
> fgen is a free command line tool that facilitates cross platform c++
> development, including header generation, cpp file generation, makefile
> generation, unit test framework generation, etc.
>
> http://sf.net/projects/fgen
>
> I'm not very familiar with Python. Any feedback are appreciated! Or
> anyone like to develop it with me?
> 
> Thanks.

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


Re: html + javascript automations = [mechanize + ?? ] or something else?

2007-01-16 Thread Andrey Khavryuchenko
John,

"J" == John  wrote:

 J> I have to write a spyder for a webpage that uses html + javascript. I
 J> had it written using mechanize but the authors of the webpage now use a
 J> lot of javascript. Mechanize can no longer do the job.  Does anyone
 J> know how I could automate my spyder to understand javascript? Is there
 J> a way to control a browser like firefox from python itself? How about
 J> IE?  That way, we do not have to go thru something like mechanize?

Up to my knowledge, there no way to test javascript but to fire up a
browser.

So, you might check Selenium (http://www.openqa.org/selenium/) and its
python module.

-- 
Andrey V Khavryuchenko
Software Development Company http://www.kds.com.ua/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html + javascript automations = [mechanize + ?? ] or something else?

2007-01-16 Thread Diez B. Roggisch
> Up to my knowledge, there no way to test javascript but to fire up a
> browser.
> 
> So, you might check Selenium (http://www.openqa.org/selenium/) and its
> python module.

No use in that, as to be remote-controlled by python, selenium must be run
on the server-site itself, due to JS security model restrictions.

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


Re: How to convert float to sortable integer in Python

2007-01-16 Thread robert
shellon wrote:
> Hi all:
> I want to convert the float number to sortable integer, like the
> function float2rawInt() in java, but I don't know the internal
> expression of float, appreciate your help!
> 

float comparision works well enough for sorting in Python. What is 
the actual requirement?

see also hash() and id() for keying.

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


Regular expressions question

2007-01-16 Thread Victor Polukcht
I have 2 strings:

"Global   etsi3   *200 ok30   100% 100%
Outgoing"
and
"Global   etsi3   *   4 ok 30   100% 100%
Outgoing"

The difference is "*200" instead of "*  4". Is there ability to write a
regular expression that will match both of that strings?

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


Re: html + javascript automations = [mechanize + ?? ] or something else?

2007-01-16 Thread Duncan Booth
"John" <[EMAIL PROTECTED]> wrote:

> Is there a way
> to control a browser like firefox from python itself? How about IE?

IE is easy enough to control and you have full access to the DOM:

>>> import win32com
>>> win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-
C05BAE0B}', 0, 1, 1)

>>> IE = win32com.client.DispatchEx('InternetExplorer.Application.1')
>>> dir(IE)
['CLSID', 'ClientToWindow', 'ExecWB', 'GetProperty', 'GoBack', 'GoForward', 
'GoHome', 'GoSearch', 'Navigate', 'Navigate2', 'PutProperty', 
'QueryStatusWB', 'Quit', 'Refresh', 'Refresh2', 'ShowBrowserBar', 'Stop', 
'_ApplyTypes_', '__call__', '__cmp__', '__doc__', '__getattr__', 
'__init__', '__int__', '__module__', '__repr__', '__setattr__', '__str__', 
'__unicode__', '_get_good_object_', '_get_good_single_object_', '_oleobj_', 
'_prop_map_get_', '_prop_map_put_', 'coclass_clsid']
>>> IE.Visible=True
>>> IE.Navigate("http://plone.org";)
>>> while IE.Busy: pass

>>> print IE.Document.getElementById("portlet-news").innerHTML
http://plone.org/rss.gif";> http://plone.org/news";>News 

... and so on ...


See 
http://msdn.microsoft.com/workshop/browser/webbrowser/reference/objects/int
ernetexplorer.asp
for the documentation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyExcelerator big integer values

2007-01-16 Thread Gacha
John Machin wrote:
> Here's a possible replacement -- I say possible because you have been
> rather coy about what you are actually trying to do.
>
> value = values[(row_idx, col_idx)])
> if isinstance(value, float):
> v = repr(value)
> else:
> v = unicode(value)
>
> HTH
> John

My final result:

value = values[(row_idx, col_idx)]
if isinstance(value, float) and
re.match('^\d+\.\d+e\+\d+$',unicode(value)):
v = repr(value)
else:
v = unicode(value)

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


Re: Regular expressions question

2007-01-16 Thread Duncan Booth
"Victor Polukcht" <[EMAIL PROTECTED]> wrote:

> I have 2 strings:
> 
> "Global   etsi3   *200 ok30   100% 100%
> Outgoing"
> and
> "Global   etsi3   *   4 ok 30   100% 100%
> Outgoing"
> 
> The difference is "*200" instead of "*  4". Is there ability to write a
> regular expression that will match both of that strings?
> 
Yes, ".*" would match both of the strings, but not in a useful way. You'll 
have to consider which strings you *don't* want to match as well as which 
ones you do and whether you want to extract any information from the 
strings or find the ones which match.

But first take a step back and look at the problem as a whole. You didn't 
say what you are trying to do, and often people will jump at regular 
expressions as the solution when there may be better ways of doing what 
they want without writing a regular expression.

What do you really want to do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert float to sortable integer in Python

2007-01-16 Thread Duncan Booth
robert <[EMAIL PROTECTED]> wrote:

> shellon wrote:
>> Hi all:
>> I want to convert the float number to sortable integer, like the
>> function float2rawInt() in java, but I don't know the internal
>> expression of float, appreciate your help!
>> 
> 
> float comparision works well enough for sorting in Python. What is 
> the actual requirement?
> 

Maybe this is the problem?

>>> sorted([-0.0, 0.0, -0.0, 0.0, -0.0])
[-0.0, 0.0, -0.0, 0.0, -0.0]

Java sorting imposes an artificial total ordering on float or double 
values:

> The < relation does not provide a total order on all floating-point
> values; although they are distinct numbers -0.0 == 0.0 is true and a
> NaN value compares neither less than, greater than, nor equal to any
> floating-point value, even itself. To allow the sort to proceed,
> instead of using the < relation to determine ascending numerical
> order, this method uses the total order imposed by
> Double.compareTo(java.lang.Double). This ordering differs from the <
> relation in that -0.0 is treated as less than 0.0 and NaN is
> considered greater than any other floating-point value. For the
> purposes of sorting, all NaN values are considered equivalent and
> equal. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why scipy cause my program slow?

2007-01-16 Thread robert
HYRY wrote:
> Thanks, by your hint, I change type(data) to type(data[0]), and I get
> 
> 
> So, calculate with float is about 5x faster numpy.float64.
> 

approx..
numpy funcs all upcast int to int32 and float to float32 and 
int32/float to float32 etc. This is probably ill behavior.
float32 arrays should only arise if numpy.array(l,dtype=numpy.float32)

In your example you'll best go to numpy/scipy types very early 
(not mixing with the python array type in addition) and do the 
array computations with scipy

left = [abs(x-mean) for x in left]

->

data = scipy.array(f.readframes(t[3]),"h")
..
left = abs(left-mean)

code the test(data) similar - see also scipy.signal.lfilter etc.

and cast types down to Python types late like float(mynumfloat) ...


The type magic and speed loss will and pickle problems will 
probably only disapear, when float & int are handled as extra 
(more conservative) types in numpy - with numpy scalar types only 
on request. Currently numpy uses Python.


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


Projects anyone?

2007-01-16 Thread placid
Hi all,

I'm looking for anyone who is working on a project at the moment that
needs help (volunteer). The last project i worked on personally was
screen-scraping MySpace profiles (read more at the following link)

http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles


but that didn't go all to well, so im kinda bored and need something to
do, with Python. So any suggestions anyone? 

Cheers

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


Re: How to convert float to sortable integer in Python

2007-01-16 Thread Wolfgang Grafen
shellon wrote:
> Hi all:
> I want to convert the float number to sortable integer, like the
> function float2rawInt() in java, but I don't know the internal
> expression of float, appreciate your help!
> 
You should know you can sort mixed float/integer values in Python
 >>> l=[3,2.3,1.45,2,5]
 >>> l.sort()
 >>> l
[1.45, 2, 2.2998, 3, 5]

to convert a float to int use the built-in int function:

 >>> int(2.34)
2

Hope this helps

regards

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


wxPython, having images in a textCtrl

2007-01-16 Thread Erik
Is it possible with wxPython to place images in a textctrl (or a
styledtextctrl)?
If you don't get what I mean, just think about emoticons in the MSN
messenger
chat window. So is it possible to use images in a textCtrl?

Thanks

Erik

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


Re: Anyone has a nice "view_var" procedure ?

2007-01-16 Thread Neil Cerutti
On 2007-01-15, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> At Monday 15/1/2007 17:45, Stef Mientki wrote:
>
>>Is there some handy/ nice manner to view the properties of some variable ?
>>As a newbie, I often want to see want all the properties of a var,
>>and also some corner values (large arrays) etc.
>
> You can try dir(x), vars(x). If you want a "nice print", see
> the pprint module.
>
> py> import csv
> py> x = csv.DictReader('') # a bogus object
> py> x
>
> py> dir(x)
> ['__doc__', '__init__', '__iter__', '__module__', 'fieldnames', 
> 'next', 'reader'
> , 'restkey', 'restval']
> py> vars(x)
> {'restkey': None, 'restval': None, 'fieldnames': None, 'reader': 
><_csv.reader ob
> ject at 0x00BC98B8>}
> py> from pprint import pprint
> py> pprint(vars(x))
> {'fieldnames': None,
>   'reader': <_csv.reader object at 0x00BC98B8>,
>   'restkey': None,
>   'restval': None}
> py>

It's an unfortunately limited sort of introspection. To rehash a
recent experience:

>>> import re
>>> import pprint
>>> r = re.match("(x+)|(y+)", "xxx")
>>> pprint.pprint(dir(r))
['__copy__',
 '__deepcopy__',
 'end',
 'expand',
 'group',
 'groupdict',
 'groups',
 'span',
 'start']
>>> r.lastindex
1

The documentation is deliberately vague:

dir( [object]) 
  
  [...] The list is not necessarily
  complete. If the object is a module object, the list contains
  the names of the module's attributes. If the object is a type
  or class object, the list contains the names of its attributes,
  and recursively of the attributes of its bases. Otherwise, the
  list contains the object's attributes' names, the names of its
  class's attributes, and recursively of the attributes of its
  class's base classes. The resulting list is sorted
  alphabetically. [...]

It's unclear to me what attributes an object could have that
aren't included in the above list.

  Note: Because dir() is supplied primarily as a convenience for
  use at an interactive prompt, it tries to supply an interesting
  set of names more than it tries to supply a rigorously or
  consistently defined set of names, and its detailed behavior
  may change across releases. 

In other words, dir is just for fun, like monkey bars. ;)

-- 
Neil Cerutti
The eighth-graders will be presenting Shakespeare's Hamlet in the church
basement on Friday at 7 p.m. The congregation is invited to attend this
tragedy. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assert versus print [was Re: The curious behavior of integer objects]

2007-01-16 Thread Ron Adam
Carl Banks wrote:
> Ron Adam wrote:
>> There have been times where I would like assert to be a little more assertive
>> than it is.  :-)
>>
>> ie.. not being able to turn them off with the -0/-00 switches, and having 
>> them
>> generate a more verbose traceback.
> 
> Personally, I'd rather see it get less assertive, i.e., having it only
> work in a special debugging mode.  That way people who haven't RTFM
> don't use it to make sure their input is correct.
> 
> 
> Carl Banks

Well, the manual could be improved in this area quite a bit.  There also really 
need to be easier to find examples for both assert and warnings use.


But it does only work in a special debugging mode.  Didn't you RTFM?  ;-)

http://docs.python.org/ref/assert.html

It just happens this mode is turned on by default.  So you would like this to 
be 
turned off by default.  I agree.  I think there may be a way to change pythons 
default startup behavior for this.


Warnings generated by warn() on the other hand can be silenced, but not 
completely ignored.  But I also think they could be a more useful and flexible 
tool for debugging purposes.

http://docs.python.org/lib/warning-functions.html

I have to admit that part of why assert seems wrong to me is the meaning of the 
word implies something you shouldn't be able to ignore.  While warnings seem 
like something that can be disregarded.

I think maybe the best way to use both may be to combine them...

assert  warn(...)

But I'm not sure that doesn't have problems of it's own. 

Cheers,
Ron










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


Re: Anyone has a nice "view_var" procedure ?

2007-01-16 Thread Duncan Booth
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> dir( [object]) 
>   
>   [...] The list is not necessarily
>   complete. If the object is a module object, the list contains
>   the names of the module's attributes. If the object is a type
>   or class object, the list contains the names of its attributes,
>   and recursively of the attributes of its bases. Otherwise, the
>   list contains the object's attributes' names, the names of its
>   class's attributes, and recursively of the attributes of its
>   class's base classes. The resulting list is sorted
>   alphabetically. [...]
> 
> It's unclear to me what attributes an object could have that
> aren't included in the above list.

For a start the potentially infinite list of attributes handled by 
__getattr__ or __getattribute__:

>>> class C(object):
def __getattribute__(self, name):
if name.startswith('weird'):
return 42


>>> c = C()
>>> c.weirdattribute
42
>>> dir(c)
[]

Any objects which are actually implemented as C extensions are quite likely 
to have attributes that dir() cannot see.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: whats wrong with my reg expression ?

2007-01-16 Thread Neil Cerutti
On 2007-01-15, Gert Cuykens <[EMAIL PROTECTED]> wrote:
> thx
>
> PS i also cant figure out what is wrong here ?
>
> rex=re.compile('^"(?P[^"]*)"$',re.M)
> for v in l:
> v=rex.match(v).group('value')
> v=v.replace('""','"')
> return(l)
>
> v=rex.match(v).group('value')
> AttributeError: 'NoneType' object has no attribute 'group'

When the regex doesn't match, match returns None.

-- 
Neil Cerutti
Strangely, in slow motion replay, the ball seemed to hang in the air for even
longer. --David Acfield
-- 
http://mail.python.org/mailman/listinfo/python-list


re.sub and empty groups

2007-01-16 Thread Hugo Ferreira
Hi!

I'm trying to do a search-replace in places where some groups are
optional... Here's an example:

>> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola").groups()
('ola', None)

>> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|").groups()
('ola', '')

>> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|ole").groups()
('ola', 'ole')

The second and third results are right, but not the first one, where
it should be equal to the second (i.e., it should be an empty string
instead of None). This is because I want to use re.sub() and when the
group is None, it blows up with a stack trace...

Maybe I'm not getting the essence of groups and non-grouping groups.
Someone care to explain (and, give the correct solution :)) ?

Thanks in advance,

Hugo Ferreira

-- 
GPG Fingerprint: B0D7 1249 447D F5BB 22C5  5B9B 078C 2615 504B 7B85
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html + javascript automations = [mechanize + ?? ] or something else?

2007-01-16 Thread Andrey Khavryuchenko
Diez,

"DBR" == Diez B Roggisch wrote:

 >> Up to my knowledge, there no way to test javascript but to fire up a
 >> browser.
 >> 
 >> So, you might check Selenium (http://www.openqa.org/selenium/) and its
 >> python module.

 DBR> No use in that, as to be remote-controlled by python, selenium must be run
 DBR> on the server-site itself, due to JS security model restrictions.

Sorry, missed 'spider' word in the original post.

-- 
Andrey V Khavryuchenko
Software Development Company http://www.kds.com.ua/
-- 
http://mail.python.org/mailman/listinfo/python-list


Globbing files by their creation date

2007-01-16 Thread tkpmep
I'd like to create a list of all files in a directory that were created
after a certain date. How does one do this? I've used glob.glob to
create a list of all files whose name matches a substring, but I don't
see how I can use it to identify files by their creation date.

Thanks in advance for the assistance.

Thomas Philips

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


Re: assert versus print [was Re: The curious behavior of integer objects]

2007-01-16 Thread Neil Cerutti
On 2007-01-16, Ron Adam <[EMAIL PROTECTED]> wrote:
> I have to admit that part of why assert seems wrong to me is
> the meaning of the word implies something you shouldn't be able
> to ignore.  While warnings seem like something that can be
> disregarded.

Experienced C coders expect assert to behave like that.

The only reason (I know of) to turn off error checking is to
optimize. However, removing tests won't usually make a big enough
speed difference to be worth the burthen of testing two different
versions of the same source code.

So to me the assert statement is either dubious syntax-sugar or
dangerous, depending on Python's command line arguments.

The warning module would seem to have limited applications.
Searching my Python distribution shows that it's used for
deprecation alerts, and elsewhere for turning those selfsame
alerts off. How copacetic! It is the null module. ;-)

-- 
Neil Cerutti
Facts are stupid things. --Ronald Reagan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Globbing files by their creation date

2007-01-16 Thread skip

Thomas> I've used glob.glob to create a list of all files whose name
Thomas> matches a substring, but I don't see how I can use it to
Thomas> identify files by their creation date.

Sumthin' like:

files = [f for f in glob.glob(globpat)
   if os.path.getctime(f) > timethreshold]

Define globpat and timethreshold accordingly.  You sure you don't mean
modification time?  If so, change getctime to getmtime.

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


Re: re.sub and empty groups

2007-01-16 Thread harvey . thomas

Hugo Ferreira wrote:

> Hi!
>
> I'm trying to do a search-replace in places where some groups are
> optional... Here's an example:
>
> >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola").groups()
> ('ola', None)
>
> >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|").groups()
> ('ola', '')
>
> >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|ole").groups()
> ('ola', 'ole')
>
> The second and third results are right, but not the first one, where
> it should be equal to the second (i.e., it should be an empty string
> instead of None). This is because I want to use re.sub() and when the
> group is None, it blows up with a stack trace...
>
> Maybe I'm not getting the essence of groups and non-grouping groups.
> Someone care to explain (and, give the correct solution :)) ?
>
> Thanks in advance,
>
> Hugo Ferreira
>
> --
> GPG Fingerprint: B0D7 1249 447D F5BB 22C5  5B9B 078C 2615 504B 7B85

>From the documentation:
groups( [default])
Return a tuple containing all the subgroups of the match, from 1 up to
however many groups are in the pattern. The default argument is used
for groups that did not participate in the match; it defaults to None.

Your second group is optional and does not take part in the match in
your first example. You can, however, still use this regular expression
if you use groups('') rather than groups().

A better way probably is to use a simplified regular expression

re.match(r"Image:([^\|]+)\|?(.*)", "Image:ola").groups()

i.e. match the text "Image:" followed by at least one character not
matching "|" followed by an optional "|" followed by any remaining
characters.

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


Re: re.sub and empty groups

2007-01-16 Thread harvey . thomas

Hugo Ferreira wrote:

> Hi!
>
> I'm trying to do a search-replace in places where some groups are
> optional... Here's an example:
>
> >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola").groups()
> ('ola', None)
>
> >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|").groups()
> ('ola', '')
>
> >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|ole").groups()
> ('ola', 'ole')
>
> The second and third results are right, but not the first one, where
> it should be equal to the second (i.e., it should be an empty string
> instead of None). This is because I want to use re.sub() and when the
> group is None, it blows up with a stack trace...
>
> Maybe I'm not getting the essence of groups and non-grouping groups.
> Someone care to explain (and, give the correct solution :)) ?
>
> Thanks in advance,
>
> Hugo Ferreira
>
> --
> GPG Fingerprint: B0D7 1249 447D F5BB 22C5  5B9B 078C 2615 504B 7B85

>From the documentation:
groups( [default])
Return a tuple containing all the subgroups of the match, from 1 up to
however many groups are in the pattern. The default argument is used
for groups that did not participate in the match; it defaults to None.

Your second group is optional and does not take part in the match in
your first example. You can, however, still use this regular expression
if you use groups('') rather than groups().

A better way probably is to use a simplified regular expression

re.match(r"Image:([^\|]+)\|?(.*)", "Image:ola").groups()

i.e. match the text "Image:" followed by at least one character not
matching "|" followed by an optional "|" followed by any remaining
characters.

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


Re: Watch log

2007-01-16 Thread Salvatore Di Fazio
Thinker ha scritto:

> What you want is something like 'tail -f' in linux.
> If you look into it's source code, you will find it check file periodically.
> When a read() reach the end of the file, read() will return a empty string.
> You can try to read data from the file periodically after a EOF.
> I think it is what you want.

So every 2 sec:
- open the file
- read the file from the oldPosition to the EOF
- save the last position in file
- first point

mmm ok

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


Re: Watch log

2007-01-16 Thread Salvatore Di Fazio
Michele Simionato ha scritto:

> You may begin from this:

Tnx Michele

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


Re: Debugging SocketServer.ThreadingTCPServer

2007-01-16 Thread Jean-Paul Calderone
On Tue, 16 Jan 2007 00:23:35 -0500, "Stuart D. Gathman" <[EMAIL PROTECTED]> 
wrote:
>I have a ThreadingTCPServer application (pygossip, part of
>http://sourceforge.net/projects/pymilter).  It mostly runs well, but
>occasionally goes into a loop.  How can I get a stack trace of running
>threads to figure out where the loop is?  Is there some equivalent of
>sending SIGQUIT to Java to get a thread dump?  If needed, I can import pdb
>and set options at startup, but there needs to be some external way of
>triggering the dump since I can't reproduce it at will.

Grab the gdbinit out of Python SVN Misc/ directory.  Apply this patch:

  http://jcalderone.livejournal.com/28224.html

Attach to the process using gdb.  Make sure you have debugging symbols
in your build of Python.  Run 'thread apply all pystack'.

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


Re: Command line arguments on Vista

2007-01-16 Thread jmike
Thanks for the answers; that was the problem exactly.
  --JMike

Duncan Booth wrote:

> It sounds like the registry entry for running Python files is messed up.
> Can you go to a command line and see what the command 'ftype Python.File'
> displays? (Assuming that command lines and ftype still work on Vista)
>
> The output should be:
> Python.File="C:\Python25\python.exe" "%1" %*
>
> but if it only says:
> Python.File="C:\Python25\python.exe" "%1"
>
> then you would get the behaviour you observed (on any version of Windows,
> not just Vista).

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


Re: Regular expressions question

2007-01-16 Thread Victor Polukcht
Actually, i'm trying to get the values of first field (Global) , fourth
(200, 4), and fifth (100%) and sixth (100%).

Everything except fourth is simple.

On Jan 16, 2:59 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> "Victor Polukcht" <[EMAIL PROTECTED]> wrote:
> > I have 2 strings:
>
> > "Global   etsi3   *200 ok30   100% 100%
> > Outgoing"
> > and
> > "Global   etsi3   *   4 ok 30   100% 100%
> > Outgoing"
>
> > The difference is "*200" instead of "*  4". Is there ability to write a
> > regular expression that will match both of that strings?Yes, ".*" would 
> > match both of the strings, but not in a useful way. You'll
> have to consider which strings you *don't* want to match as well as which
> ones you do and whether you want to extract any information from the
> strings or find the ones which match.
>
> But first take a step back and look at the problem as a whole. You didn't
> say what you are trying to do, and often people will jump at regular
> expressions as the solution when there may be better ways of doing what
> they want without writing a regular expression.
> 
> What do you really want to do?

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


Re: Regular expressions question

2007-01-16 Thread Neil Cerutti
On 2007-01-16, Victor Polukcht <[EMAIL PROTECTED]> wrote:
> Actually, i'm trying to get the values of first field (Global) , fourth
> (200, 4), and fifth (100%) and sixth (100%).
>
> Everything except fourth is simple.

>>> g = "Global etsi3  *   4 ok 30 100% 100% Outgoing"
>>> import re
>>> r = re.search('\*\s+(\d+)', g)
>>> r.group()
'*   4'
>>> r.group(1)
'4'

-- 
Neil Cerutti
We're not afraid of challenges. It's like we always say: If you want to go out
in the rain, be prepared to get burned. --Brazillian soccer player
-- 
http://mail.python.org/mailman/listinfo/python-list


urrlib2 multithreading error

2007-01-16 Thread viscanti
Hi,

I'm using urllib2 to retrieve some data usign http in a multithreaded
application.
Here's a piece of code:
req = urllib2.Request(url, txdata, txheaders)
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', user_agent)]
request = opener.open(req)
data = request.read(1024)

I'm trying to read only the first 1024 bytes to retrieve http headers
(if is html then I will retrieve the entire page).
When I use it on a single thread everything goes ok, when I create
multiple threads the execution halts and the program terminates, just
before the last line (when I execute the request.read(.) ). Obviously I
tried to catch the exception but it doesn't work, the interpreter exits
without any exception or message.
How can I solve this?

lv

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


Re: Regular expressions question

2007-01-16 Thread Victor Polukcht
The same regular expression should work for another string (with *200).

On Jan 16, 5:40 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-01-16, Victor Polukcht <[EMAIL PROTECTED]> wrote:
>
> > Actually, i'm trying to get the values of first field (Global) , fourth
> > (200, 4), and fifth (100%) and sixth (100%).
>
> > Everything except fourth is simple.
> >>> g = "Global etsi3  *   4 ok 30 100% 100% Outgoing"
> >>> import re
> >>> r = re.search('\*\s+(\d+)', g)
> >>> r.group()
> '*   4'
> >>> r.group(1)'4'
>
> --
> Neil Cerutti
> We're not afraid of challenges. It's like we always say: If you want to go out
> in the rain, be prepared to get burned. --Brazillian soccer player

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


Re: Regular expressions question

2007-01-16 Thread Neil Cerutti
On 2007-01-16, Victor Polukcht <[EMAIL PROTECTED]> wrote:
> On Jan 16, 5:40 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> On 2007-01-16, Victor Polukcht <[EMAIL PROTECTED]> wrote:
>>
>> > Actually, i'm trying to get the values of first field (Global) , fourth
>> > (200, 4), and fifth (100%) and sixth (100%).
>>
>> > Everything except fourth is simple.
>> >>> g = "Global etsi3  *   4 ok 30 100% 100% Outgoing"
>> >>> import re
>> >>> r = re.search('\*\s+(\d+)', g)
>> >>> r.group()
>> '*   4'
>> >>> r.group(1)'4'
>
> The same regular expression should work for another string (with *200).

Sorry about that. It should have been:

r = re.search('\*\s*(\d+)', g)

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


Re: Regular expressions question

2007-01-16 Thread Wolfgang Grafen
Victor Polukcht wrote:
> I have 2 strings:
> 
> "Global   etsi3   *200 ok30   100% 100%
> Outgoing"
> and
> "Global   etsi3   *   4 ok 30   100% 100%
> Outgoing"
> 
> The difference is "*200" instead of "*  4". Is there ability to write a
> regular expression that will match both of that strings?
> 
 x.py begin 
import re

s1 = "Global   etsi3   *200 ok30   100% 100% Outgoing"
s2 = "Global   etsi3   *   4 ok 30   100% 100% Outgoing"

re_m = re.compile( "^"
"(\S+)" # Global
"\s+"
"(\S+)" # etsi3
"\s+"
"((\*)\s*(\d+))"# *200 *  4
"\s+"
"(\S+)" # ok
"\s+"
"(\S+)" # 30
"\s+"
"(\S+)" # 100%
"\s+"
"(\S+)" # 100%
"\s+"
"(\S+)" # Outgoing
"$"
  ).match

print "match s1:", re_m(s1).groups()
print "match s2:", re_m(s2).groups()
- x.py file end -

% python x.py
match s1: ('Global', 'etsi3', '*200', '*', '200', 'ok', '30', '100%', '100%', 
'Outgoing')
match s2: ('Global', 'etsi3', '*   4', '*', '4', 'ok', '30', '100%', '100%', 
'Outgoing')
-- 
http://mail.python.org/mailman/listinfo/python-list


arguments of a function/metaclass

2007-01-16 Thread rubbishemail
Hello,


I have a member function with many (20) named arguments

def __init__(self,a=1,b=2):
self.a=a
self.b=b

I would like to get rid of the many redundant lines like self.a=a and
set the members automatically.
The list of default arguments could be given like

def __init__(**kwargs):
arglist={"a":1,"b":2]

if this makes things easier

Of course there has to be a check that raises an error in case of an
unknown argument not mentioned in this list.


I am sure there is an elegant way how to do this, could you give me any
hints???


Many thanks



Daniel

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


Search Queue

2007-01-16 Thread abcd
I have a class such as...

id = 0
class Foo:
def __init__(self, data):
self.id = id
id += 1
self.data = data

And I am storing them in a Queue.Queue...

import Queue
q = Queue.Queue()
q.put(Foo('blah'))
q.put(Foo('hello world'))
q.put(Foo('test'))

how can I search "q" for an instance of Foo which has 'id' equal to say
2?  Typically a queue only lets you put and get, not really search.

Thanks.

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


Re: Projects anyone?

2007-01-16 Thread stef
placid wrote:
> Hi all,
>
> I'm looking for anyone who is working on a project at the moment that
> needs help (volunteer). The last project i worked on personally was
> screen-scraping MySpace profiles (read more at the following link)
>
> http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles
>
>
> but that didn't go all to well, so im kinda bored and need something to
> do, with Python. So any suggestions anyone? 
>
> Cheers
>
>   
hello Chad,

I would have expected lots of reactions on your message,
buts as there's still none, I'll kick of.

I don't know what your knowledge and interests and

I'm just a completely newbie in Python (3..4 weeks),
so I might not have a good overview,
but coming from MatLab (and I'm not the only one who is thinking of 
switching to Python ;-)
there are a couple of fairly general modules that I'm missing in Python:
- SimuLink
- (PowerSim)

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conflicting needs for __init__ method

2007-01-16 Thread Mark Dickinson
On Jan 15, 4:54 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> [EMAIL PROTECTED] writes:
> > Suppose you're writing a class "Rational" for rational numbers.  The
> > __init__ function of such a class has two quite different roles to
> > play.
> That should be your first clue to question whether you're actually
> needing separate functions, rather than trying to force one function
> to do many different things.

Agreed.  It was clear that I wanted two separate functions, but it
seemed that the system was effectively forcing me to use just one;
that is, I was working from the following two assumptions:

(1) *Every* time a Rational is created, __init__ must eventually be
called, and
(2) The user of the class expects to call Rational() to create
rationals.

(1) argues for __init__ being small, simple and efficient, while (2)
wants it to be large and user friendly (possibly dispatching to other
methods to do most of the real work).  But as has been pointed out,
thanks to the existence of __new__,  (1) is simply false.  Time to be
thankful for new-style classes.

> > But __init__ also plays another role: it's going to be used by the
> > other Rational arithmetic methods, like __add__ and __mul__, to
> > return new Rational instances.
> No, it won't; those methods won't "use" the __init__ method. They will
> use a constructor, and __init__ is not a constructor (though it does
> get *called by* the construction process).

Sorry---I'm well aware that __init__ isn't a constructor; I wasn't
being precise enough in my use of `used'.

Mark

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


Re: Regular expressions question

2007-01-16 Thread Jussi Salmela
Victor Polukcht kirjoitti:
> I have 2 strings:
> 
> "Global   etsi3   *200 ok30   100% 100%
> Outgoing"
> and
> "Global   etsi3   *   4 ok 30   100% 100%
> Outgoing"
> 
> The difference is "*200" instead of "*  4". Is there ability to write a
> regular expression that will match both of that strings?
> 

If the goal is not to study regular expressions, here's a solution 
without them. Not so short, but working.

lst = [
 "Global   etsi3   *200 ok30   100% 100% 
Outgoing",
 "Global   etsi3   *   4 ok 30   100% 100% 
Outgoing"]

for e in lst:
 es = e.split()
 if len(es) == 9:
 num_val = es[3]
 else:
 num_val = es[2][1:]
 print es[0], num_val, es[-3], es[-2]


Cheers,
Jussi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Projects anyone?

2007-01-16 Thread Peter Decker
On 16 Jan 2007 04:07:50 -0800, placid <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I'm looking for anyone who is working on a project at the moment that
> needs help (volunteer). The last project i worked on personally was
> screen-scraping MySpace profiles (read more at the following link)
>
> http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles
>
>
> but that didn't go all to well, so im kinda bored and need something to
> do, with Python. So any suggestions anyone?

I know the Dabo folks (http://dabodev.com) are always looking for
help, although that is not a simple one-trick project, so it might not
be what you're looking for.

-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assert versus print [was Re: The curious behavior of integer objects]

2007-01-16 Thread Ron Adam
Neil Cerutti wrote:
 > On 2007-01-16, Ron Adam <[EMAIL PROTECTED]> wrote:
 >> I have to admit that part of why assert seems wrong to me is
 >> the meaning of the word implies something you shouldn't be able
 >> to ignore.  While warnings seem like something that can be
 >> disregarded.
 >
 > Experienced C coders expect assert to behave like that.
 >
 > The only reason (I know of) to turn off error checking is to
 > optimize. However, removing tests won't usually make a big enough
 > speed difference to be worth the burthen of testing two different
 > versions of the same source code.

Ah... but that's the irony.  The whole purpose of the existence of the second
version you refer to, is to better check the first version.  These checks should
not change the flow of code that is executed!

The problem with assert as a debugging tool, is it *can* change the execution
flow by raising a catchable exception.  So you do have *two* versions that may
not behave the same.

Like I suggested earlier, assert should not be turned off *ever*, but should be
considered a nicer way to generate exceptions to do value checks.

And warnings should never change code execution order, but we should be able to
completely turn them off on the byte code level like asserts are when the -O
command line option is given.

I believe both of these features would be used a lot more if they where like 
this.


 > So to me the assert statement is either dubious syntax-sugar or
 > dangerous, depending on Python's command line arguments.

Yep.. unless you use them in a very limited way.


 > The warning module would seem to have limited applications.
 > Searching my Python distribution shows that it's used for
 > deprecation alerts, and elsewhere for turning those selfsame
 > alerts off. How copacetic! It is the null module. ;-)

I think you understand the point I'm trying to make.  :-)

Ron

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


connection to server not accepted (but no error) only after several hours

2007-01-16 Thread seb
Hi, this simple server (time protocol) does not respond after a few
hours, even when it is restarted. The behaviour looks to me like a
firewall blocking but I have desabled the firewall.
Using Netstat - a I find the server listed when it is running and not
listed when I stop it.
The server starts whith no error. But after about 6-8 hours there is no
way to make it respond again (even when it is restarted).

Once it is blocked, I killes it, wait for about 15 minutes without
running the server and then started again but this gives me the same
behaviour (no response).

The solution at this time is to reboot windows !!!

I have also tried to run it twice in order to get the exception that
the port is already used and an exeption is raised.
I have tried from another computer to connect to mine but it does not
manage.
  When I change the port in the server it responds immediatly.

I am running winXP SP2, python 2.4.

Do you have any clues ?
Thanks in advance.
Seb.

PS : I am calling this server from another program and make it run in a
thread.
Below is the standalone version (wich is adpated from effbot site).

import socket
import struct, time
import threading
import os
import appel_log2 as appel_log
import sys


class TimeServer(threading.Thread) :
def __init__(self):
nom_function_actuelle= str(sys._getframe().f_code.co_filename)
+"___"+str(sys._getframe().f_code.co_name)
try :
threading.Thread.__init__(self)
self.log_file="timeserverlog.txt"
self.PORT=37
self.TIME1970=2208988800L
self._continue=1
self.time_shift=0
message=nom_function_actuelle+"\t "+"STARTED OK "
appel_log.write_log("info",message)
except Exception, e :
message=nom_function_actuelle+"\t "+"PB:::"+str(e)
print message
appel_log.write_log("warning",message)

def set_log_file(self, file):
nom_function_actuelle= str(sys._getframe().f_code.co_filename)
+"___"+str(sys._getframe().f_code.co_name)
if os.path.exists(file):
pass
else :
f=open(file,"w")
f.close()
self.log_file=file
print "log file ",self.log_file
self.log_file=file

def reset_log_file(self):
nom_function_actuelle= str(sys._getframe().f_code.co_filename)
+"___"+str(sys._getframe().f_code.co_name)
print "resetting log file "
if os.path.exists(self.log_file):
f=open(self.log_file,"w")
f.close()

def set_time_shift(self,time_shift):
self.time_shift=time_shift

def run(self):
nom_function_actuelle= str(sys._getframe().f_code.co_filename)
+"___"+str(sys._getframe().f_code.co_name)
socket.timeout(1)
service=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
service.bind(("", self.PORT))
service.listen(1)
print "listening on port", self.PORT
while self._continue==1 :
channel, info = service.accept()
print "connection from", info

message=str(time.time())+"\t"+str(time.asctime())+"\t"+str(info)+"\n"
g=open(self.log_file,"a")
g.write(message)
g.close()
t = int(time.time()) + self.TIME1970 + self.time_shift
t = struct.pack("!I", t)
channel.send(t) # send timestamp
channel.close() # disco
m=nom_function_actuelle+" response OK "+str(info)
appel_log.write_log("info",m)
#print "apres m "
print "time server self_continue=0"
appel_log.write_log("warning",nom_function_actuelle+"\t
self._continue ="+str(self._continue))
print "sortie du thread"

def main() :
a=TimeServer()
a.start()
a.set_log_file("log_nw.txt")
a.reset_log_file()
while 1==1 :
time.sleep(10)
#a._continue=0
pass
time.sleep(2)

main()

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


Re: Search Queue

2007-01-16 Thread Bill Scherer
abcd wrote:

>I have a class such as...
>
>id = 0
>class Foo:
>def __init__(self, data):
>self.id = id
>id += 1
>self.data = data
>
>And I am storing them in a Queue.Queue...
>
>import Queue
>q = Queue.Queue()
>q.put(Foo('blah'))
>q.put(Foo('hello world'))
>q.put(Foo('test'))
>
>how can I search "q" for an instance of Foo which has 'id' equal to say
>2?  Typically a queue only lets you put and get, not really search.
>
>Thanks.
>
>  
>
You could iterate through q.queue. Something like:

for instance in q.queue:
if instance.id == 2:
print 'found it!"


But, you mess around with the internals of a Queue instance at your own 
peril!


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


Re: Search Queue

2007-01-16 Thread Tim Golden
abcd wrote:
> I have a class such as...

[... ]

> And I am storing them in a Queue.Queue...
>
> import Queue
> q = Queue.Queue()
> q.put(Foo('blah'))
> q.put(Foo('hello world'))
> q.put(Foo('test'))
>
> how can I search "q" for an instance of Foo which has 'id' equal to say
> 2?  Typically a queue only lets you put and get, not really search.

It's possible you're seeing the Queue structure as
some sort of list / array, rather than its intended purpose
as a thread-safe channel. If I'm wrong, ignore the rest of
this post. If, however, you're just after a container for
various instances of Foo then use a list or a dict,
depending on what you're after.

eg,


class Foo:
  def __init__ (self, id):
self.id = id

list_of_foos = [Foo('blah'), Foo('hello'), Foo('test')]
dict_of_foos = dict ((f.id, f) for f in list_of_foos)

print dict_of_foos['blah']



TJG

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


Re: Conflicting needs for __init__ method

2007-01-16 Thread Mark Dickinson
On Jan 16, 10:25 am, "Mark Dickinson" <[EMAIL PROTECTED]> wrote:

> that is, I was working from the following two assumptions:
>
> (1) *Every* time a Rational is created, __init__ must eventually be
> called, and
> (2) The user of the class expects to call Rational() to create
> rationals.

(with apologies for replying to myself)

I'm still not being careful.  The assumptions should be these:

(1) Any creation of a Rational instance must eventually go through
Rational().
(2) A call to Rational() eventually results in a call to __init__.
(3) The user of the class expects to call Rational() to create
rationals.

There you are:  three flawed assumptions for the price of two! (1)
fails because __new__ provides an alternative, (2) could easily become
untrue by changing the metaclass, and (3)---well, who knows what the
user expects?

Right.  Now that I've thoroughly analyzed my own stupidity, things are
much clearer.  Thank you to all who replied.

Mark

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


urllib2 and HTTPBasicAuthHandler

2007-01-16 Thread m.banaouas
Hi all,
I started to use urllib2 library and HTTPBasicAuthHandler class in order 
to authenticate with a http server (Zope in this case).
I don't know why but it doesn't work, while authenticating with direct 
headers manipulation works fine!

WinXP Sp2
Python 2.4.4

Thanks in advance for your help/comments

# TestAuthHandler.py
import base64, httplib, urllib2
httplib.HTTPConnection.debuglevel = 1
#
def TestAuth(method):
   data = 
{'prot':'http','user':'admin','pass':'xx','host':'localhost','port':'8080','path':'manage','realm':'Zope'}
   url = '%(prot)s://%(host)s:%(port)s/%(path)s' % data
   req = urllib2.Request(url)
   #
   if (method == 'headers'):
 base64string = base64.encodestring('%s:%s' % (data['user'], 
data['pass']))[:-1]
 req.add_header("Authorization", "Basic %s" % base64string)
   elif  (method == 'handler'):
 auth_url = '%(host)s:%(port)s/%(path)s' % data
 auth_handler = urllib2.HTTPBasicAuthHandler()
 auth_handler.add_password(data['realm'], auth_url, data['user'], 
data['pass'])
 opener = urllib2.build_opener(auth_handler)
 urllib2.install_opener(opener)
   #
   f = urllib2.urlopen(req)
   data = f.read()
   print data
#
TestAuth('headers')
TestAuth('handler')
-
output:
-
http://www.w3.org/TR/REC-html40/loose.dtd";>


Zope on http://localhost:8080

... all right page ...



Traceback (most recent call last):
   File "C:\Test\TestAuthHandler.py", line 25, in ?
 TestAuth('handler')
   File "C:\Test\TestAuthHandler.py", line 20, in TestAuth
 f = urllib2.urlopen(req)
   File "C:\Python\Lib\urllib2.py", line 130, in urlopen
 return _opener.open(url, data)
   File "C:\Python\Lib\urllib2.py", line 364, in open
 response = meth(req, response)
   File "C:\Python\Lib\urllib2.py", line 471, in http_response
 response = self.parent.error(
   File "C:\Python\Lib\urllib2.py", line 402, in error
 return self._call_chain(*args)
   File "C:\Python\Lib\urllib2.py", line 337, in _call_chain
 result = func(*args)
   File "C:\Python\Lib\urllib2.py", line 480, in http_error_default
 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized

Process "Python" completed with Exit Code 1, at 16/01/2007 16:51:18.
-- 
http://mail.python.org/mailman/listinfo/python-list


help needed for pymorph

2007-01-16 Thread azrael
Hi guys

I tried to install and run pymorph but I am having some problems.
when I want to use mmshow() I get the message

 ImportError: DLL load failed: the specified module could not be
found

import morph
import handson

def main ():
arr = mmreadgray("beef.jpg");
mmgshow(arr)

does anyone have any idea how to fix it.


thnx

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


sslerror: (8, 'EOF occurred in violation of protocol')

2007-01-16 Thread Roopesh
I am getting an SSL error while fetching mails from Gmail over SSL on
Port 995. This problem occurs occasionally only, otherwise it works
file. Any idea why it happens.

Exception in thread Thread-1:
Traceback (most recent call last):
  File "c:\python24\lib\threading.py", line 442, in __bootstrap
self.run()
  File
"C:\The_email_archive_system\email_archiver\pensive\mail_source.py",
line
 425, in run
self.download_mails ()
  File
"C:\The_email_archive_system\email_archiver\pensive\mail_source.py",
line
 403, in download_mails
mymsg = M.retr(msg_no)
  File "c:\python24\lib\poplib.py", line 237, in retr
return self._longcmd('RETR %s' % which)
  File "c:\python24\lib\poplib.py", line 172, in _longcmd
return self._getlongresp()
  File "c:\python24\lib\poplib.py", line 157, in _getlongresp
line, o = self._getline()
  File "c:\python24\lib\poplib.py", line 374, in _getline
self._fillBuffer()
  File "c:\python24\lib\poplib.py", line 364, in _fillBuffer
localbuf = self.sslobj.read()
sslerror: (8, 'EOF occurred in violation of protocol')


Regards
Roopesh

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


Re: Segfault with tktreectrl on python-2.5 on linux

2007-01-16 Thread Anton Hartl
On 2007-01-16, klappnase <[EMAIL PROTECTED]> wrote:

>> Solutions:
>>
>> a) convince Python developers to prefix ALL new (wrt. 2.5)
>>global symbols with a prefix like "_PyAST_" or equivalent;
>>this would be consistent with how it is done anyway,
>>unfortunately the new AST symbols deviate from this practise
>>(there are symbols like "Assert", "If", "Then", ...)
>>
>>  or b) apply an equivalent rule to the global symbols in
>>tktreectrl that are global by accident, i.e. because
>>of the way the library is structured and built
>>
>
> Anton, you're cool,

Well :) understanding this bug required a looong stare at the
gdb stacktrace and a short experiment with loading shared libraries
to verify my understanding with a simple example.

>
> actually renaming Ellipsis to Py_Ast_Ellipsis in ast.c and Python-ast.c
> seems to fix this.

Alternatively renaming Ellipsis to TkTc_Ellipsis in tktreectrl
works too;  that's what I did :)

> What I don't understand, isn't it very likely that such things will
> happen when names like "Ellipsis" or "Slice" and "Index" (which I also
> found in Python-ast.c) are being used, or are the treectrl people doing
> something they should avoid?

IMHO global symbols that do not actually have any use outside
the respective library should follow a naming convention that
minimizes the probablity of name clashes like this.  I.e. both
the new AST symbols in Python 2.5 and the global symbols in
tktreectrl should be prefixed appropriately.

> I think the answer to this might be important when deciding to whom I
> should send a bug report :)

The bug report should go to both;  I actually contacted Jeremy Hylton
as a main contributor of the new AST code two weeks ago but didn't
get any response.

Regards,
Anton

PS
Thanks for your work on TkinterTreectrl!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Search Queue

2007-01-16 Thread abcd
Yea basically I need Queue like functionality with the ability to
search for a particular instance in it.  I guess I could just use a
list and search it as needed.

Thanks.

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


Re: arguments of a function/metaclass

2007-01-16 Thread Michele Simionato
[EMAIL PROTECTED] wrote:
> Hello,
>
>
> I have a member function with many (20) named arguments
>
> def __init__(self,a=1,b=2):
> self.a=a
> self.b=b
>
> I would like to get rid of the many redundant lines like self.a=a and
> set the members automatically.
> The list of default arguments could be given like
>
> def __init__(**kwargs):
> arglist={"a":1,"b":2]
>
> if this makes things easier
>
> Of course there has to be a check that raises an error in case of an
> unknown argument not mentioned in this list.
>
>
> I am sure there is an elegant way how to do this, could you give me any
> hints???
>

def __init__(self, **kw):
vars(self).update(kw)


   Michele Simionato

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


Re: arguments of a function/metaclass

2007-01-16 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> Hello,
> 
> 
> I have a member function with many (20) named arguments
> 
> def __init__(self,a=1,b=2):
> self.a=a
> self.b=b
> 
> I would like to get rid of the many redundant lines like self.a=a and
> set the members automatically.
> The list of default arguments could be given like
> 
> def __init__(**kwargs):
> arglist={"a":1,"b":2]
> 
> if this makes things easier
> 
> Of course there has to be a check that raises an error in case of an
> unknown argument not mentioned in this list.
> 
> 
> I am sure there is an elegant way how to do this, could you give me any
> hints???
> 
> 
> Many thanks
> 
> 
> 
> Daniel
> 

If it's a long list of arguments, it will stay a long list (i. e. 
representation) of arguments, whatever you do. You could minimize your 
layout, though, to e. g. use a decorator that takes a list of arguments 
automatically saved to self.
But that's just a "layout" (or design) issue and it will stay clumsy, 
whatever you do (perhaps splitting up the dict to many lines will make 
it more readable, but that's it).

To bring up a more liberate attempt, why don't you just save *all* args 
received (self.__dict__.update(kwargs)). If the user provides more 
arguments -- nevermind!
You would have to do something about default values though and here you 
got to use the list again, first updating self.__dict__ with the list 
and afterwards with kwargs.

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


Re: Conflicting needs for __init__ method

2007-01-16 Thread BJörn Lindqvist
On 1/15/07, Ben Finney <[EMAIL PROTECTED]> wrote:
> The alternate constructors are decorated as '@classmethod' since they
> won't be called as instance methods, but rather:
>
> foo = Rational.from_string("355/113")
> bar = Rational.from_int(17)
> baz = Rational.from_rational(foo)

I agree with you that that method is the right approach. But you can
also use module level functions, and sometimes that is even better:

def from_string(str):
(n, d) = parse_elements_of_string_input(str)
return Rational(n, d)

That way, you do not even have to expose the class at all to users of
the module. I think it depends on how you want users to use your
module. If you prefer:

import rational
rat = rational.from_string("123/456")

Then module level functions is best. But if you prefer:

from rational import Rational
rat = Rational.from_string("123/456")

class methods are better.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: arguments of a function/metaclass

2007-01-16 Thread goodwolf

[EMAIL PROTECTED] je napisao/la:
> Hello,
>
>
> I have a member function with many (20) named arguments
>
> def __init__(self,a=1,b=2):
> self.a=a
> self.b=b
>
> I would like to get rid of the many redundant lines like self.a=a and
> set the members automatically.
> The list of default arguments could be given like
>
> def __init__(**kwargs):
> arglist={"a":1,"b":2]
>
> if this makes things easier
>
> Of course there has to be a check that raises an error in case of an
> unknown argument not mentioned in this list.
>
>
> I am sure there is an elegant way how to do this, could you give me any
> hints???
>
>
> Many thanks
>
>
>
> Daniel

A simply solution:

def __init__(self, a=1, b=2, c=3, ..):
for key, val in locals().items():
if key != 'self':
setattr(self.__class__, key, val)

in addition:

def set(self, **kwarg):
for key in kwargs:
if hasattr(self.__class__, key):
setattr(self.__class__, key, kwargs[key])
else:
raise 

This solution is appropriate with use of proprieties.
For better proprety usage look at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418

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


Re: Conflicting needs for __init__ method

2007-01-16 Thread BJörn Lindqvist
On 1/16/07, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Tue, 16 Jan 2007 08:54:09 +1100, Ben Finney wrote:
> Think of built-ins like str() and int(). I suggest that people would be
> *really* unhappy if we needed to do this:
>
> str.from_int(45)
> str.from_float(45.0)
> str.from_list([45, 45.5])
> etc.
>
> Why do you consider that Rationals are different from built-ins in this
> regard?

I would solve that with:

import rational
rational.rational(45)
rational.rational(45.0)
rational.rational([45, 45.5])

def rational(obj):
initers = [(int, from_int), (basestring, from_str), (list, from_list)]
for obj_type, initer in initers:
if isinstance(obj, obj_type):
return initer(obj)
raise ValueError("Can not create a rational from a %r" % type(obj).__name__)

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html + javascript automations = [mechanize + ?? ] or something else?

2007-01-16 Thread ina

John wrote:
> I have to write a spyder for a webpage that uses html + javascript. I
> had it written using mechanize
> but the authors of the webpage now use a lot of javascript. Mechanize
> can no longer do the job.
> Does anyone know how I could automate my spyder to understand
> javascript? Is there a way
> to control a browser like firefox from python itself? How about IE?
> That way, we do not have
> to go thru something like mechanize?
>
> Thanks in advance for your help/comments,
> --j

You want pamie, iec or ishybrowser.  Pamie is probably the best choice
since it gets patches and updates on a regular basis.

http://pamie.sourceforge.net/

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


Re: Python web app. (advice sought)

2007-01-16 Thread Tim Williams
On 16/01/07, Ralf Schönian <[EMAIL PROTECTED]> wrote:

>
> I would also like to vote for Karrigell.
>
> BTW: Does anyone knows how to avoid stopping/starting of the webserver
> after changing external libraries? I have some own modules under
> /opt/local/python/lib and import them by extending the path with
> sys.path.append() After changing any file here, I have to restart
> Karrigell.
>

Ralf,  you should ask this on the Karrigell list  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: arguments of a function/metaclass

2007-01-16 Thread Gabriel Genellina
"goodwolf" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]
> A simply solution:
>
> def __init__(self, a=1, b=2, c=3, ..):
>for key, val in locals().items():
>if key != 'self':
>setattr(self.__class__, key, val)
>
> in addition:
>
> def set(self, **kwarg):
>for key in kwargs:
>if hasattr(self.__class__, key):
>setattr(self.__class__, key, kwargs[key])
>else:
>raise 

Why setattr(self.__class__,...) instead of setattr(self, ...)? You're 
modifying the class attributes, and that's not usually intended.

-- 
Gabriel Genellina 


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


Check a windows service

2007-01-16 Thread awel
Hi,

I'm new in python and I would like to know if it's possible to check if
a specific windows service is present and if it's possible how can I
do?

Thanks

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


Re: help needed for pymorph

2007-01-16 Thread azrael
here is the traceback

http://barok.foi.hr/~ikljaic/untitled.jpg

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


Re: Check a windows service

2007-01-16 Thread Tim Golden
awel wrote:

> I'm new in python and I would like to know if it's possible to check if
> a specific windows service is present and if it's possible how can I
> do?

This is one way:

http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services

You'd have to change that example slightly, but I
hope the principal is clear enough. If not, ask again.

TJG

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


Re: Search Queue

2007-01-16 Thread Gabriel Genellina
"abcd" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> Yea basically I need Queue like functionality with the ability to
> search for a particular instance in it.  I guess I could just use a
> list and search it as needed.

Perhaps the Queue class should be called ThreadQueue, or be contained in the 
threading module, or something like that. The current name is misleading.

-- 
Gabriel Genellina


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


smtplib question

2007-01-16 Thread gandalf gold
Hi everyone,

I was trying out smtplib and found out that I can email to anyone in my domain 
but not to an email address not in the domain. From browsing on the web, it 
seems that this has to do with the configuration of the mail server. The mail 
server in my organization is MS exchange. Obviously I can email to any email 
address from my MS outlook.

What's the easiest way to fix the program? 

Thanks.

- gan

import sys, smtplib
fr = "[EMAIL PROTECTED]"
to = "[EMAIL PROTECTED]" # will not work
line = "testing"
subj = "subject line"
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (fr, to, subj, line)
server = smtplib.SMTP("EXCHCLUSTER.ccis.edu")
server.set_debuglevel(1)
server.sendmail(fr, [to], msg)
server.quit()





 

Do you Yahoo!?
Everyone is raving about the all-new Yahoo! Mail beta.
http://new.mail.yahoo.com-- 
http://mail.python.org/mailman/listinfo/python-list

A note on heapq module

2007-01-16 Thread bearophileHUGS
In few minutes I have just written this quite raw class, it lacks
doctring (the same of the functions of the heapq module), it may
contain bugs still, I haven't tested it much. It's just a simple
wrapper around some of the functions of the heapq module (nsmallest and
nlargest are missing). Usually I use classes only when I need then, I
like functional programming enough, and this class seems to just slow
down the functions of the heapq module. But I think an improved class
similar to this one may be useful (added, replacing isn't necessary)
into the heapq module, because it can avoid cetain errors: I know what
Heaps are and how they work, but some time ago I have written a bug
into small program that uses the functions of the heapq module, because
I have added an item to the head of the heap using a normal list
method, breaking the heap invariant. With a simple class like this one
all the methods of your object keep the heap invariant, avoiding that
kind of bugs. (If you are interested I can improve this class some,
it't not difficult.)


from heapq import heapify, heappush, heappop, heapreplace

class Heap(object):
def __init__(self, init=None):
if init is None:
self.h = []
elif isinstance(init, Heap):
self.h = init.h[:]
else:
self.h = list(init)
heapify(self.h)
def smallest(self):
return self.h[0]
def sort(self, cmp=None, key=None):
self.h.sort(cmp=cmp, key=key)
def heappush(self, item):
heappush(self.h, item)
def heappop(self):
return heappop(self.h)
def heapreplace(self, item):
return heapreplace(self.h, item)
def clear(self):
del self.h[:]
def __contains__(self, item):
return item in self.h
def __hash__(self):
raise TypeError("Heap objects are unhashable.")
def __iter__(self):
return self.h.__iter__()
def __eq__(self, other):
return isinstance(other, Heap) and self.h == other.h
def __ne__(self, other):
return not isinstance(other, Heap) or self.h != other.h
def __len__(self):
return len(self.h)
def __nonzero__(self):
return bool(self.h)
def __str__(self):
return str(self.h)
def __repr__(self):
return "Heap(%s)" % self.h if self.h else "Heap()"

Bye,
bearophile

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


Re: Check a windows service

2007-01-16 Thread Chris Mellon
On 16 Jan 2007 09:09:34 -0800, Tim Golden <[EMAIL PROTECTED]> wrote:
> awel wrote:
>
> > I'm new in python and I would like to know if it's possible to check if
> > a specific windows service is present and if it's possible how can I
> > do?
>
> This is one way:
>
> http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services
>
> You'd have to change that example slightly, but I
> hope the principal is clear enough. If not, ask again.
>
> TJG
>

Here's some code cut & pasted from the demos included in the win32 module:

import win32service
import win32con


def EnumServices():
resume = 0
accessSCM = win32con.GENERIC_READ
accessSrv = win32service.SC_MANAGER_ALL_ACCESS

#Open Service Control Manager
hscm = win32service.OpenSCManager(None, None, accessSCM)

#Enumerate Service Control Manager DB

typeFilter = win32service.SERVICE_WIN32
stateFilter = win32service.SERVICE_STATE_ALL

statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)
for (short_name, desc, status) in statuses:
print short_name, desc, status
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check a windows service

2007-01-16 Thread Gabriel Genellina
"awel" <[EMAIL PROTECTED]> escribió en el mensaje
news:[EMAIL PROTECTED]

> I'm new in python and I would like to know if it's possible to check if
> a specific windows service is present and if it's possible how can I
> do?

Yes, using the wmi module, but you'll have to search the Microsoft
documentation on how to enumerate services and their properties:
http://msdn2.microsoft.com/en-us/library/aa384642.aspx
The code might look like this, but the names may be wrong:

import wmi
import pythoncom
pythoncom.CoInitialize()
w = wmi.WMI()
for s in w.Win32_Services():
  print s

-- 
Gabriel Genellina 


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


Re: arguments of a function/metaclass

2007-01-16 Thread goodwolf

Gabriel Genellina je napisao/la:
> "goodwolf" <[EMAIL PROTECTED]> escribió en el mensaje
> news:[EMAIL PROTECTED]
> > A simply solution:
> >
> > def __init__(self, a=1, b=2, c=3, ..):
> >for key, val in locals().items():
> >if key != 'self':
> >setattr(self.__class__, key, val)
> >
> > in addition:
> >
> > def set(self, **kwarg):
> >for key in kwargs:
> >if hasattr(self.__class__, key):
> >setattr(self.__class__, key, kwargs[key])
> >else:
> >raise 
>
> Why setattr(self.__class__,...) instead of setattr(self, ...)? You're
> modifying the class attributes, and that's not usually intended.
>
> -- 
> Gabriel Genellina

My error. Post was written directly. Sorry.

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


Re: A note on heapq module

2007-01-16 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> some time ago I have written a bug
> into small program that uses the functions of the heapq module, because
> I have added an item to the head of the heap using a normal list
> method, breaking the heap invariant.

I know I've had similar bugs in my code before.

> from heapq import heapify, heappush, heappop, heapreplace
> 
> class Heap(object):
[snip implementation]

+1 for adding a Heap object like this to the collections module. If you 
can make a little time to add some tests (you could probably steal a lot 
of what you need from test_heapq.py) you should definitely submit it as 
a patch for 2.6.

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


Python for Maemo -- new version released

2007-01-16 Thread Osvaldo Santana
We from INdT (Nokia Institute of Technology -- Brazil) have the pleasure
to announce the new version of Python for Maemo, for Maemo SDK 2.1
("Scirocco") and SDK 3.0 ("Bora"). Highlights of this version:

* Support for Nokia N800[1] device/software (SDK 3.0)
* Language updated to Python 2.5
* Updated bindings
* Added bindings to new Hildon widgets
* Improved OSSO bindings
* Project home has moved to Garage.maemo.org.

The new project page is http://pymaemo.garage.maemo.org. There you can
find directions about repositories, installation on SDK/device etc. The
release notes for this version can be found at
http://pymaemo.garage.maemo.org/pymaemo25_releasenotes.html.

We encourage everybody to try the software and report bugs/improvement
requests.

Thanks,
Osvaldo Santana Neto

[1] http://europe.nokia.com/phones/n800


-- 
Osvaldo Santana Neto (aCiDBaSe)
http://www.pythonologia.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: smtplib question

2007-01-16 Thread Tim Williams
On 16/01/07, gandalf gold <[EMAIL PROTECTED]> wrote:
>
> Hi everyone,
>
> I was trying out smtplib and found out that I can email to anyone in my
> domain but not to an email address not in the domain. From browsing on the
> web, it seems that this has to do with the configuration of the mail server.
> The mail server in my organization is MS exchange. Obviously I can email to
> any email address from my MS outlook.
>
> What's the easiest way to fix the program?
>
> Thanks.
>
> - gan
>
> import sys, smtplib
> fr = "[EMAIL PROTECTED]"
> to = "[EMAIL PROTECTED]" # will not work
> line = "testing"
> subj = "subject line"
> msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (fr, to, subj, line)
> server = smtplib.SMTP("EXCHCLUSTER.ccis.edu")
> server.set_debuglevel(1)
> server.sendmail(fr, [to], msg)
> server.quit()
>

You will need to get smtplib to authenticate when connecting to the
exchange server.Use the login function and the same username/pw
that you use to login to Outlook.

server.login(user, password)

Note: Your exchange administrator may have disabled this function.  (
Your Outlook will almost certainly be using MAPI not SMTP to talk to
the server).

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


PyQt: QListviewItemIterator

2007-01-16 Thread Tina I
Hi,
I'm fairly new to both Python and Qt so please bare with me.

I have a QListView with a number of columns. In order to filter the 
output I iterate using QListViewItemIterator looking for the string 
entered by the user (filterString). Currently I do it this way:


it = QListViewItemIterator(self.authListView)
 try:
 while it:
 item = it.current()
 if item.text(0).contains(filterString) or 
item.text(1).contains(filterString) or item.text(2).contains(filterString):
 item.setVisible(1)
 else:
 item.setVisible(0)
 it +=1
 except AttributeError:
 pass


Basically I iterate through the ListView until it goes beyond the list 
and raise an exception, which I catch. It works but to be honest it 
looks and feels ugly; "Do something until it goes wrong"

So, question: How can I know I have reached the last item in the QListView?

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


Re: A note on heapq module

2007-01-16 Thread bearophileHUGS
I think the sort has to be simplified, otherwise it can't keep the heap
invariant...

def sort(self):
self.h.sort()

Bye,
bearophile

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


Re: Regular expressions question

2007-01-16 Thread Victor Polukcht
Great thnx. It works.

On Jan 16, 6:02 pm, Wolfgang Grafen <[EMAIL PROTECTED]>
wrote:
> Victor Polukcht wrote:
> > I have 2 strings:
>
> > "Global   etsi3   *200 ok30   100% 100%
> > Outgoing"
> > and
> > "Global   etsi3   *   4 ok 30   100% 100%
> > Outgoing"
>
> > The difference is "*200" instead of "*  4". Is there ability to write a
> > regular expression that will match both of that 
> > strings? x.py begin 
> import re
>
> s1 = "Global   etsi3   *200 ok30   100% 100% Outgoing"
> s2 = "Global   etsi3   *   4 ok 30   100% 100% 
> Outgoing"
>
> re_m = re.compile( "^"
> "(\S+)" # Global
> "\s+"
> "(\S+)" # etsi3
> "\s+"
> "((\*)\s*(\d+))"# *200 *  4
> "\s+"
> "(\S+)" # ok
> "\s+"
> "(\S+)" # 30
> "\s+"
> "(\S+)" # 100%
> "\s+"
> "(\S+)" # 100%
> "\s+"
> "(\S+)" # Outgoing
> "$"
>   ).match
>
> print "match s1:", re_m(s1).groups()
> print "match s2:", re_m(s2).groups()
> - x.py file end -
>
> % python x.py
> match s1: ('Global', 'etsi3', '*200', '*', '200', 'ok', '30', '100%', '100%', 
> 'Outgoing')
> match s2: ('Global', 'etsi3', '*   4', '*', '4', 'ok', '30', '100%', '100%', 
> 'Outgoing')

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


Re: urllib2 and HTTPBasicAuthHandler

2007-01-16 Thread Max Erickson
"m.banaouas" <[EMAIL PROTECTED]> wrote:

> Hi all,
> I started to use urllib2 library and HTTPBasicAuthHandler class
> in order to authenticate with a http server (Zope in this case).
> I don't know why but it doesn't work, while authenticating with
> direct headers manipulation works fine!
> 
...
> port':'8080','path':'manage','realm':'Zope'} 
>url = '%(prot)s://%(host)s:%(port)s/%(path)s' % data
...

Are you certain that the realm on the server matches 'Zope'?

HTTPBasicAuthHandler uses the realm to look for the password, if the 
realm the server provides is different, urllib2 will respond as if it 
does not have a user/password.

If you are only doing one request, it isn't that big a deal; if you 
are doing many requests or want urllib2 to handle the response for 
other reseans, you can use a default realm, see the bottom of this 
example:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305288

(The advantage of using a default rather than making sure the realm is 
correct is that it can change and you won't have to do anything)



max

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


Re: A note on heapq module

2007-01-16 Thread Jussi Salmela
[EMAIL PROTECTED] kirjoitti:
> I think the sort has to be simplified, otherwise it can't keep the heap
> invariant...
> 
> def sort(self):
> self.h.sort()
> 
> Bye,
> bearophile
> 
And __repr__ should be something like this:
=
 def __repr__(self):
 if self.h:
 return "Heap(%s)" % self.h
 else:
 return "Heap()"
==
to make it compatible with versions earlier than 2.5

Cheers,
Jussi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help needed for pymorph

2007-01-16 Thread azrael
yes, in the PIL directory




Dennis Lee Bieber je napisao/la:
> On 16 Jan 2007 08:07:09 -0800, "azrael" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>
> >
> > does anyone have any idea how to fix it.
> >
>   Well, the last line of your traceback indicates that the error is
> somewhere in the PIL libraries -- do you have a _imagingtk.pyd file?
> --
>   WulfraedDennis Lee Bieber   KD6MOG
>   [EMAIL PROTECTED]   [EMAIL PROTECTED]
>   HTTP://wlfraed.home.netcom.com/
>   (Bestiaria Support Staff:   [EMAIL PROTECTED])
>   HTTP://www.bestiaria.com/

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


Re: whats wrong with my reg expression ?

2007-01-16 Thread Gert Cuykens
thx it works now
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A note on heapq module

2007-01-16 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
> In few minutes I have just written this quite raw class, 
I'd suggest some changes.  It is nice to have Heaps with equal
contents equal no matter what order the inserts have been done.
Consider how you want Heap([1, 2, 3]) and Heap([3, 1, 2]) to behave.
Similarly, it is nice to have str and repr produce canonical
representations (I would skip the __str__ code, myself, though).
Also, subclasses should get their identities tweaked as so:

> class Heap(object):
> ...
> def sort(self, cmp=None, key=None):
> self.h.sort(cmp=cmp, key=key)
I'd remove this method.
> ...
> def __eq__(self, other):
> return isinstance(other, Heap) and self.h == other.h
   return isinstance(other, self.__class__) and sorted(
  self.h) == sorted(other.h)
> def __ne__(self, other):
> return not isinstance(other, Heap) or self.h != other.h
   return not isinstance(other, self.__class__) and sorted(
  self.h) != sorted(other.h)
> ...
> def __str__(self):
> return str(self.h)
   return str(sorted(self.h))
> def __repr__(self):
> return "Heap(%s)" % self.h if self.h else "Heap()"
   return "%s(%s)" % (self.__class__.__name__, sorted(self.h))
And I'd add:
   def __lt__(self, other):
   raise TypeError('no ordering relation is defined for %s'
   % self.__class__.__name__)
   __gt__ = __le__ = __ge__ = __lt__

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


Re: A note on heapq module

2007-01-16 Thread Scott David Daniels
Scott David Daniels wrote:

Sorry, I blew the __ne__:

>> def __ne__(self, other):
>> return not isinstance(other, Heap) or self.h != other.h
>   return not isinstance(other, self.__class__) and sorted(
>  self.h) != sorted(other.h)
Should be:
   return not isinstance(other, self.__class__) or sorted(
 self.h) != sorted(other.h)

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


How can I create a linked list in Python?

2007-01-16 Thread Dongsheng Ruan
with a cell class like this:

#!/usr/bin/python

import sys

class Cell:

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

 def __str__( self ):
  return str( self.data )

 def echo( self ):
  print self.__str__() 


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


Re: Segfault with tktreectrl on python-2.5 on linux

2007-01-16 Thread klappnase

Anton Hartl schrieb:

> The bug report should go to both;  I actually contacted Jeremy Hylton
> as a main contributor of the new AST code two weeks ago but didn't
> get any response.
>

Ok, I submitted bug reports on both the tktreectrl and the python
sourceforge pages.
Now I'll have a nice cup of tea and see what happens :)

Regards

Michael

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


Re: How can I create a linked list in Python?

2007-01-16 Thread Gary Herron
Dongsheng Ruan wrote:
> with a cell class like this:
>
> #!/usr/bin/python
>
> import sys
>
> class Cell:
>
>  def __init__( self, data, next=None ):
>   self.data = data
>   self.next = next
>
>  def __str__( self ):
>   return str( self.data )
>
>  def echo( self ):
>   print self.__str__() 
>   
If you really want a list (as Python defines a list - with all the methods) 
then you should use Python's lists.  They are quite efficient and convenient:

l = [Cell(1), Cell(2), Cell(3)]

However, if what you want is each cell to refer to a next cell (which after all 
is what a linked list does), then you already have it with the next attribute.  
(In other languages you might implement 'next' as a pointer, while in Python we 
call it a reference -- but it amounts to the same thing.)  Create it this way:

c = Cell(3)
b = Cell(2, c) 
a = Cell(1, b)

or

a = Cell(1, Cell(2, Cell(3)))

However, I'll repeat this:  The concept of a linked list if a figment of 
languages with pointer data types.  Python abstracts that by allowing 
attributes to contain references to other objects.  However, you're much better 
off if you can use Python's list data structure rather than try to emulate an 
outdated concept in a modern language.

Gary Herron



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


How to determine what exceptions a method might raise?

2007-01-16 Thread Ed Jensen
I'm really enjoying using the Python interactive interpreter to learn
more about the language.  It's fantastic you can get method help right
in there as well.  It saves a lot of time.

With that in mind, is there an easy way in the interactive interpreter
to determine which exceptions a method might raise?  For example, it
would be handy if there was something I could do in the interactive
interpreter to make it tell me what exceptions the file method might
raise (such as IOError).

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


Re: How can I create a linked list in Python?

2007-01-16 Thread azrael
How can I implement a linked list like the implementations in c with
struct-s and arrays (or pointers).
to simbolize the working principe



Gary Herron je napisao/la:
> Dongsheng Ruan wrote:
> > with a cell class like this:
> >
> > #!/usr/bin/python
> >
> > import sys
> >
> > class Cell:
> >
> >  def __init__( self, data, next=None ):
> >   self.data = data
> >   self.next = next
> >
> >  def __str__( self ):
> >   return str( self.data )
> >
> >  def echo( self ):
> >   print self.__str__()
> >
> If you really want a list (as Python defines a list - with all the methods) 
> then you should use Python's lists.  They are quite efficient and convenient:
>
> l = [Cell(1), Cell(2), Cell(3)]
>
> However, if what you want is each cell to refer to a next cell (which after 
> all is what a linked list does), then you already have it with the next 
> attribute.  (In other languages you might implement 'next' as a pointer, 
> while in Python we call it a reference -- but it amounts to the same thing.)  
> Create it this way:
>
> c = Cell(3)
> b = Cell(2, c)
> a = Cell(1, b)
>
> or
>
> a = Cell(1, Cell(2, Cell(3)))
>
> However, I'll repeat this:  The concept of a linked list if a figment of 
> languages with pointer data types.  Python abstracts that by allowing 
> attributes to contain references to other objects.  However, you're much 
> better off if you can use Python's list data structure rather than try to 
> emulate an outdated concept in a modern language.
> 
> Gary Herron

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


Re: for v in l:

2007-01-16 Thread Gert Cuykens
ok thx this was just what i was looking for

http://docs.python.org/tut/node7.html#SECTION00760
-- 
http://mail.python.org/mailman/listinfo/python-list


OT: teleporters (Was: General Question About Python)

2007-01-16 Thread Carroll, Barry
> -Original Message-
> From: Hendrik van Rooyen [mailto:[EMAIL PROTECTED]
> Sent: Saturday, January 13, 2007 9:47 PM
> To: Torabisu; python-list@python.org
> Subject: Re: General Question About Python
> 
>  "Torabisu" <[EMAIL PROTECTED]> wrote:
> 
> 
> >
> > Hendrik van Rooyen wrote:
> 
> > > What do you want done? - I am only a thousand miles away...
> > >
> >
> > If I can just get my Python teleporter sorted out, distance will be
no
> > problem...  A little buggy at the moment though...  Poor John, I
told
> > him not to test it but oh well.
> 
> OMG!  - I have been feeding that unexpected heap of minced meat
> to the cat...
> 
> - Hendrik
> 
Gentlemen:

Y'all really need to be more careful.  Much research has been done on
matter teleportation, and there is ample documentation of the dangers
involved.  The logs of the USS Enterprise alone are rife with the
horrible consequences of "transporters gone wild".(1) In addition, the
historical records of the  NSEA Protector contain a particularly
gruesome account of a "digital conveyor" malfunction which caused the
subject to turn inside out and then explode.(2)

These experiments MUST be conducted under the most rigorous controls to
prevent similar catastrophes.  (Unless, you're using Perl programmers as
test subjects, in which case it's okay.  ;^)

Humorously yours,
 
Barry

---
(1) "Star Trek: the Motion Picture": Roddenberry, Foster and Wise, 1979 
(2) "Galaxy Quest": Howard, Gordon and Parisot, 1999


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


Re: Regex Question

2007-01-16 Thread Bill Mill
James Stroud wrote:
> Bill Mill wrote:
> > Hello all,
> >
> > I've got a test script:
> >
> >  start python code =
> >
> > tests2 = ["item1: alpha; item2: beta. item3 - gamma--",
> > "item1: alpha; item3 - gamma--"]
> >
> > def test_re(regex):
> >r = re.compile(regex, re.MULTILINE)
> >for test in tests2:
> >res = r.search(test)
> >if res:
> >print res.groups()
> >else:
> >print "Failed"
> >
> >  end python code 
> >
> > And a simple question:
> >
> > Why does the first regex that follows successfully grab "beta", while
> > the second one doesn't?
> >
> > In [131]: test_re(r"(?:item2: (.*?)\.)")
> > ('beta',)
> > Failed
> >
> > In [132]: test_re(r"(?:item2: (.*?)\.)?")
> > (None,)
> > (None,)
> >
> > Shouldn't the '?' greedily grab the group match?
> >
> > Thanks
> > Bill Mill
> > bill.mill at gmail.com
>
> The question-mark matches at zero or one. The first match will be a
> group with nothing in it, which satisfies the zero condition. Perhaps
> you mean "+"?
>
> e.g.
>
> py> import re
> py> rgx = re.compile('1?')
> py> rgx.search('a1').groups()
> (None,)
> py> rgx = re.compile('(1)+')
> py> rgx.search('a1').groups()

But shouldn't the ? be greedy, and thus prefer the one match to the
zero? This is my sticking point - I've seen that plus works, and this
just confuses me more.

-Bill Mill
bill.mill at gmail.com

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


Re: How to determine what exceptions a method might raise?

2007-01-16 Thread Harlin Seritt
Hi Ed,

Generally checking the sources give a very good clue as to what
exceptions the interpreter can raise. Look around _builtins_ for this.

Harlin Seritt


Ed Jensen wrote:
> I'm really enjoying using the Python interactive interpreter to learn
> more about the language.  It's fantastic you can get method help right
> in there as well.  It saves a lot of time.
>
> With that in mind, is there an easy way in the interactive interpreter
> to determine which exceptions a method might raise?  For example, it
> would be handy if there was something I could do in the interactive
> interpreter to make it tell me what exceptions the file method might
> raise (such as IOError).
> 
> Thanks in advance.

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


  1   2   >