Re: ANN: WHIFF += Flash chart widget support (Aaron Watters)

2009-06-12 Thread oyster
nice
the only pity is that amcharts is not a money-free product
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: command line of a process.exe on another host

2009-06-12 Thread Tim Golden

Harry wrote:

HI ,
I have number of process run on different windows servers which run's 
with different command line parameters. for example "process.exe 
-input statusurl: http://sss.com "., These parameters can vary from 
host to host. using Psexec I know the PID and process name which are 
running on these machines, but how I can read the command line 
parameters of these process. Is there a way to read these command line 
of the proess via python pls?


WMI can get this for you. This example uses my WMI module
from here:

 http://timgolden.me.uk/python/wmi.html

but it's not hard to do it with "raw" Python / Windows.


import wmi

c = wmi.WMI ("other_machine")
for p in c.Win32_Process (name="process.exe"):
 print p.CommandLine



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


Re: install older Python version parallel

2009-06-12 Thread edexter
On Jun 11, 8:50 am, "S. Dornseifer"  wrote:
> Hi everybody,
>
> The situation:
> I wrote a GUI, based on Python, TkInter and Pmw.
> It runs perfectly fine with Python 2.4 (providing, TkInter and Pmw are
> installed). But it crashes with Python 2.6. I tried this on MacOSX11.4
> and various Linux Distributions.
> Crashes occurs when I activate a Pmw.Diaog (I guess this is due to a bug
> in the installed blt package), also when I use setitems on
> Pmw.OptionMenu (I guess this is due to another package, associated with
> tcl/tk).
>
> The target:
> I have to get my GUI work under openSUSE 11.1 (x86_64).
>
> My plan:
> On my openSUSE 11.1 (x86_64), Python 2.6 is installed by default.
> I would like to know, how to install Python 2.4 along with TkInter and
> Pmw (and packages that are required by them), parallel to the existing
> Python 2.6. So that I do not break other software that depends on Python
> 2.6.
>
> If you can think of another plan, I would be also glad to discuss it.
>
> Cheers,
> Simon

0n windows I had multiple versions installed ex
python24
python25

i would write a batch file
C:\python24\python.exe test.py
pause

the pause is there just so that I can see an error message if there is
one.

I have no idea what would work for the mac or linux though... I
suspect something simular might work after all
why rewrite all your software because someone else wants you to have a
particular version of python not with the amount of disk space that is
available now-adays..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: install older Python version parallel

2009-06-12 Thread edexter
On Jun 11, 8:50 am, "S. Dornseifer"  wrote:
> Hi everybody,
>
> The situation:
> I wrote a GUI, based on Python, TkInter and Pmw.
> It runs perfectly fine with Python 2.4 (providing, TkInter and Pmw are
> installed). But it crashes with Python 2.6. I tried this on MacOSX11.4
> and various Linux Distributions.
> Crashes occurs when I activate a Pmw.Diaog (I guess this is due to a bug
> in the installed blt package), also when I use setitems on
> Pmw.OptionMenu (I guess this is due to another package, associated with
> tcl/tk).
>
> The target:
> I have to get my GUI work under openSUSE 11.1 (x86_64).
>
> My plan:
> On my openSUSE 11.1 (x86_64), Python 2.6 is installed by default.
> I would like to know, how to install Python 2.4 along with TkInter and
> Pmw (and packages that are required by them), parallel to the existing
> Python 2.6. So that I do not break other software that depends on Python
> 2.6.
>
> If you can think of another plan, I would be also glad to discuss it.
>
> Cheers,
> Simon

I suspect you want to install python 2.4 and then reinstall 2.6  I did
that in windows and I don't understand why it wouldn't work in linux
-- 
http://mail.python.org/mailman/listinfo/python-list


RE replace problem too

2009-06-12 Thread oyster
in my case, I want to replace all the function name with '', that is
sin(1)  ->  (1)
sin(pi*(2+4))  -> (pi*(2+4))
how can I use RE in this situation? thanx
-- 
http://mail.python.org/mailman/listinfo/python-list


Measuring Fractal Dimension ?

2009-06-12 Thread Peter Billam
Greetings.  Are there any modules, packages, whatever, that will
measure the fractal dimensions of a dataset, e.g. a time-series ?
Like the Correlation Dimension, the Information Dimension, etc...

Peter

-- 
Peter Billam  www.pjb.com.auwww.pjb.com.au/comp/contact.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Periodic table gets a new element

2009-06-12 Thread Mensanator
On Jun 11, 8:27 am, Jean-Michel Pichavant 
wrote:
> Not if this element is to end up in some further ultimate nuclear weapon
>   :-)  

Don't worry, a millisecond half-life is kind of a wet
blanket as far as weapon design is concerned.

> , unless you are using python to conquer the world (I've been
> told this is GVR main secret objective).
>
>
>
> MRAB wrote:
> > Element 112 is to be named. Do you think we could persuade the
> > scientists to name it "Pythonium"? :-)
>
> >http://news.bbc.co.uk/1/hi/sci/tech/8093374.stm- Hide quoted text -
>
> - Show quoted text -

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


Re: Voronoi diagram algorithm (Fortune’s sweepline )

2009-06-12 Thread Bearophile
dorzey:
> Found this python implementation:
> http://www.oxfish.com/python/voronoi.py

Looks very nice, and it may be ShedSkin-compilable too.

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EOF problem with ENTER

2009-06-12 Thread Francesco Bochicchio
On 12 Giu, 08:49, Prasoon  wrote:
> On Jun 12, 11:28 am, Chris Rebert  wrote:
>
>
>
>
>
> > On Thu, Jun 11, 2009 at 11:17 PM, Prasoon wrote:
> > > I am new to python
> > > I have written the following program in python.It is the solution of
> > > problem ETF in SPOJ.
>
> > > #Euler Totient Function
>
> > > from math import sqrt
> > > def etf(n):
> > >   i,res =2,n
> > >   while(i*i<=n):
> > >      if(n%i==0):
> > >            res-=res/i
> > >      while(n%i==0):
> > >            n/=i
> > >      i+=1
> > >   if(n>1):
> > >        res-=res/n
> > >   return res
>
> > > def main():
> > >  t=input()
> > >  while(t):
> > >    x=input()
> > >    print str(etf(x))
> > >    t-=1
>
> > > if __name__ == "__main__":
> > >  main()
>
> > > The problem with my code is that whenever I press an extra "Enter"
> > > button instead of getting the cursor moved to the next line.I get
> > > an error
>
> > > _SyntaxError- EOF while parsing and the program terminates.._
>
> > > How should  the code be modified so that even after  pressing an extra
> > > "Enter" button the cursor get moved to the next line instead to
> > > throwing an exception..
>
> > Use raw_input() instead of input() [at least until you switch to Python 
> > 3.x].
> > input() does an implicit eval() of the keyboard input, which is (in
> > part) causing your problem.
> > Note that you'll need to explicitly convert the string raw_input()
> > reads in using either int() or float() as appropriate.
>
> > Still, you can't just enter extra lines and expect the program to
> > automatically ignore them. You'll have to write the extra code
> > yourself to handle empty input from the user.
>
> > Cheers,
> > Chris
> > --http://blog.rebertia.com
>
> I am using Python 2.6
> I have modified that code
> def main():
>   t=int(raw_input())
>   while(t):
>     x=int(raw_input())
>     print str(etf(x))
>     t-=1
>
> what should i do to handle new line and space..
> We used to get spaces and newline in C using their ASCII values ...can
> similar things be done here???
>
> Please write the code snippet(by modifying my code) from which i can
> understand something..!
>
> - Mostra testo citato -

You could do:

while True:
   x = raw_input("Enter x=>")
   if x != "" : break # if you just press enter, raw_input returns an
empty string

Note that this still leaves out the case when you type something which
is not a number.
To cover this case, supposing that you need a float, you could do like
this (NOT TESTED):

while True:
   x_str = raw_input("Enter x=>")
   if x_str != "" : #  to prevent having the error message on empty
imput
  try:
 x = float(x_str)
 break # if it gets here the conversion in float was succesful
  except ValueError :
 print "The input '%s' cannot be converted in float" % x_str

This code exits from the loop only when you supply a string that
represents a floating number


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


Re: Win32 stdin redirection

2009-06-12 Thread Tim Harig
On 2009-06-12, lynvie  wrote:
> Thanks for the additional info! I had no idea this was an old Windows
> problem... I'm using Windows XP and I'm up-to-date on all my patches.

s/problem/feature/
Steve Ballmer, CEO of Microsoft, would prefer that you think of it as a
'feature'.

This is a problem that I would suspect has plagued a lot of people because
it doesn't seem to be overly documented in any of the popular python
learning materials.  Even Mark Hammond & Andy Robinson's book _Python
Programming on Win32_ doesn't mention the problem directly in its Windowes
gotchas section-- though it does mention there are a number of bugs in the
Windows implementation of popen().

> The good news is I can invoke the script correctly now, thanks to your
> help!

Happy Pythoning!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help in Python regular expression

2009-06-12 Thread Vlastimil Brom
2009/6/12 meryl :
> On Jun 11, 9:41 pm, "Mark Tolonen"  wrote:
>> "meryl"  wrote in message
>>
>> > I have this regular expression

>...

> I try adding ".*" at the end , but it ends up just matching the second
> one.

If there can be more matches in a line, maybe the non-greedy
quantifier ".*?", and a lookahead assertion can help.
You can try something like:
(?m)Render(?:Block|Table) (?:\(\w+\)|{\w+})(.+?(?=$|RenderBlock))?

(?m) multiline flag - also the end of line can be matched with $
.+? any character - one or more (no greedy, i.e. as little as possible)
(?=$|RenderBlock) the lookahead assertion - condition for the
following string - not part of the match - here the end of line/string
or "RenderBlock"

I guess, if you need to add more possibilities or conditions depending
on your source data, it might get too complex for a single regular
expression to match effectively.

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


failed to build decompyle/unpyc project on WindowsXP

2009-06-12 Thread higer
Maybe everyone know that decompyle(hosted on SourceForge.net) is a
tool to transfer a .pyc file to .py file and now it does only support
Python 2.3 or the below. I have found a project named unpyc which can
support Python version 2.5. Unpyc project is build on decompyle which
is hosted on google code and if you want you can download it.

I build unpyc on Ubuntu successfully and can run it ok. But with some
purpose, I just want to use this tool on my WindowsXP, so I tried to
build it. I have tried many times and methods, with .net2003 or
MingGW, but I failed. So,I come here looking for sombody can help me.I
will give the showing error message with different method on the
following:

1 Using command : python setup.py install
F:\unpyc>python setup.py install
running install
running build
running build_py
creating build\lib.win32-2.5
creating build\lib.win32-2.5\unpyc
copying unpyc\dis_15.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_16.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_20.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_21.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_22.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_23.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_24.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_25.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_26.py -> build\lib.win32-2.5\unpyc
copying unpyc\dis_files.py -> build\lib.win32-2.5\unpyc
copying unpyc\magics.py -> build\lib.win32-2.5\unpyc
copying unpyc\marshal_files.py -> build\lib.win32-2.5\unpyc
copying unpyc\opcode_23.py -> build\lib.win32-2.5\unpyc
copying unpyc\opcode_24.py -> build\lib.win32-2.5\unpyc
copying unpyc\opcode_25.py -> build\lib.win32-2.5\unpyc
copying unpyc\opcode_26.py -> build\lib.win32-2.5\unpyc
copying unpyc\Parser.py -> build\lib.win32-2.5\unpyc
copying unpyc\Scanner.py -> build\lib.win32-2.5\unpyc
copying unpyc\spark.py -> build\lib.win32-2.5\unpyc
copying unpyc\verify.py -> build\lib.win32-2.5\unpyc
copying unpyc\Walker.py -> build\lib.win32-2.5\unpyc
copying unpyc\__init__.py -> build\lib.win32-2.5\unpyc
running build_ext
building 'unpyc/marshal_25' extension
creating build\temp.win32-2.5
creating build\temp.win32-2.5\Release
creating build\temp.win32-2.5\Release\unpyc
f:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c /
nologo /Ox /MD /W3 /GX /DNDEBU
G -IF:\Python25\include -IF:\Python25\PC /Tcunpyc/marshal_25.c /Fobuild
\temp.win32-2.5\Release\unpyc
/marshal_25.obj
marshal_25.c
unpyc\marshal_25.c(401) : warning C4273: 'PyMarshal_WriteLongToFile' :
inconsistent dll linkage
unpyc\marshal_25.c(413) : warning C4273:
'PyMarshal_WriteObjectToFile' : inconsistent dll linkage
unpyc\marshal_25.c(1004) : warning C4273:
'PyMarshal_ReadShortFromFile' : inconsistent dll linkage
unpyc\marshal_25.c(1015) : warning C4273:
'PyMarshal_ReadLongFromFile' : inconsistent dll linkage
unpyc\marshal_25.c(1044) : warning C4273:
'PyMarshal_ReadLastObjectFromFile' : inconsistent dll link
age
unpyc\marshal_25.c(1087) : warning C4273:
'PyMarshal_ReadObjectFromFile' : inconsistent dll linkage
unpyc\marshal_25.c(1101) : warning C4273:
'PyMarshal_ReadObjectFromString' : inconsistent dll linkag
e
unpyc\marshal_25.c(1116) : warning C4273:
'PyMarshal_WriteObjectToString' : inconsistent dll linkage

f:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe /
DLL /nologo /INCREMENTAL:NO /LI
BPATH:F:\Python25\libs /LIBPATH:F:\Python25\PCBuild /EXPORT:initunpyc/
marshal_25 build\temp.win32-2.
5\Release\unpyc/marshal_25.obj /OUT:build\lib.win32-2.5\unpyc/
marshal_25.pyd /IMPLIB:build\temp.win3
2-2.5\Release\unpyc\marshal_25.lib
marshal_25.obj : error LNK2001: unresolved external symbol initunpyc/
marshal_25
build\temp.win32-2.5\Release\unpyc\marshal_25.lib : fatal error
LNK1120: 1 unresolved externals
LINK : fatal error LNK1141: failure during build of exports file
error: command '"f:\Program Files\Microsoft Visual Studio .NET
2003\Vc7\bin\link.exe"' failed with e
xit status 1141

2Using command:   python setup.py build -c mingw32

F:\unpyc>python setup.py build -c mingw32
running build
running build_py
running build_ext
building 'unpyc/marshal_25' extension
F:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IF:\Python25\include -
IF:\Python25\PC -c unpyc/mars
hal_25.c -o build\temp.win32-2.5\Release\unpyc\marshal_25.o
unpyc/marshal_25.c:1087: warning: 'PyMarshal_ReadObjectFromFile'
defined locally after being referen
ced with dllimport linkage
unpyc/marshal_25.c:1101: warning: 'PyMarshal_ReadObjectFromString'
defined locally after being refer
enced with dllimport linkage
writing build\temp.win32-2.5\Release\unpyc\marshal_25.def
F:\mingw\bin\gcc.exe -mno-cygwin -shared -s build
\temp.win32-2.5\Release\unpyc\marshal_25.o build\te
mp.win32-2.5\Release\unpyc\marshal_25.def -LF:\Python25\libs -LF:
\Python25\PCBuild -lpython25 -lmsvc
r71 -o build\lib.win32-2.5\unpyc/marshal_25.pyd
F:\Python25\libs/libpython25.a(dcbbs00336.o):(.text+0x0): multiple
definition of `PyMarshal_ReadObje
ctFromStr

Re: EOF problem with ENTER

2009-06-12 Thread Prasoon

> You could do:
>
> while True:
>    x = raw_input("Enter x=>")
>    if x != "" : break # if you just press enter, raw_input returns an
> empty string
>
> Note that this still leaves out the case when you type something which
> is not a number.
> To cover this case, supposing that you need a float, you could do like
> this (NOT TESTED):
>
> while True:
>    x_str = raw_input("Enter x=>")
>    if x_str != "" : #  to prevent having the error message on empty
> imput
>       try:
>          x = float(x_str)
>          break # if it gets here the conversion in float was succesful
>       except ValueError :
>          print "The input '%s' cannot be converted in float" % x_str
>
> This code exits from the loop only when you supply a string that
> represents a floating number
>


I modified my code to

#Euler Totient Function
import sys
from math import sqrt
def etf(n):
   i,res =2,n
   while(i*i<=n):
  if(n%i==0):
res-=res/i
  while(n%i==0):
n/=i
  i+=1
   if(n>1):
res-=res/n
   return res

def main():
  while True:
   t=raw_input()
   if t!="":break
  t=int(t)
  while(t):
while True:
 x=raw_input()
 if x!="":break
x=int(x)
print str(etf(x))
t-=1

if __name__ == "__main__":
  main()

Now it is working fine thanks!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Exception inside loop wrongly failing doctest

2009-06-12 Thread Steven D'Aprano
One of my doctests is failing, and I suspect a bug.

The test involves matching an exception in a for-loop. Here are two
simplified versions of the test, both should pass but only the first does.


As a doctest, this passes:

>>> for x in [3, 2, 1]:
... print (x, 1.0/x)
...
(3, 0.1)
(2, 0.5)
(1, 1.0)


However, this fails:

>>> for x in [3, 2, 1, 0]:
... print (x, 1.0/x)
...
(3, 0.1)
(2, 0.5)
(1, 1.0)
Traceback (most recent call last):
  ...
ZeroDivisionError: float division


Attached is a simple test script which runs doctest.testmod(). Both tests
should pass, with no output printing. However, it does this:

$ python doctest_error.py
**
File "doctest_error.py", line 14, in __main__
Failed example:
for x in [3, 2, 1, 0]:
print (x, 1.0/x)
Exception raised:
Traceback (most recent call last):
  File "/usr/lib/python2.5/doctest.py", line 1212, in __run
compileflags, 1) in test.globs
  File "", line 2, in 
print (x, 1.0/x)
ZeroDivisionError: float division
**
1 items had failures:
   1 of   2 in __main__
***Test Failed*** 1 failures.



I've tested this in Python 2.4, 2.5 and 2.6 and get the same result for all
three.

Have I missed something, or should I report this as a bug?



-- 
Steven

"""


>>> for x in [3, 2, 1]:
... print (x, 1.0/x)
...
(3, 0.1)
(2, 0.5)
(1, 1.0)


This fails as a doctest:

>>> for x in [3, 2, 1, 0]:
... print (x, 1.0/x)
...
(3, 0.1)
(2, 0.5)
(1, 1.0)
Traceback (most recent call last):
  ...
ZeroDivisionError: float division

"""



if __name__ == '__main__':
import doctest
doctest.testmod()


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


Re: Exception inside loop wrongly failing doctest

2009-06-12 Thread Lie Ryan
Steven D'Aprano wrote:
> One of my doctests is failing, and I suspect a bug.
> 
> The test involves matching an exception in a for-loop. Here are two
> simplified versions of the test, both should pass but only the first does.
> 

tell me, what's the result of 1/0?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception inside loop wrongly failing doctest

2009-06-12 Thread Lie Ryan
Lie Ryan wrote:
> Steven D'Aprano wrote:
>> One of my doctests is failing, and I suspect a bug.
>>
>> The test involves matching an exception in a for-loop. Here are two
>> simplified versions of the test, both should pass but only the first does.
>>
> 
> tell me, what's the result of 1/0?

Whooopss.. replied too fast...

This seems to work:

>>> for i in [3, 2, 1, 0]:
... print (i, 1.0/i)
...
Traceback (most recent call last):
...
ZeroDivisionError: float division

it seems that if the expected result is a traceback, the doc result must
starts with the traceback keyword:

"""
The expected output for an exception must *start* with a traceback
header, which may be either of the following two lines, indented the
same as the first line of the example:

Traceback (most recent call last):
Traceback (innermost last):
"""

(emphasizes added)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: install older Python version parallel

2009-06-12 Thread Simon212

> > Hi everybody,
> >
> > The situation:
> > I wrote a GUI, based on Python, TkInter and Pmw.
> > It runs perfectly fine with Python 2.4 (providing, TkInter and Pmw are  
> > installed). But it crashes with Python 2.6. I tried this on MacOSX11.4  
> > and various Linux Distributions.
> > Crashes occurs when I activate a Pmw.Diaog (I guess this is due to a bug
>  
> > in the installed blt package), also when I use setitems on  
> > Pmw.OptionMenu (I guess this is due to another package, associated with 
> > tcl/tk).
> 
> You might get more helpful responses if you say more than just "it  
> crashes".
> What's the traceback?
>

Thanks for the suggestion.

1.
Here is what it says when I try to use setitems on a Pmw.OptionMenu to refresh 
its contents:

com.read_config_file ./.mWIN/profiles/last.profile
Traceback (most recent call last):
  File "./startMW.py", line 1323, in 
frontEnd = FrontEnd(root)
  File "./startMW.py", line 854, in __init__
self.loadProfile()
  File "./startMW.py", line 1216, in loadProfile
self.profileList.setitems(self.com.profile_names)
  File 
"/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/Pmw/Pmw_1_3/lib/PmwOptionMenu.py",
 line 67, in setitems
self._menu.delete(0, 'end')
  File 
"/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 2675, in delete
self.deletecommand(c)
  File 
"/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 358, in deletecommand
self.tk.deletecommand(name)
_tkinter.TclError: can't delete Tcl command

2.
In case of the activation of a Pmw.Diaog it just gives me a segmentation vault.


-- 
GMX FreeDSL Komplettanschluss mit DSL 6.000 Flatrate und Telefonanschluss
für nur 17,95 Euro/mtl.!* http://portal.gmx.net/de/go/dsl02
-- 
http://mail.python.org/mailman/listinfo/python-list


matplotlib installation

2009-06-12 Thread Virgil Stokes
Any suggestions on installing matplotlib for Python 2.6.2 on a Windows 
Vista platform?


--V

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


Re: Exception inside loop wrongly failing doctest

2009-06-12 Thread Steven D'Aprano
Lie Ryan wrote:

> Lie Ryan wrote:
>> Steven D'Aprano wrote:
>>> One of my doctests is failing, and I suspect a bug.
...
> it seems that if the expected result is a traceback, the doc result must
> starts with the traceback keyword:


Ah, that would be it. Not a bug then, a limitation of the doctest module. 

Thanks,



-- 
Steven

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


Re: command line of a process.exe on another host

2009-06-12 Thread Giampaolo Rodola'
On 12 Giu, 00:18, "Harry"  wrote:
> HI ,
> I have number of process run on different windows servers which run's with
> different command line parameters. for example "process.exe -input
> statusurl:http://sss.com";., These parameters can vary from host to host.
> using Psexec I know the PID and process name which are running on these
> machines, but how I can read the command line parameters of these process.
> Is there a way to read these command line of the proess via python pls?
>
> any feedback appreciated..
>
> thanks
> Hari

You can easily do this with psutil [1]:


>>> import psutil, os
>>> p = psutil.Process(os.getpid())
>>> p.cmdline
['/usr/bin/python2.4']
>>>


Since psutil uses the native Windows calls to retrieve such kind of
info it's a lot faster than using any WMI-based solution.


[1] http://code.google.com/p/psutil/



--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: command line of a process.exe on another host

2009-06-12 Thread Tim Golden

Giampaolo Rodola' wrote:

On 12 Giu, 00:18, "Harry"  wrote:

HI ,
I have number of process run on different windows servers which run's with
different command line parameters. 




You can easily do this with psutil [1]:



Since psutil uses the native Windows calls to retrieve such kind of
info it's a lot faster than using any WMI-based solution.



Looks great (and it's certainly fast). Can you pick up processes
on a different server? The docs don't seem to say so. Did I miss
something? (It's not clear that the OP actually wants that altho'
I read it that way).

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


Re: matplotlib installation

2009-06-12 Thread Alan G Isaac
On 6/12/2009 5:55 AM Virgil Stokes apparently wrote:
> Any suggestions on installing matplotlib for Python 2.6.2 on a Windows 
> Vista platform?


Maintainers for some packages have run into a wall
compiling for 2.6.  Matplotlib is one of these:
http://www.nabble.com/binary-installers-for-python2.6--libpng-segfault%2C-MSVCR90.DLL-and-%09mingw-td23971661.html

Another package I care about is SimpleParse, which also
found compiling for 2.6 to be impossible.  I do not know
if this was the same problem or not, but it means that
SimpleParse is *still* not available as an installer for 2.6.

I assume this is of great concern to the Python community,
but I do not know where the discussion is taking place.

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


trying to understand dictionaries

2009-06-12 Thread [email protected]
Hi.
As the subject says, I'm a newbie trying to learn python and now
dictionaries. I can create a dict, understand it and use it for simple
tasks. But the thing is that I don't really get the point on how to
use these in real life programing.

For example I tryed to create a very simple phonebook

code:

d = {'fname': [], 'ename': []}
name1 = 'ricky'
name2 = 'martin'
d['fname'].append(name1)
d['ename'].append(name2)

name1 = 'britney'
name2 = 'spears'
d['fname'].append(name1)
d['ename'].append(name2)


This gives me:
{'ename': ['martin', 'spears'], 'fname': ['ricky', 'britney']}

I wonder if this is a correct usage and thinking about dictioaries in
python.
Everything in my example is based on a serval lists in a dictionary,
and person 1 is == ename[0] & fname[0]
and person 2 is == ename[1] & fname[1], it's based on position and
indexing.

Is this correct if no, how would you do it?
if yes, how can I print the result out in a nice way? I need a for-
loop that prints:
all [0] in all lists
all [0] in all lists and so on.


thanks
/jonas

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


CAD file format specifications?

2009-06-12 Thread Anthra Norell

Hi,
  Anyone working with CAD who knows about numeric data entry? I have 3d 
coordinates of a construction site on a slope (borders, setbacks and 
isometric elevation lines). Someone made me aware of Google's Sketch Up. 
It looks very attractive for the purpose of architectural planning, 
especially suited to create visual impressions. Doodling seems easy. But 
I have to start with modeling the terrain and the envelope and the only 
way to do that seems to be in one of several CAD file formats (skp, dwg, 
dxf, 3ds, ddf and dem). So I need to cast my numbers into one of these 
formats. Any suggestions?


Thanks

Frederic

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


Re: Need help in Python regular expression

2009-06-12 Thread Jean-Michel Pichavant

To the OP,

I suggest if you haven't yet Kodos, to get it here 
http://kodos.sourceforge.net/.

It's a python regexp debugger, a lifetime saver.

Jean-Michel

John S wrote:

On Jun 11, 10:30 pm, meryl  wrote:
  

Hi,

I have this regular expression
blockRE = re.compile(".*RenderBlock {\w+}")

it works if my source is "RenderBlock {CENTER}".

But I want it to work with
1. RenderTable {TABLE}

So i change the regexp to re.compile(".*Render[Block|Table] {\w+}"),
but that breaks everything

2. RenderBlock (CENTER)

So I change the regexp to re.compile(".*RenderBlock {|\(\w+}|\)"),
that also breaks everything

Can you please tell me how to change my reg exp so that I can support
all 3 cases:
RenderTable {TABLE}
RenderBlock (CENTER)
RenderBlock {CENTER}

Thank you.



Short answer:

r = re.compile(r"Render(?:Block|Table)\s+[({](?:TABLE|CENTER)[})]")

s = """
blah blah blah
blah blah blah RenderBlock {CENTER} blah blah RenderBlock {CENTER}
blah blah blah RenderTable {TABLE} blah blah RenderBlock (CENTER)
blah blah blah
"""

print r.findall(s)



output:
['RenderBlock {CENTER}', 'RenderBlock {CENTER}', 'RenderTable
{TABLE}', 'RenderBlock (CENTER)']



Note that [] only encloses characters, not strings; [foo|bar] matches
'f','o','|','b','a', or 'r', not "foo" or "bar".
Use (foo|bar) to match "foo" or "bar"; (?xxx) matches xxx without
making a backreference (i.e., without capturing text).

HTH

-- John Strickler
  


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


Re: trying to understand dictionaries

2009-06-12 Thread Jean-Michel Pichavant
Basically, dictionaries are a bunch of couples of key and  value where 
key is an immutable object. In fact you'll find a more accurate 
definition in any python book or online tutorial.
The thing is that keys are usually used as an easy and quick way the 
search and index items.
You can see dict as a list that can use strings instead of integers to 
index its values.


phonebook = {
   'ricky' : ('ricky', 'martin', 'male'),
   'britney' : ('britney', 'spears', 'female'),
   'myBestBuddy' : ('barack', 'obama', 'male'),
   42 : ('bob', 'bib', 'male'), # you can use 42 as index, like strings 
integers are not mutable
   True: ('', '', ''), # meaningless example just to show that any 
immutable object will fit as index

}

fname, ename, gender = phonebook['myBestBuddy']
fname, ename, gender = phonebook[42]

Keys are unique among the dictionary.

Jean-Michel

[email protected] wrote:

Hi.
As the subject says, I'm a newbie trying to learn python and now
dictionaries. I can create a dict, understand it and use it for simple
tasks. But the thing is that I don't really get the point on how to
use these in real life programing.

For example I tryed to create a very simple phonebook

code:

d = {'fname': [], 'ename': []}
name1 = 'ricky'
name2 = 'martin'
d['fname'].append(name1)
d['ename'].append(name2)

name1 = 'britney'
name2 = 'spears'
d['fname'].append(name1)
d['ename'].append(name2)


This gives me:
{'ename': ['martin', 'spears'], 'fname': ['ricky', 'britney']}

I wonder if this is a correct usage and thinking about dictioaries in
python.
Everything in my example is based on a serval lists in a dictionary,
and person 1 is == ename[0] & fname[0]
and person 2 is == ename[1] & fname[1], it's based on position and
indexing.

Is this correct if no, how would you do it?
if yes, how can I print the result out in a nice way? I need a for-
loop that prints:
all [0] in all lists
all [0] in all lists and so on.


thanks
/jonas

  


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


Re: trying to understand dictionaries

2009-06-12 Thread Alan G Isaac
On 6/12/2009 7:51 AM [email protected] apparently wrote:
> d = {'fname': [], 'ename': []}
> name1 = 'ricky'
> name2 = 'martin'
> d['fname'].append(name1)
> d['ename'].append(name2)
> 
> name1 = 'britney'
> name2 = 'spears'
> d['fname'].append(name1)
> d['ename'].append(name2)
> 
> 
> This gives me:
> {'ename': ['martin', 'spears'], 'fname': ['ricky', 'britney']}


Trying to stick close to your example,
reverse the use of lists and dicts.

worst_musicians = list()
entry = dict(fname='ricky',lname='martin')
worst_musicians.append(entry)
entry = dict(fname='britney',lname='spears')
worst_musicians.append(entry)

for musician in worst_musicians:
print "%(fname)s %(lname)s"%musician

hth,
Alan Isaac
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EOF problem with ENTER

2009-06-12 Thread Jean-Michel Pichavant

Prasoon wrote:

I modified my code to

#Euler Totient Function
import sys
from math import sqrt
def etf(n):
   i,res =2,n
   while(i*i<=n):
  if(n%i==0):
res-=res/i
  while(n%i==0):
n/=i
  i+=1
   if(n>1):
res-=res/n
   return res

def main():
  while True:
   t=raw_input()
   if t!="":break
  t=int(t)
  while(t):
while True:
 x=raw_input()
 if x!="":break
x=int(x)
print str(etf(x))
t-=1

if __name__ == "__main__":
  main()

Now it is working fine thanks!!!
  
Hello Prasoon, there's  still a major issue with your code, check out 
http://tottinge.blogsome.com/meaningfulnames/
If your code is a private script targeted at your personal use, well I 
guess you can just ignore my comment. But I'm still impressed by how 
some of the python-list users have dived into your code with such ease.


Regards,

Jean-Michel


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


Re: TypeError: int argument required

2009-06-12 Thread mblume
Am Thu, 11 Jun 2009 20:56:24 -0700 schrieb lucius:

> I am trying to
> print some values to a file (using c's printf like method). TypeError:
> int argument required
> # this works, i see value on screen
>  print  w, h, absX, absY
> 
Are you sure that w or h are not returned as strings?
Hint: try this in an interpreter:
w="100"
print "%d" % (w)

> 
> # this fails, I get "TypeError: int argument required"
>  print >> fo, " style=\"fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-
> opacity:0.9\"/> " % (absX, absY, w, h)
> 

You could simplify such as an expression by writing:
print 'x="%f"' % (x)

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


Re: trying to understand dictionaries

2009-06-12 Thread Albert Hopkins
On Fri, 2009-06-12 at 04:51 -0700, [email protected] wrote:
> Hi.
> As the subject says, I'm a newbie trying to learn python and now
> dictionaries. I can create a dict, understand it and use it for simple
> tasks. But the thing is that I don't really get the point on how to
> use these in real life programing.
> 
> For example I tryed to create a very simple phonebook
> 
> code:
> 
> d = {'fname': [], 'ename': []}
> name1 = 'ricky'
> name2 = 'martin'
> d['fname'].append(name1)
> d['ename'].append(name2)
> 
> name1 = 'britney'
> name2 = 'spears'
> d['fname'].append(name1)
> d['ename'].append(name2)
> 
> 
> This gives me:
> {'ename': ['martin', 'spears'], 'fname': ['ricky', 'britney']}
> 
> I wonder if this is a correct usage and thinking about dictioaries in
> python.
> Everything in my example is based on a serval lists in a dictionary,
> and person 1 is == ename[0] & fname[0]
> and person 2 is == ename[1] & fname[1], it's based on position and
> indexing.
> 
> Is this correct if no, how would you do it?
> if yes, how can I print the result out in a nice way? I need a for-
> loop that prints:
> all [0] in all lists
> all [0] in all lists and so on.

That's probably not the data model I'd use for a phone book.  The
following isn't either, but is better:

d = dict()
d[('martin', 'ricky')] = '555-1212'
d[('spears', 'britney')] = '555-1213'

for last, first in d:
phone_number = d[(last, first)]
print ...



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


Re: matplotlib installation

2009-06-12 Thread Jean-Paul Calderone

On Fri, 12 Jun 2009 11:33:36 GMT, Alan G Isaac  wrote:

On 6/12/2009 5:55 AM Virgil Stokes apparently wrote:

Any suggestions on installing matplotlib for Python 2.6.2 on a Windows
Vista platform?



Maintainers for some packages have run into a wall
compiling for 2.6.  Matplotlib is one of these:
http://www.nabble.com/binary-installers-for-python2.6--libpng-segfault%2C-MSVCR90.DLL-and-%09mingw-td23971661.html

Another package I care about is SimpleParse, which also
found compiling for 2.6 to be impossible.  I do not know
if this was the same problem or not, but it means that
SimpleParse is *still* not available as an installer for 2.6.

I assume this is of great concern to the Python community,
but I do not know where the discussion is taking place.


Some discussion has occurred in the issue tracker:

 http://bugs.python.org/issue3308
 http://bugs.python.org/issue6007

In general, the people responsible for how CPython builds on Windows
don't seem to consider this an issue.

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


Re: RE replace problem too

2009-06-12 Thread Lie Ryan
oyster wrote:
> in my case, I want to replace all the function name with '', that is
> sin(1)  ->  (1)
> sin(pi*(2+4))  -> (pi*(2+4))
> how can I use RE in this situation? thanx

this works if there is no implicit multiplication:

re.sub('\w+\(', '(', 'sin(pi*(2+4))')

this one might be more robust:
re.sub('[a-zA-Z]\w*\s*\(', '(', 'sin(pi*cos(2+4))')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: command line of a process.exe on another host

2009-06-12 Thread Giampaolo Rodola'
On 12 Giu, 13:02, Tim Golden  wrote:
> Giampaolo Rodola' wrote:
> > On 12 Giu, 00:18, "Harry"  wrote:
> >> HI ,
> >> I have number of process run on different windows servers which run's with
> >> different command line parameters.
> > You can easily do this with psutil [1]:
> > Since psutil uses the native Windows calls to retrieve such kind of
> > info it's a lot faster than using any WMI-based solution.
>
> Looks great (and it's certainly fast). Can you pick up processes
> on a different server? The docs don't seem to say so. Did I miss
> something? (It's not clear that the OP actually wants that altho'
> I read it that way).
>
> TJG


Sorry, I didn't notice the OP meant to retrieve information from a
remote machine.
And no, psutil can't do anything like that.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: command line of a process.exe on another host

2009-06-12 Thread Tim Wintle
On Thu, 2009-06-11 at 23:18 +0100, Harry wrote:
> HI ,
> I have number of process run on different windows servers which run's with 
> different command line parameters. for example "process.exe -input 
> statusurl: http://sss.com "., These parameters can vary from host to host. 
> using Psexec I know the PID and process name which are running on these 
> machines, but how I can read the command line parameters of these process. 
> Is there a way to read these command line of the proess via python pls?

I'm not sure how well this will work, but it might be worth looking at
fabric - which lets you run through ssh onto lots of different machines
(so I assume you'll need openssh on those machines)

http://docs.fabfile.org/

Haven't used it myself, but I keep meaning to.


> 
> any feedback appreciated..
> 
> thanks
> Hari
> 

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


install Python-2.4.4 from source (parallel to existing Python-2.6)

2009-06-12 Thread Simon

edexter wrote:

simon wrote:

Hi everybody,

The situation:
I wrote a GUI, based on Python, TkInter and Pmw.
It runs perfectly fine with Python 2.4 (providing, TkInter and Pmw are
installed). But it crashes with Python 2.6. I tried this on MacOSX11.4
and various Linux Distributions.
Crashes occurs when I activate a Pmw.Diaog (I guess this is due to a bug
in the installed blt package), also when I use setitems on
Pmw.OptionMenu (I guess this is due to another package, associated with
tcl/tk).

The target:
I have to get my GUI work under openSUSE 11.1 (x86_64).

My plan:
On my openSUSE 11.1 (x86_64), Python 2.6 is installed by default.
I would like to know, how to install Python 2.4 along with TkInter and
Pmw (and packages that are required by them), parallel to the existing
Python 2.6. So that I do not break other software that depends on Python
2.6.

If you can think of another plan, I would be also glad to discuss it.

Cheers,
Simon


I suspect you want to install python 2.4 and then reinstall 2.6  I did
that in windows and I don't understand why it wouldn't work in linux


I'm afraid, installation is quit different under UNIX based systems and 
Windows.


I installed Python-2.4.4.tar.bz2 from python.org, using gcc-4.3 (within 
openSUSE 11.1 x86_64) via 'make altinstall'.


First, I tried to configure with the following flags: 
--prefix=/opt/python-24 --enable-framework --with-pydebug
This provoked an error during compilation via make (sorry, the list was 
so long, but I will post it, if it helps).


Second, configured again without any flags. The installation by 'make 
altinstall' to /usr/local was a success. Python2.6 seams unaffected, 
too. So, I got my parallel installation.


However, I cannot import modules like Tkinter or readline within python2.4.

For example, Tkinter.py is located in /usr/local/lib/python2.4/lib-tk

sys.path says: ['', '/usr/local/lib/python24.zip', 
'/usr/local/lib/python2.4', '/usr/local/lib/python2.4/plat-linux2', 
'/usr/local/lib/python2.4/lib-tk', 
'/usr/local/lib/python2.4/lib-dynload', 
'/usr/local/lib/python2.4/site-packages']


sys.prefix and sys.exec_prefix say: '/usr/local'

my bash's PATH variable says: 
/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/opt/kde3/bin:/usr/lib64/jvm/jre/bin:/usr/lib/mit/bin:/usr/lib/mit/sbin


Which configuration step did I miss after my Python2.4 installation? 
What did I do wrong?


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


Re: install older Python version parallel

2009-06-12 Thread Tim Wintle
On Fri, 2009-06-12 at 00:30 -0700, edexter wrote:
> I suspect you want to install python 2.4 and then reinstall 2.6  I did
> that in windows and I don't understand why it wouldn't work in linux

It won't normally work on linux these days because most distributions of
gnu/linux need python to run the GUI.

Put another way it means if something doesn't work how you want it, it's
just some python somewhere to change :-)


(Trust me, you don't want to remove the system version of python on most
linux distributions or on macs)


Tim

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


Re: matplotlib installation

2009-06-12 Thread David Cournapeau
On Fri, Jun 12, 2009 at 9:50 PM, Jean-Paul Calderone wrote:
> On Fri, 12 Jun 2009 11:33:36 GMT, Alan G Isaac  wrote:
>>
>> On 6/12/2009 5:55 AM Virgil Stokes apparently wrote:
>>>
>>> Any suggestions on installing matplotlib for Python 2.6.2 on a Windows
>>> Vista platform?
>>
>>
>> Maintainers for some packages have run into a wall
>> compiling for 2.6.  Matplotlib is one of these:
>>
>> http://www.nabble.com/binary-installers-for-python2.6--libpng-segfault%2C-MSVCR90.DLL-and-%09mingw-td23971661.html
>>
>> Another package I care about is SimpleParse, which also
>> found compiling for 2.6 to be impossible.  I do not know
>> if this was the same problem or not, but it means that
>> SimpleParse is *still* not available as an installer for 2.6.
>>
>> I assume this is of great concern to the Python community,
>> but I do not know where the discussion is taking place.
>
> Some discussion has occurred in the issue tracker:
>
>  http://bugs.python.org/issue3308
>  http://bugs.python.org/issue6007
>
> In general, the people responsible for how CPython builds on Windows
> don't seem to consider this an issue.

We got the same problem with numpy.  The good news is it is solvable
(at least partially).

http://projects.scipy.org/numpy/browser/trunk/numpy/random/mtrand/randomkit.c

Basically, there are some functions which are erroneously "declared"
in the .lib, but they don't actually exist in the MS C runtime. We
detect when the .C code is built under mingw, and add an hack to
redirect the function to the "real" function, _ftime64 (see around
line 75).

cheers,

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


ANNOUNCE: libmsgque 3.3

2009-06-12 Thread Andreas Otto

ANNOUNCE a majorfeature improvement of libmsgque ...


What is LibMsgque
=

LibMsgque is an OS independent, Programming Language independent and
Hardware independent solution to link applications together to act like a
single application. Or with other words, LibMsgque is an Application-Server
toolkit.


Highlights of the current Release:
=

This release introduce the C# port and the long waiting "managed" code
interface to "libmsgque". This interface allow writing language-bindings
to libmsgque without using an addition C library as "translator" between
the native language and "libmsgque". The skip of this "translation"
library introduce a new performance leader using C# together with
the "mono" tools and outperform JAVA, TCL, PYTHON.

On windows the "mono" tool and the "microsoft" native C# is supported.

The performance-comparison between "c", "tcl", "python", "C#" and "java" 
was updated:

  -> results: http://libmsgque.sourceforge.net/performance.htm


The Web-Site was updated:
=

   -> http://libmsgque.sourceforge.net

  For a fast introduction use the following URL:

   -> http://libmsgque.sourceforge.net/features.htm



mfg

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


Question about None

2009-06-12 Thread Paul LaFollette
Kind people,

Using Python 3.0 on a Gatesware machine (XP).
I am building a class in which I want to constrain the types that can
be stored in various instance variables.  For instance, I want to be
certain that self.loc contains an int.  This is straightforward (as
long as I maintain the discipline of changing loc through a method
rather than just twiddling it directly.

  def setLoc(lo):
assert isinstance(lo, int), "loc must be an int"
self.loc = lo

does the trick nicely.

However, I also want to constrain self.next to be either an instance
of class Node, or None.  I would think that the following should work
but it doesn't.

  def setNext(nxt):
assert isinstance(nxt, (Node, NoneType)), "next must be a Node"
self.next = nxt

since type(Node) responds with  but the assertion
above gives "name 'NoneType' is not defined" suggesting that NoneType
is some sort of quasi-class.

  def setNext(nxt):
assert nxt==None or isinstance(nxt, Node), "next must be a Node"
self.next = nxt

works ok, but it's uglier than it ought to be.

So, I have three questions.

1) Why doesn't isinstance(nxt, (Node, NoneType)) work?
2) is their a less ugly alternative that what I am using?
3) (this is purely philosophical but I am curious)  Would it not be
more intuitive if
isinstance(None, ) returned true?

Thank you for your kind attention.
Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about None

2009-06-12 Thread Javier Collado
Hello,

This should work for you:

In [1]: import types

In [2]: isinstance(None, types.NoneType)
Out[2]: True


Best regards,
Javier

2009/6/12 Paul LaFollette :
> Kind people,
>
> Using Python 3.0 on a Gatesware machine (XP).
> I am building a class in which I want to constrain the types that can
> be stored in various instance variables.  For instance, I want to be
> certain that self.loc contains an int.  This is straightforward (as
> long as I maintain the discipline of changing loc through a method
> rather than just twiddling it directly.
>
>  def setLoc(lo):
>    assert isinstance(lo, int), "loc must be an int"
>    self.loc = lo
>
> does the trick nicely.
>
> However, I also want to constrain self.next to be either an instance
> of class Node, or None.  I would think that the following should work
> but it doesn't.
>
>  def setNext(nxt):
>    assert isinstance(nxt, (Node, NoneType)), "next must be a Node"
>    self.next = nxt
>
> since type(Node) responds with  but the assertion
> above gives "name 'NoneType' is not defined" suggesting that NoneType
> is some sort of quasi-class.
>
>  def setNext(nxt):
>    assert nxt==None or isinstance(nxt, Node), "next must be a Node"
>    self.next = nxt
>
> works ok, but it's uglier than it ought to be.
>
> So, I have three questions.
>
> 1) Why doesn't isinstance(nxt, (Node, NoneType)) work?
> 2) is their a less ugly alternative that what I am using?
> 3) (this is purely philosophical but I am curious)  Would it not be
> more intuitive if
> isinstance(None, ) returned true?
>
> Thank you for your kind attention.
> Paul
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: install Python-2.4.4 from source (parallel to existing Python-2.6)

2009-06-12 Thread Simon

Simon wrote:

edexter wrote:

simon wrote:

Hi everybody,

The situation:
I wrote a GUI, based on Python, TkInter and Pmw.
It runs perfectly fine with Python 2.4 (providing, TkInter and Pmw are
installed). But it crashes with Python 2.6. I tried this on MacOSX11.4
and various Linux Distributions.
Crashes occurs when I activate a Pmw.Diaog (I guess this is due to a bug
in the installed blt package), also when I use setitems on
Pmw.OptionMenu (I guess this is due to another package, associated with
tcl/tk).

The target:
I have to get my GUI work under openSUSE 11.1 (x86_64).

My plan:
On my openSUSE 11.1 (x86_64), Python 2.6 is installed by default.
I would like to know, how to install Python 2.4 along with TkInter and
Pmw (and packages that are required by them), parallel to the existing
Python 2.6. So that I do not break other software that depends on Python
2.6.

If you can think of another plan, I would be also glad to discuss it.

Cheers,
Simon


I suspect you want to install python 2.4 and then reinstall 2.6  I did
that in windows and I don't understand why it wouldn't work in linux


I'm afraid, installation is quit different under UNIX based systems and 
Windows.


I installed Python-2.4.4.tar.bz2 from python.org, using gcc-4.3 (within 
openSUSE 11.1 x86_64) via 'make altinstall'.


First, I tried to configure with the following flags: 
--prefix=/opt/python-24 --enable-framework --with-pydebug
This provoked an error during compilation via make (sorry, the list was 
so long, but I will post it, if it helps).


Second, configured again without any flags. The installation by 'make 
altinstall' to /usr/local was a success. Python2.6 seams unaffected, 
too. So, I got my parallel installation.


However, I cannot import modules like Tkinter or readline within python2.4.

For example, Tkinter.py is located in /usr/local/lib/python2.4/lib-tk

sys.path says: ['', '/usr/local/lib/python24.zip', 
'/usr/local/lib/python2.4', '/usr/local/lib/python2.4/plat-linux2', 
'/usr/local/lib/python2.4/lib-tk', 
'/usr/local/lib/python2.4/lib-dynload', 
'/usr/local/lib/python2.4/site-packages']


sys.prefix and sys.exec_prefix say: '/usr/local'

my bash's PATH variable says: 
/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/opt/kde3/bin:/usr/lib64/jvm/jre/bin:/usr/lib/mit/bin:/usr/lib/mit/sbin 



Which configuration step did I miss after my Python2.4 installation? 
What did I do wrong?


Cheers,
Simon


OK, I found an 'Ansatzpunkt' where I can start from:
_tkinter.so is missing in /usr/local/lib/python2.4/lib-dynload
so I guess my python is not configured for using Tcl?

I found the following from 
http://mail.python.org/pipermail/python-list/2001-December/117984.html


Install Tcl, Tk and Python as peers of each other ...
1. run configure in Python
2. make and make install Tcl  (unless you're using binary dist)make and
3. make install Tk   (unless you're using binary dist)
4. edit Setup
5. make and make install Python

I guess, I will try that next. Maybe somebody knows a more detailed 
instruction. My problems:


a)
I don't know if I have to set special flags to make the three packages 
aware of each other during 'configure', 'make', and 'make altinstall'.


b)
Also, I don't know, which setup do I have to edit during step 4.

c)
Which Tcl and Tk versions do I need, don't I need tcl-devel in addition?

Sorry for so many questions, but this stuff is new for me,
Simon
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about None

2009-06-12 Thread Christian Heimes
Paul LaFollette schrieb:
> Kind people,
> 
> Using Python 3.0 on a Gatesware machine (XP).
> I am building a class in which I want to constrain the types that can
> be stored in various instance variables.  For instance, I want to be
> certain that self.loc contains an int.  This is straightforward (as
> long as I maintain the discipline of changing loc through a method
> rather than just twiddling it directly.
> 
>   def setLoc(lo):
> assert isinstance(lo, int), "loc must be an int"
> self.loc = lo
> 
> does the trick nicely.
> 
> However, I also want to constrain self.next to be either an instance
> of class Node, or None.  I would think that the following should work
> but it doesn't.
> 
>   def setNext(nxt):
> assert isinstance(nxt, (Node, NoneType)), "next must be a Node"
> self.next = nxt

How about the canonical way to check if an object is None?

assert Node is None

None is a singleton. Python guarantees that there is exactly one None
object and on this account only one instance of NoneType. In Python 3.x
you can't even overwrite the global variable None. User code shouldn't
use NoneType at all.

 >>> type(None)

>>> type(None)()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot create 'NoneType' instances
>>> None = 1
  File "", line 1
SyntaxError: assignment to keyword

The singletons True and False have a similar behavior. It's not possible
to overwrite them as well. The bool type always returns either the
singleton True or the singleton False.

>>> True = False
  File "", line 1
SyntaxError: assignment to keyword
>>> type(True)

>>> type(True) is bool
True
>>> bool(42)
True

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


Re: matplotlib installation

2009-06-12 Thread Jean-Paul Calderone

On Fri, 12 Jun 2009 22:54:14 +0900, David Cournapeau  wrote:

On Fri, Jun 12, 2009 at 9:50 PM, Jean-Paul Calderone wrote:

On Fri, 12 Jun 2009 11:33:36 GMT, Alan G Isaac  wrote:


On 6/12/2009 5:55 AM Virgil Stokes apparently wrote:


Any suggestions on installing matplotlib for Python 2.6.2 on a Windows
Vista platform?



Maintainers for some packages have run into a wall
compiling for 2.6.  Matplotlib is one of these:

http://www.nabble.com/binary-installers-for-python2.6--libpng-segfault%2C-MSVCR90.DLL-and-%09mingw-td23971661.html

Another package I care about is SimpleParse, which also
found compiling for 2.6 to be impossible.  I do not know
if this was the same problem or not, but it means that
SimpleParse is *still* not available as an installer for 2.6.

I assume this is of great concern to the Python community,
but I do not know where the discussion is taking place.


Some discussion has occurred in the issue tracker:

 http://bugs.python.org/issue3308
 http://bugs.python.org/issue6007

In general, the people responsible for how CPython builds on Windows
don't seem to consider this an issue.


We got the same problem with numpy.  The good news is it is solvable
(at least partially).

http://projects.scipy.org/numpy/browser/trunk/numpy/random/mtrand/randomkit.c

Basically, there are some functions which are erroneously "declared"
in the .lib, but they don't actually exist in the MS C runtime. We
detect when the .C code is built under mingw, and add an hack to
redirect the function to the "real" function, _ftime64 (see around
line 75).


Thanks for pointing out one possible workaround.  I don't think this is
always applicable, though.  For example, pyOpenSSL can't be built for
Python 2.6 because OpenSSL uses localtime, another function with a similar
problem as the one with ftime.  To redirect its usage, OpenSSL itself needs
to be changed and then distributed along with pyOpenSSL.

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


Re: install Python-2.4.4 from source (parallel to existing Python-2.6)

2009-06-12 Thread Christian Heimes
Simon wrote:
> I installed Python-2.4.4.tar.bz2 from python.org, using gcc-4.3 (within
> openSUSE 11.1 x86_64) via 'make altinstall'.
> 
> First, I tried to configure with the following flags:
> --prefix=/opt/python-24 --enable-framework --with-pydebug
> This provoked an error during compilation via make (sorry, the list was
> so long, but I will post it, if it helps).

--enable-framework is for Mac OS X only.

> Second, configured again without any flags. The installation by 'make
> altinstall' to /usr/local was a success. Python2.6 seams unaffected,
> too. So, I got my parallel installation.

You have chosen the correct and canonical way to install a parallel
installation of Python.

> However, I cannot import modules like Tkinter or readline within python2.4.

You must install the development library of tk, readline, zlib and
libbz2 prior to configure && make.

Try this on your box:

zypper install gcc make autoconf automake libtool zlib-devel
readline-devel tk-devel tcl-devel sqlite2-devel libbz2-devel
libopenssl-devel

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


Re: Question about None

2009-06-12 Thread Bruno Desthuilliers

Paul LaFollette a écrit :

Kind people,

Using Python 3.0 on a Gatesware machine (XP).
I am building a class in which I want to constrain the types that can
be stored in various instance variables.


This somehow goes against the whole philosophy of dynamic typing Python 
is based upon... But there are indeed cases where it makes sense and I 
assume you know what you're doing !-)



 For instance, I want to be
certain that self.loc contains an int.  This is straightforward (as
long as I maintain the discipline of changing loc through a method
rather than just twiddling it directly.

  def setLoc(lo):
assert isinstance(lo, int), "loc must be an int"
self.loc = lo

does the trick nicely.


Did you considered using properties (or custom descriptors) instead ?

(snip - others already answered)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about None

2009-06-12 Thread Jeff McNeil
On Jun 12, 10:05 am, Paul LaFollette 
wrote:
> Kind people,
>
> Using Python 3.0 on a Gatesware machine (XP).
> I am building a class in which I want to constrain the types that can
> be stored in various instance variables.  For instance, I want to be
> certain that self.loc contains an int.  This is straightforward (as
> long as I maintain the discipline of changing loc through a method
> rather than just twiddling it directly.
>
>   def setLoc(lo):
>     assert isinstance(lo, int), "loc must be an int"
>     self.loc = lo
>
> does the trick nicely.
>
> However, I also want to constrain self.next to be either an instance
> of class Node, or None.  I would think that the following should work
> but it doesn't.
>
>   def setNext(nxt):
>     assert isinstance(nxt, (Node, NoneType)), "next must be a Node"
>     self.next = nxt
>
> since type(Node) responds with  but the assertion
> above gives "name 'NoneType' is not defined" suggesting that NoneType
> is some sort of quasi-class.
>
>   def setNext(nxt):
>     assert nxt==None or isinstance(nxt, Node), "next must be a Node"
>     self.next = nxt
>
> works ok, but it's uglier than it ought to be.
>
> So, I have three questions.
>
> 1) Why doesn't isinstance(nxt, (Node, NoneType)) work?
> 2) is their a less ugly alternative that what I am using?
> 3) (this is purely philosophical but I am curious)  Would it not be
> more intuitive if
> isinstance(None, ) returned true?
>
> Thank you for your kind attention.
> Paul

1. The problem is described clearly by that Exception. The 'NoneType'
name isn't bound to any objects at that current scope.  I know that
with 2.6, you can import 'types.NoneType' but I don't believe the 3.0
types module includes NoneType.  Someone else will have to clarify
that as I don't have 3.0 installed.

2. A less ugly alternative? You could use the accepted method of
testing against None:

if var is None:
do_stuff()

The use of the 'is' operator checks whether objects are exactly the
same (id(var) == id(None)) as opposed to 'isinstance' or '==.'

You might also try defining descriptors in order to make your type
checks slightly more transparent. That might be confusing to other
users of your class, though. Not many people expect a TypeError from
an attribute assignment.

3. None is an instance of NoneType. Why should isinstance return True
when it's tested against other types?

HTH,

Jeff
mcjeff.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: install Python-2.4.4 from source (parallel to existing Python-2.6)

2009-06-12 Thread Benjamin Kaplan
On Fri, Jun 12, 2009 at 9:31 AM, Simon  wrote:

> edexter wrote:
>
>> simon wrote:
>>
>>> Hi everybody,
>>>
>>> The situation:
>>> I wrote a GUI, based on Python, TkInter and Pmw.
>>> It runs perfectly fine with Python 2.4 (providing, TkInter and Pmw are
>>> installed). But it crashes with Python 2.6. I tried this on MacOSX11.4
>>> and various Linux Distributions.
>>> Crashes occurs when I activate a Pmw.Diaog (I guess this is due to a bug
>>> in the installed blt package), also when I use setitems on
>>> Pmw.OptionMenu (I guess this is due to another package, associated with
>>> tcl/tk).
>>>
>>> The target:
>>> I have to get my GUI work under openSUSE 11.1 (x86_64).
>>>
>>> My plan:
>>> On my openSUSE 11.1 (x86_64), Python 2.6 is installed by default.
>>> I would like to know, how to install Python 2.4 along with TkInter and
>>> Pmw (and packages that are required by them), parallel to the existing
>>> Python 2.6. So that I do not break other software that depends on Python
>>> 2.6.
>>>
>>> If you can think of another plan, I would be also glad to discuss it.
>>>
>>> Cheers,
>>> Simon
>>>
>>
>> I suspect you want to install python 2.4 and then reinstall 2.6  I did
>> that in windows and I don't understand why it wouldn't work in linux
>>
>
> I'm afraid, installation is quit different under UNIX based systems and
> Windows.
>
> I installed Python-2.4.4.tar.bz2 from python.org, using gcc-4.3 (within
> openSUSE 11.1 x86_64) via 'make altinstall'.
>
> First, I tried to configure with the following flags:
> --prefix=/opt/python-24 --enable-framework --with-pydebug
> This provoked an error during compilation via make (sorry, the list was so
> long, but I will post it, if it helps).
>

The --enable-framework option is for creating Framework builds on OS X. It
won't work on Linux.


>
> Second, configured again without any flags. The installation by 'make
> altinstall' to /usr/local was a success. Python2.6 seams unaffected, too.
> So, I got my parallel installation.
>
> However, I cannot import modules like Tkinter or readline within python2.4.
>
> For example, Tkinter.py is located in /usr/local/lib/python2.4/lib-tk
>
> sys.path says: ['', '/usr/local/lib/python24.zip',
> '/usr/local/lib/python2.4', '/usr/local/lib/python2.4/plat-linux2',
> '/usr/local/lib/python2.4/lib-tk', '/usr/local/lib/python2.4/lib-dynload',
> '/usr/local/lib/python2.4/site-packages']
>
> sys.prefix and sys.exec_prefix say: '/usr/local'
>
> my bash's PATH variable says:
> /sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/opt/kde3/bin:/usr/lib64/jvm/jre/bin:/usr/lib/mit/bin:/usr/lib/mit/sbin
>
> Which configuration step did I miss after my Python2.4 installation? What
> did I do wrong?
>


Again, give us the error message. We can't help if we don't know exactly
what's going on.


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


Re: Making the case for repeat

2009-06-12 Thread Boris Borcic

Raymond Hettinger wrote:

There is a natural inclination to do the opposite.  We factor code
to eliminate redundancy, but that is not always a good idea with
an API.  The goal for code factoring is to minimize redundancy.
The goal for API design is having simple parts that are easily
learned and can be readily combined (i.e. the notion of an
iterator algebra).


This reminds me of an early programming experience that left me with a 
fascination. At a time where code had to fit in a couple dozens kilobytes, I 
once had to make significant room in what was already very tight and terse code. 
Code factoring *did* provide the room in the end, but the fascinating part came 
before.


There was strictly no redundancy apparent at first, and finding a usable one 
involved contemplating code execution paths for hours until some degree of 
similarity was apparent between two code path families. And then, the 
fascinating part, was to progressively mutate both *away* from minimality of 
code, in order to enhance the similarity until it could be factored out.


I was impressed; in various ways. First; that the effort could be characterized 
quite mechanically and in a sense stupidly as finding a shortest equivalent 
program, while the subjective feeling was that the task exerted perceptive 
intelligence to the utmost. Second; by the notion that a global constraint of 
code minimization could map more locally to a constraint that drew code to 
expand. Third; that the process resulted in bottom-up construction of what's 
usually constructed top-down, mimicking the willful design of the latter case, 
eg. an API extension, as we might call it nowadays.


Cheers, BB
--
"hope achieves the square root of the impossible"


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


Re: Question about None

2009-06-12 Thread Javier Collado
Hello,

You're right, types.NoneType is not available in python 3.0, I wasn't
aware of that change. Thanks for pointing it out.

Best regards,
Javier

2009/6/12 Jeff McNeil :
> On Jun 12, 10:05 am, Paul LaFollette 
> wrote:
>> Kind people,
>>
>> Using Python 3.0 on a Gatesware machine (XP).
>> I am building a class in which I want to constrain the types that can
>> be stored in various instance variables.  For instance, I want to be
>> certain that self.loc contains an int.  This is straightforward (as
>> long as I maintain the discipline of changing loc through a method
>> rather than just twiddling it directly.
>>
>>   def setLoc(lo):
>>     assert isinstance(lo, int), "loc must be an int"
>>     self.loc = lo
>>
>> does the trick nicely.
>>
>> However, I also want to constrain self.next to be either an instance
>> of class Node, or None.  I would think that the following should work
>> but it doesn't.
>>
>>   def setNext(nxt):
>>     assert isinstance(nxt, (Node, NoneType)), "next must be a Node"
>>     self.next = nxt
>>
>> since type(Node) responds with  but the assertion
>> above gives "name 'NoneType' is not defined" suggesting that NoneType
>> is some sort of quasi-class.
>>
>>   def setNext(nxt):
>>     assert nxt==None or isinstance(nxt, Node), "next must be a Node"
>>     self.next = nxt
>>
>> works ok, but it's uglier than it ought to be.
>>
>> So, I have three questions.
>>
>> 1) Why doesn't isinstance(nxt, (Node, NoneType)) work?
>> 2) is their a less ugly alternative that what I am using?
>> 3) (this is purely philosophical but I am curious)  Would it not be
>> more intuitive if
>> isinstance(None, ) returned true?
>>
>> Thank you for your kind attention.
>> Paul
>
> 1. The problem is described clearly by that Exception. The 'NoneType'
> name isn't bound to any objects at that current scope.  I know that
> with 2.6, you can import 'types.NoneType' but I don't believe the 3.0
> types module includes NoneType.  Someone else will have to clarify
> that as I don't have 3.0 installed.
>
> 2. A less ugly alternative? You could use the accepted method of
> testing against None:
>
> if var is None:
>    do_stuff()
>
> The use of the 'is' operator checks whether objects are exactly the
> same (id(var) == id(None)) as opposed to 'isinstance' or '==.'
>
> You might also try defining descriptors in order to make your type
> checks slightly more transparent. That might be confusing to other
> users of your class, though. Not many people expect a TypeError from
> an attribute assignment.
>
> 3. None is an instance of NoneType. Why should isinstance return True
> when it's tested against other types?
>
> HTH,
>
> Jeff
> mcjeff.blogspot.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about None

2009-06-12 Thread Jean-Michel Pichavant



  def setNext(nxt):
assert nxt==None or isinstance(nxt, Node), "next must be a Node"
self.next = nxt

works ok, but it's uglier than it ought to be.

  
I don't find it that ugly. It's accurate, easy to read and understand. 
"What else ?" would say a famous coffee representative.

If you like perfection, replace nxt==None by nxt is None.

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


Re: install Python-2.4.4 from source (parallel to existing Python-2.6)

2009-06-12 Thread Simon

Benjamin Kaplan wrote:



On Fri, Jun 12, 2009 at 9:31 AM, Simon > wrote:


edexter wrote:

simon wrote:

Hi everybody,

The situation:
I wrote a GUI, based on Python, TkInter and Pmw.
It runs perfectly fine with Python 2.4 (providing, TkInter
and Pmw are
installed). But it crashes with Python 2.6. I tried this on
MacOSX11.4
and various Linux Distributions.
Crashes occurs when I activate a Pmw.Diaog (I guess this is
due to a bug
in the installed blt package), also when I use setitems on
Pmw.OptionMenu (I guess this is due to another package,
associated with
tcl/tk).

The target:
I have to get my GUI work under openSUSE 11.1 (x86_64).

My plan:
On my openSUSE 11.1 (x86_64), Python 2.6 is installed by
default.
I would like to know, how to install Python 2.4 along with
TkInter and
Pmw (and packages that are required by them), parallel to
the existing
Python 2.6. So that I do not break other software that
depends on Python
2.6.

If you can think of another plan, I would be also glad to
discuss it.

Cheers,
Simon


I suspect you want to install python 2.4 and then reinstall 2.6
 I did
that in windows and I don't understand why it wouldn't work in linux


I'm afraid, installation is quit different under UNIX based systems
and Windows.

I installed Python-2.4.4.tar.bz2 from python.org
, using gcc-4.3 (within openSUSE 11.1 x86_64) via
'make altinstall'.

First, I tried to configure with the following flags:
--prefix=/opt/python-24 --enable-framework --with-pydebug
This provoked an error during compilation via make (sorry, the list
was so long, but I will post it, if it helps).


The --enable-framework option is for creating Framework builds on OS X. 
It won't work on Linux.
 



Second, configured again without any flags. The installation by
'make altinstall' to /usr/local was a success. Python2.6 seams
unaffected, too. So, I got my parallel installation.

However, I cannot import modules like Tkinter or readline within
python2.4.

For example, Tkinter.py is located in /usr/local/lib/python2.4/lib-tk

sys.path says: ['', '/usr/local/lib/python24.zip',
'/usr/local/lib/python2.4', '/usr/local/lib/python2.4/plat-linux2',
'/usr/local/lib/python2.4/lib-tk',
'/usr/local/lib/python2.4/lib-dynload',
'/usr/local/lib/python2.4/site-packages']

sys.prefix and sys.exec_prefix say: '/usr/local'

my bash's PATH variable says:

/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/opt/kde3/bin:/usr/lib64/jvm/jre/bin:/usr/lib/mit/bin:/usr/lib/mit/sbin

Which configuration step did I miss after my Python2.4 installation?
What did I do wrong?



Again, give us the error message. We can't help if we don't know exactly 
what's going on.
 





Sorry, here it comes:


Python 2.4.4 (#1, Jun 12 2009, 14:11:55)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Traceback (most recent call last):
  File "/etc/pythonstart", line 7, in ?
import readline
ImportError: No module named readline

>>> import Tkinter
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 38, in ?
import _tkinter # If this fails your Python may not be configured 
for Tk

ImportError: No module named _tkinter



Right know, I'm following Christian's hint, to "install the development 
library of tk, readline, zlib and libbz2 prior to configure && make", 
because the following essential packages were not installed on my system:


autoconf automake libbz2-devel libopenssl-devel libtool ncurses-devel 
readline-devel sqlite2-devel tack tcl-devel tk-devel zlib-devel


I will let you know about the result, soon.

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


Re: Question about None

2009-06-12 Thread Terry Reedy

Paul LaFollette wrote:


since type(Node) responds with  but the assertion
above gives "name 'NoneType' is not defined" suggesting that NoneType
is some sort of quasi-class.


add NoneType = type(None) before using Nonetype

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


Re: zipfile doesn't compress very good, are there other solutions?

2009-06-12 Thread R. David Murray
Chris Rebert  wrote:
> On Thu, Jun 11, 2009 at 1:41 PM, Stef Mientki wrote:
> > Peter Otten wrote:
> >> Stef Mientki wrote:
> >>> Peter Otten wrote:
>  Stef Mientki wrote:
> > I packed all sources with zipfile,
> > but the compression doesn't seem to be very good.
> >
> 
>  If you don't specify the compression, the files are not compressed at
>  all. Just in case you didn't know...
> 
> >>>
> >>> .. and would you be willing to tell me how I could set the compression (
> >>> at maximum) ?
> >>>
> >>
> >> According to the documentation (hint, hint) there is only on and off.
> >>
> >> zipfile.ZipFile(filename, "w", compression=zipfile.ZIP_DEFLATED)
> >>
> >>
> >
> > sorry guys I made a mistake,
> > I did read the doc, but as there was no default value metioned,
> 
> Erm...
> 
> class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
> 
> Open a ZIP file [...] compression is the ZIP compression method to
> use when writing the archive, and should be ZIP_STORED or
> ZIP_DEFLATED; [...] The default is ZIP_STORED. [...]
> 
> Though I admit the docs could definitely do with having
> "compression=ZIP_STORED" in the signature part of the doc.

Georg's been fixing the method signatures bit by bit to use keyword style.
Doc patches would be welcome to help speed up the conversion process.

--David

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


ANNOUNCE: TIB/Rendezvous module for python

2009-06-12 Thread Sandra Bunn
Hi Thomas,

 

My name is Sandra with The Carrera Agency.  I saw an online article by you
regarding Tibco Rendezvous with Python.  I am currently looking for a
Python/Tibco developer for a remote position.  Below is a description of
what they are trying to do:

 

Summary: 
Need the ability to connect to a TIBCO server natively using Python. The
Python TICBO interface must be able to query for available servers and
server clusters, create connections and sessions, and feed messages to
queues and topics. The implementation must be fault tolerant and inform
calling libraries of errors and / or throw consistent exceptions that can be
caught and handled by higher level libraries. 

Functional Requirements 

The module must be able to: 
. connect to a TIBCO server using TIBCO's URL format 
. create a session to a named queue on the server. 
. create a message producer with a given session. 
. easily fill a TIBCO EMS Map Message with key value pairs. 
. send a filled Map Message to a TIBCO server. 
. shut down a connection. 
. work with TIBCO's built in failover and load balancing functionality. 

TIBCO C Native Equivalents 
The following are the native equivalents that need to successfully connect
to a TIBCO server. These functions should only be used as guidelines for
understanding which portions of TIBCO functionality are being used, and
should not be considered requirements for 1:1 equivalency. Simplifications
of TIBCO's C based functionality is expected. 
. Functions 
1. tibemsConnectionFactory_Create 
2. tibemsConnectionFactor_SetServerURL 
3. tibemsConnectionFactory_CreateConnection 
4. tibemsConnectionFactory_Destroy 
5. tibemsQueue_Create 
6. tibemsConnection_CreateSession 
7. tibemsConnection_Stop 
8. tibemsConnection_Close 
9. tibemsSession_CreateProducer 
10. tibemsMsgProducer_Close 
11. tibemsMsgProducer_SendEx 
12. tibemsDestination_Destroy 
13. tibemsMsg_Destroy 
14. tibemsMapMsg_Create 
15. tibemsMapMsg_Set* 

Structures 
1. tibemsMapMsg 
2. tibemsConnectionFactory 
3. tibemsConnection 
4. tibemsDestination 
5. tibemsSession 
6. tibemsMsgProducer

 

Basic assessment (not set in stone) of project level of effort to work
against: 
. Phase One - 1 week 
o Discovery 
o Architectural documentation for to the C TIBCO level commands.  Validation
with internal engineering teams of architectural documentation and high
level project plan. 

. Phase Two - 1.5 weeks 
o Coding - Wrapping C code with Boost or an equivalent wrapper system for
python. 

. Phase Three - 1.5 weeks 
o Test and debug the implementation to assure the appropriate error
conditions, performance, and other requirements set forth. 

. Phase Four - .5 week 
o Finalize documentation and cross train team on implementation

 

If you or someone you know might be interested, please contact me.  I look
forward to hearing from you.

 

Regards,

Sandra

 

 

Sandra Bunn
The Carrera Agency
65 Enterprise
Aliso Viejo, CA 92656
(310) 370-4778 - Ofc.
(310) 499-5653 - Fax

We've changed our look, not the quality of our service -
www.thecarreraagency.com



 

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


Re: Need help in Python regular expression

2009-06-12 Thread Rhodri James
On Fri, 12 Jun 2009 06:20:24 +0100, meryl   
wrote:

On Jun 11, 9:41 pm, "Mark Tolonen"  wrote:

"meryl"  wrote in message

> Hi,

> I have this regular expression
> blockRE = re.compile(".*RenderBlock {\w+}")

> it works if my source is "RenderBlock {CENTER}".


[snip]


---code--
import re
pat = re.compile(r'Render(?:Block|Table) (?:\(\w+\)|{\w+})')

testdata = '''\
RenderTable {TABLE}
RenderBlock (CENTER)
RenderBlock {CENTER}
RenderTable {TABLE)      #shouldn't match
'''

print pat.findall(testdata)
---

Result:

['RenderTable {TABLE}', 'RenderBlock (CENTER)', 'RenderBlock {CENTER}']

-Mark


Thanks for both of your help. How can i modify the RegExp so that
both
RenderTable {TABLE}
and
RenderTable {TABLE} [text with a-zA-Z=SPACE0-9]
will match

I try adding ".*" at the end , but it ends up just matching the second
one.


Curious, it should work (and match rather more than you want, but
that's another matter.  Try adding this instead:

'(?: \[[a-zA-Z= 0-9]*\])?'

Personally I'd replace all those spaces with \s* or \s+, but I'm
paranoid when it comes to whitespace.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about None

2009-06-12 Thread Robert Kern

On 2009-06-12 09:05, Paul LaFollette wrote:

Kind people,

Using Python 3.0 on a Gatesware machine (XP).
I am building a class in which I want to constrain the types that can
be stored in various instance variables.  For instance, I want to be
certain that self.loc contains an int.  This is straightforward (as
long as I maintain the discipline of changing loc through a method
rather than just twiddling it directly.


You may want to consider using Enthought's Traits package (disclosure: I work 
for Enthought).


  http://pypi.python.org/pypi/Traits/

Type-checking attributes is not my favorite feature of Traits (I try to avoid 
using this feature if I can avoid it), but it is designed for precisely your use 
cases.



In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:from enthought.traits.api import Float, HasTraits, Instance, Int, This
:
:class FancyClass(HasTraits):
:""" An example traited class.
:"""
:x = Float(10.0)
:y = Int(-20)
:
:class Node(HasTraits):
:""" A node in a single-linked list.
:"""
:
:# The location of this Node.
:loc = Int(0)
:
:# The next Node. This() is a special trait that accepts instances of
:# this class, or None.
:next = This()
:
:# The data attached to the Node. It will accept instances of FancyClass
:# or None.
:data = Instance(FancyClass)
:
:
:--

In [3]: n = Node()

In [4]: n.next

In [5]: n.data

In [6]: n.loc
Out[6]: 0

In [7]: fc = FancyClass(x=15.0)

In [8]: fc.x
Out[8]: 15.0

In [9]: fc.y
Out[9]: -20

In [10]: fc.y = 'a string'
---
TraitErrorTraceback (most recent call last)

/Users/rkern/ in ()

/Users/rkern/svn/et/Traits/enthought/traits/trait_handlers.pyc in error(self, 
object, name, value)

173 """
174 raise TraitError( object, name, self.full_info( object, name, 
value ),

--> 175   value )
176
177 def arg_error ( self, method, arg_num, object, name, value ):

TraitError: The 'y' trait of a FancyClass instance must be an integer, but a 
value of 'a string'  was specified.


In [11]: n.data = fc

In [12]: n.data = None

In [13]: n.data = n
---
TraitErrorTraceback (most recent call last)

/Users/rkern/ in ()

/Users/rkern/svn/et/Traits/enthought/traits/trait_handlers.pyc in error(self, 
object, name, value)

173 """
174 raise TraitError( object, name, self.full_info( object, name, 
value ),

--> 175   value )
176
177 def arg_error ( self, method, arg_num, object, name, value ):

TraitError: The 'data' trait of a Node instance must be a FancyClass or None, 
but a value of <__main__.Node object at 0x17999c0>  was 
specified.


In [14]: n.next = Node(loc=1)

In [15]: n.next
Out[15]: <__main__.Node at 0x1892e70>

--
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: TypeError: int argument required

2009-06-12 Thread Rhodri James

On Fri, 12 Jun 2009 04:56:24 +0100, lucius  wrote:


I am trying to
print some values to a file (using c's printf like method).
TypeError: int argument required
# this works, i see value on screen
 print  w, h, absX, absY

# where result is the return value of my regular expression.

  w, h, absX, absY = result.group(3), result.group(4), result.group
(5), result.group(6)

w = 100
h = 200

absX = 10.0
absY = 20.0

# this fails, I get "TypeError: int argument required"
   print >> fo, " " % (absX, absY, w, h)

Thank you for any help.


1.  This has to be the most incoherent help request that I've seen that
included actual information.  Figuring out what you were actually doing
was quite a challenge.

2.  That output string has severe "leaning toothpick" syndrome.  Python
accepts both single and double quotes to help avoid creating something
so unreadable: use them.

3. matchobject.group(n) returns a string, not an int or float.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to insert string in each match using RegEx iterator

2009-06-12 Thread Aahz
In article ,
[email protected] <[email protected]> wrote:
>
>MRI scans would no doubt reveal that people who attain a mastery of
>RegEx expressions must have highly developed areas of the brain. I
>wonder where the RegEx part of the brain might be located.

You want Friedl:
http://www.powells.com/biblio/2-9780596528126-0
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"Many customs in this life persist because they ease friction and promote
productivity as a result of universal agreement, and whether they are
precisely the optimal choices is much less important." --Henry Spencer
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How should I compare two txt files separately coming from windows/dos and linux/unix

2009-06-12 Thread Piet van Oostrum
> higer  (h) wrote:

>h> On Jun 11, 11:44 am, Chris Rebert  wrote:
>>> On Wed, Jun 10, 2009 at 8:11 PM, higer wrote:
>>> > I just want to compare two files,one from windows and the other from
>>> > unix. But I do not want to compare them through reading them line by
>>> > line. Then I found there is a filecmp module which is used as file and
>>> > directory comparisons. However,when I use two same files (one from
>>> > unix,one from windows,the content of them is the same) to test its cmp
>>> > function, filecmp.cmp told me false.
>>> 
>>> > Later, I found that windows use '\n\r' as new line flag but unix use
>>> > '\n', so filecmp.cmp think that they are different,then return false.
>>> > So, can anyone tell me that is there any method like IgnoreNewline
>>> > which can ignore the difference of new line flag in diffrent
>>> > platforms? If not,I think filecmp may be not a good file comparison
>>> 
>>> Nope, there's no such flag. You could run the files through either
>>> `dos2unix` or `unix2dos` beforehand though, which would solve the
>>> problem.
>>> Or you could write the trivial line comparison code yourself and just
>>> make sure to open the files in Universal Newline mode (add 'U' to the
>>> `mode` argument to `open()`).
>>> You could also file a bug (a patch to add newline insensitivity would
>>> probably be welcome).
>>> 
>>> Cheers,
>>> Chris
>>> --http://blog.rebertia.com

>h> Thank you very much. Adding 'U' argument can perfectly work, and I
>h> think it is definitely to report this as a bug to Python.org as you
>h> say.

Filecmp does a binary compare, not a text compare. So it starts by
comparing the sizes of the files and if they are different the files
must be different. If equal it compares the bytes by reading large
blocks. Comparing text files would be quite different especially when
ignoring line separators. Maybe comparing text files should be added as
a new feature.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How should I compare two txt files separately coming from windows/dos and linux/unix

2009-06-12 Thread Emile van Sebille

On 6/11/2009 12:09 AM higer said...


Tool can certainly be used to compare two files,but I just want to
compare them using Python code.



difflib?

Emile

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


uncompress base64-gzipped string

2009-06-12 Thread Niels Egberts
I'm creating a game in python and I want to a level editor called
'tiled'. It ouputs a .xml file with base64-gzipped information. Then
every 4 bytes represents a number. See the following link:

http://www.mapeditor.org/wiki/Examining_the_map_format

To start I tried:
code = 
base64.b64decode("H4sIAO3NoREAMAgEsLedAfafE4+s6l0jolNJiif18tt/Fj8AAMC9ARtYg28AEAAA")
code = zlib.decompress(code)

But I get:
zlib.error: Error -3 while decompressing data: incorrect header check

How can I solve this?

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


Re: ANN: WHIFF += Flash chart widget support (Aaron Watters)

2009-06-12 Thread Aaron Watters
Regarding:
 http://aaron.oirt.rutgers.edu/myapp/amcharts/doc

On Jun 12, 3:07 am, oyster  wrote:
> nice
> the only pity is that amcharts is not a money-free product

It is if you don't mind the little link in the corner.
(which I think is only fair).

I found a totally free one that looked pretty good
too, which I may add sometime.

http://teethgrinder.co.uk/open-flash-chart/

  -- Aaron Watters

===
an apple every 8 hours
will keep 3 doctors away.  -- kliban
-- 
http://mail.python.org/mailman/listinfo/python-list


Exceptions and Object Destruction (was: Problem with apsw and garbage collection)

2009-06-12 Thread Nikolaus Rath
Nikolaus Rath  writes:
> Hi,
>
> Please consider this example:
[]

I think I managed to narrow down the problem a bit. It seems that when
a function returns normally, its local variables are immediately
destroyed. However, if the function is left due to an exception, the
local variables remain alive:

-snip-
#!/usr/bin/env python
import gc

class testclass(object):
def __init__(self):
print "Initializing"

def __del__(self):
print "Destructing"

def dostuff(fail):
obj = testclass()

if fail:
raise TypeError

print "Calling dostuff"
dostuff(fail=False)
print "dostuff returned"

try:
print "Calling dostuff"
dostuff(fail=True)
except TypeError:
pass

gc.collect()
print "dostuff returned"
-snip-


Prints out:


-snip-
Calling dostuff
Initializing
Destructing
dostuff returned
Calling dostuff
Initializing
dostuff returned
Destructing
-snip-


Is there a way to have the obj variable (that is created in dostuff())
destroyed earlier than at the end of the program? As you can see, I
already tried to explicitly call the garbage collector, but this does
not help.


Best,


   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception inside loop wrongly failing doctest

2009-06-12 Thread Ben Finney
Steven D'Aprano  writes:

> Ah, that would be it. Not a bug then, a limitation of the doctest module. 

The doctest module is good for narrative tests (ensuring that examples
in documentation actually work as written), but poor for unit testing.
Both functions are useful, but each should use a different tool
http://bemusement.org/diary/2008/October/23/narrative-tests>.

Not entirely related to the limitation you've found, and I don't know
from your explanation whether you're mixing the two purposes, but it's
worth pointing out in case you are.

-- 
 \ “I used to think that the brain was the most wonderful organ in |
  `\   my body. Then I realized who was telling me this.” —Emo Philips |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: install Python-2.4.4 from source (parallel to existing Python-2.6)

2009-06-12 Thread Christian Heimes
Simon schrieb:
> Christian Heimes wrote:
>> Simon wrote:
>>> I installed Python-2.4.4.tar.bz2 from python.org, using gcc-4.3 (within
>>> openSUSE 11.1 x86_64) via 'make altinstall'.
>>>
>>> First, I tried to configure with the following flags:
>>> --prefix=/opt/python-24 --enable-framework --with-pydebug
>>> This provoked an error during compilation via make (sorry, the list was
>>> so long, but I will post it, if it helps).
>>
>> --enable-framework is for Mac OS X only.
>>
>>> Second, configured again without any flags. The installation by 'make
>>> altinstall' to /usr/local was a success. Python2.6 seams unaffected,
>>> too. So, I got my parallel installation.
>>
>> You have chosen the correct and canonical way to install a parallel
>> installation of Python.
>>
>>> However, I cannot import modules like Tkinter or readline within
>>> python2.4.
>>
>> You must install the development library of tk, readline, zlib and
>> libbz2 prior to configure && make.
>>
>> Try this on your box:
>>
>> zypper install gcc make autoconf automake libtool zlib-devel
>> readline-devel tk-devel tcl-devel sqlite2-devel libbz2-devel
>> libopenssl-devel
>>
> 
> 
> Unfortunately, I got the following errors, while compiling via make.
> Please, see attached text file for details about everything I did from
> installing the missing packages via zypper until make.

zypper should have installed all necessary dependencies, including a
whole bunch of X11 headers. Something seems to be wrong on your system
or SuSE's package dependencies.
I know why I dislike SuSE. :) Although I started my Linux career 12
years ago with SuSE I prefer Debian based systems since Woody came out
in 2002. :)

> X11 says:
> Program 'X11' is present in package 'xorg-x11', which is installed on
> your system.

zypper search X11 | grep devel
...
zypper install xorg-x11-devel

That should (hopefully) do the trick. On a Debian based systems it's
much easier to install all Python dependencies with "apt-get build-dep
python2.5"

To quote SuSE: "Have a lot of fun ..."

Und viel Glück!

Christian

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


Re: Exceptions and Object Destruction

2009-06-12 Thread MRAB

Nikolaus Rath wrote:

Nikolaus Rath  writes:

Hi,

Please consider this example:

[]

I think I managed to narrow down the problem a bit. It seems that when
a function returns normally, its local variables are immediately
destroyed. However, if the function is left due to an exception, the
local variables remain alive:

-snip-
#!/usr/bin/env python
import gc

class testclass(object):
def __init__(self):
print "Initializing"

def __del__(self):

print "Destructing"

def dostuff(fail):

obj = testclass()

if fail:
raise TypeError

print "Calling dostuff"

dostuff(fail=False)
print "dostuff returned"

try:
print "Calling dostuff"
dostuff(fail=True)
except TypeError:
pass

gc.collect()
print "dostuff returned"
-snip-



Prints out:


-snip-
Calling dostuff
Initializing
Destructing
dostuff returned
Calling dostuff
Initializing
dostuff returned
Destructing
-snip-


Is there a way to have the obj variable (that is created in dostuff())
destroyed earlier than at the end of the program? As you can see, I
already tried to explicitly call the garbage collector, but this does
not help.


Are the objects retained because there's a reference to the stack
frame(s) in the traceback?
--
http://mail.python.org/mailman/listinfo/python-list


Re: uncompress base64-gzipped string

2009-06-12 Thread John Machin
Niels Egberts  gmail.com> writes:

> zlib.error: Error -3 while decompressing data: incorrect header check
> 
> How can I solve this?

The link you quoted says "you need to first base64 decode
the string, then gunzip the resulting data" ... so gunzip it:

| >>> s0 =
"H4sIA.."
| >>> import base64
| >>> s1 = base64.b64decode(s0)
| >>> len(s0)
| 72
| >>> len(s1)
| 54
| >>> import StringIO
# or cStringIO or io depending on what
# Python versions you want to support
| >>> sio = StringIO.StringIO(s1)
| >>> import gzip
| >>> gzf = gzip.GzipFile(fileobj=sio)
| >>> guff = gzf.read()
| >>> len(guff)
| 4096
| >>> guff[:100]
| '\x1b\x00\x00\x00\x1b\x00\x00\x00\x1b\x00\x00\x00 [snip]

What a long journey: parse xml, base64 decode, gunzip,
and you're still not home; next stop is struct.unpack ...

HTH,
John




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


Re: failed to build decompyle/unpyc project on WindowsXP

2009-06-12 Thread higer
On Jun 12, 4:55 pm, higer  wrote:
> Maybe everyone know that decompyle(hosted on SourceForge.net) is a
> tool to transfer a .pyc file to .py file and now it does only support
> Python 2.3 or the below. I have found a project named unpyc which can
> support Python version 2.5. Unpyc project is build on decompyle which
> is hosted on google code and if you want you can download it.
>
> I build unpyc on Ubuntu successfully and can run it ok. But with some
> purpose, I just want to use this tool on my WindowsXP, so I tried to
> build it. I have tried many times and methods, with .net2003 or
> MingGW, but I failed. So,I come here looking for sombody can help me.I
> will give the showing error message with different method on the
> following:
>
> 1     Using command : python setup.py install
> F:\unpyc>python setup.py install
> running install
> running build
> running build_py
> creating build\lib.win32-2.5
> creating build\lib.win32-2.5\unpyc
> copying unpyc\dis_15.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_16.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_20.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_21.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_22.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_23.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_24.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_25.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_26.py -> build\lib.win32-2.5\unpyc
> copying unpyc\dis_files.py -> build\lib.win32-2.5\unpyc
> copying unpyc\magics.py -> build\lib.win32-2.5\unpyc
> copying unpyc\marshal_files.py -> build\lib.win32-2.5\unpyc
> copying unpyc\opcode_23.py -> build\lib.win32-2.5\unpyc
> copying unpyc\opcode_24.py -> build\lib.win32-2.5\unpyc
> copying unpyc\opcode_25.py -> build\lib.win32-2.5\unpyc
> copying unpyc\opcode_26.py -> build\lib.win32-2.5\unpyc
> copying unpyc\Parser.py -> build\lib.win32-2.5\unpyc
> copying unpyc\Scanner.py -> build\lib.win32-2.5\unpyc
> copying unpyc\spark.py -> build\lib.win32-2.5\unpyc
> copying unpyc\verify.py -> build\lib.win32-2.5\unpyc
> copying unpyc\Walker.py -> build\lib.win32-2.5\unpyc
> copying unpyc\__init__.py -> build\lib.win32-2.5\unpyc
> running build_ext
> building 'unpyc/marshal_25' extension
> creating build\temp.win32-2.5
> creating build\temp.win32-2.5\Release
> creating build\temp.win32-2.5\Release\unpyc
> f:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c /
> nologo /Ox /MD /W3 /GX /DNDEBU
> G -IF:\Python25\include -IF:\Python25\PC /Tcunpyc/marshal_25.c /Fobuild
> \temp.win32-2.5\Release\unpyc
> /marshal_25.obj
> marshal_25.c
> unpyc\marshal_25.c(401) : warning C4273: 'PyMarshal_WriteLongToFile' :
> inconsistent dll linkage
> unpyc\marshal_25.c(413) : warning C4273:
> 'PyMarshal_WriteObjectToFile' : inconsistent dll linkage
> unpyc\marshal_25.c(1004) : warning C4273:
> 'PyMarshal_ReadShortFromFile' : inconsistent dll linkage
> unpyc\marshal_25.c(1015) : warning C4273:
> 'PyMarshal_ReadLongFromFile' : inconsistent dll linkage
> unpyc\marshal_25.c(1044) : warning C4273:
> 'PyMarshal_ReadLastObjectFromFile' : inconsistent dll link
> age
> unpyc\marshal_25.c(1087) : warning C4273:
> 'PyMarshal_ReadObjectFromFile' : inconsistent dll linkage
> unpyc\marshal_25.c(1101) : warning C4273:
> 'PyMarshal_ReadObjectFromString' : inconsistent dll linkag
> e
> unpyc\marshal_25.c(1116) : warning C4273:
> 'PyMarshal_WriteObjectToString' : inconsistent dll linkage
>
> f:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe /
> DLL /nologo /INCREMENTAL:NO /LI
> BPATH:F:\Python25\libs /LIBPATH:F:\Python25\PCBuild /EXPORT:initunpyc/
> marshal_25 build\temp.win32-2.
> 5\Release\unpyc/marshal_25.obj /OUT:build\lib.win32-2.5\unpyc/
> marshal_25.pyd /IMPLIB:build\temp.win3
> 2-2.5\Release\unpyc\marshal_25.lib
> marshal_25.obj : error LNK2001: unresolved external symbol initunpyc/
> marshal_25
> build\temp.win32-2.5\Release\unpyc\marshal_25.lib : fatal error
> LNK1120: 1 unresolved externals
> LINK : fatal error LNK1141: failure during build of exports file
> error: command '"f:\Program Files\Microsoft Visual Studio .NET
> 2003\Vc7\bin\link.exe"' failed with e
> xit status 1141
>
> 2    Using command:   python setup.py build -c mingw32
>
> F:\unpyc>python setup.py build -c mingw32
> running build
> running build_py
> running build_ext
> building 'unpyc/marshal_25' extension
> F:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IF:\Python25\include -
> IF:\Python25\PC -c unpyc/mars
> hal_25.c -o build\temp.win32-2.5\Release\unpyc\marshal_25.o
> unpyc/marshal_25.c:1087: warning: 'PyMarshal_ReadObjectFromFile'
> defined locally after being referen
> ced with dllimport linkage
> unpyc/marshal_25.c:1101: warning: 'PyMarshal_ReadObjectFromString'
> defined locally after being refer
> enced with dllimport linkage
> writing build\temp.win32-2.5\Release\unpyc\marshal_25.def
> F:\mingw\bin\gcc.exe -mno-cygwin -shared -s build
> \temp.win32-2.5\Release\unpyc\marshal_25.o build\te
> mp.win32-2.5\Re

Re: Unhandled exception in thread

2009-06-12 Thread ryles
On Jun 11, 3:52 pm, Mads Michelsen  wrote:
> Here's the deal. The script in question is a screen scraping thing
> which downloads and parses the html in the background using a separate
> thread (the 'thread' module), while the main program serves up the
> data to the user, allowing some modicum of interaction. Sometimes, not
> always (though I cannot see a pattern), when I quit the script, the
> following error message is printed:
>
>     Unhandled exception in thread started by
>     Error in sys.excepthook:
>
>     Original exception was:

Are you using daemon threads? There are some issues with CPython when
exiting with daemon threads:

http://bugs.python.org/issue1722344

http://bugs.python.org/issue1856

http://bugs.python.org/issue4106

It's possible you are encountering this kind of problem. I have had to
deal with issue4106, the workaround being to explicitly join the
thread of multiprocessing.Queue before exiting.

I would follow Scott's advice and explicitly request and wait for your
threads to exit before terminating the process.
-- 
http://mail.python.org/mailman/listinfo/python-list


Lexical scope: converting Perl to Python

2009-06-12 Thread Andrew Savige

I'd like to convert the following Perl code to Python:

 use strict;
 {
   my %private_hash = ( A=>42, B=>69 );
   sub public_fn {
 my $param = shift;
 return $private_hash{$param};
   }
 }
 print public_fn("A");    # good:  prints 42
 my $x = $private_hash{"A"};  # error: good, hash not in scope

The real code is more complex; the above is a simplified example.

Notice that this code uses Perl's lexical scope to hide the
%private_hash variable, but not the public_fn() function.

While I could convert this code to the following Python code:

 private_hash = dict( A=42, B=69 )
 def public_fn(param):
   return private_hash[param]
 print public_fn("A") # good:  prints 42
 x = private_hash["A"]    # works: oops, hash is in scope

I'm not happy with that because I'd like to limit the scope of the
private_hash variable so that it is known only inside public_fn.

Of course, I could hide the hash like so:

 def public_fn(param):
   private_hash = dict( A=42, B=69 )
   return private_hash[param]

yet I'm not happy with that either because of the repeated
initialization the hash each time the function is called.

What is the Pythonic equivalent of Perl's lexical scope, as
illustrated by the code snippet above?

Thanks,
/-\



  Need a Holiday? Win a $10,000 Holiday of your choice. Enter 
now.http://us.lrd.yahoo.com/_ylc=X3oDMTJxN2x2ZmNpBF9zAzIwMjM2MTY2MTMEdG1fZG1lY2gDVGV4dCBMaW5rBHRtX2xuawNVMTEwMzk3NwR0bV9uZXQDWWFob28hBHRtX3BvcwN0YWdsaW5lBHRtX3BwdHkDYXVueg--/SIG=14600t3ni/**http%3A//au.rd.yahoo.com/mail/tagline/creativeholidays/*http%3A//au.docs.yahoo.com/homepageset/%3Fp1=other%26p2=au%26p3=mailtagline
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] Multi-Threading and KeyboardInterrupt

2009-06-12 Thread Mike Kazantsev
On Thu, 11 Jun 2009 22:35:15 -0700
Dennis Lee Bieber  wrote:

> On Thu, 11 Jun 2009 08:44:24 -0500, "Strax-Haber, Matthew (LARC-D320)"
>  declaimed the following in
> gmane.comp.python.general:
> 
> > I sent this to the Tutor mailing list and did not receive a response.
> > Perhaps one of you might be able to offer some sagely wisdom or pointed
> > remarks?
> > 
> > Please reply off-list and thanks in advance. Code examples are below in
> > plain text.
> >
>   Sorry -- you post to a public forum, expect to get the response on a
> public forum...
> 
> > > My program runs interactively by allowing the user to directly
> > > interact with the python prompt. This program has a runAll() method
> > > that runs a series of subprocesses with a cap on how many instances
> > > are running at a time. My intent is to allow the user to use Ctrl-C to
> > > break these subprocesses. Note that while not reflected in the demo
> 
>   Are they subprocesses or threads? Your sample code seems to be using
> threads.
> 
>   When using threads, there is no assurance that any thread other than
> the main program will receive a keyboard interrupt.

In fact, no thread other than the main will get interrupt.


> > def runAll():
> > workers = [ Thread(target = runSingle, args = [i])
> > for i in xrange(MAX_SUBPROCS + 1) ]
> > try:
> > for w in workers:
> > w.start()
> > except KeyboardInterrupt:
> > ## I want this to be shown on a KeyboardInterrupt
> > print '* stopped midway '
> 
>   You are unlikely to see that... After you start the defined worker
> /threads/ (which doesn't take very long -- all threads will be started,
> but some may immediately block on the semaphore) this block will exit
> and you will be at...
> 
> > for w in workers:
> > w.join()
>
>   ... a .join() call, which is the most likely position at which the
> keyboard interrupt will be processed, killing the main program thread
> and probably generating some errors as dangling active threads are
> forceably killed.

There was quite interesting explaination of what happens when you send
^C with threads, posted on concurrency-sig list recently:

  http://blip.tv/file/2232410
  http://www.dabeaz.com/python/GIL.pdf

Can be quite shocking, but my experience w/ threads only confirms that.


-- 
Mike Kazantsev // fraggod.net


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


Re: Lexical scope: converting Perl to Python

2009-06-12 Thread Stephen Hansen
>
>  private_hash = dict( A=42, B=69 )
>  def public_fn(param):
>return private_hash[param]
>  print public_fn("A") # good:  prints 42
>  x = private_hash["A"]# works: oops, hash is in scope
>
> I'm not happy with that because I'd like to limit the scope of the
> private_hash variable so that it is known only inside public_fn.
>

A common idiom to do that would be this:

def public_fn(param, __private_hash=dict(A=42, B=69)):
return __private_hash[param]

People often squint when they see that but it is useful in several ways.
Python initializes the default arguments -once-, at definition. If they are
mutable-- a dictionary, list or such-- that same dict is used everytime the
function is called.

HTH,

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


Re: Lexical scope: converting Perl to Python

2009-06-12 Thread Terry Reedy

Andrew Savige wrote:

I'd like to convert the following Perl code to Python:

 use strict;
 {
   my %private_hash = ( A=>42, B=>69 );
   sub public_fn {
 my $param = shift;
 return $private_hash{$param};
   }
 }
 print public_fn("A");# good:  prints 42
 my $x = $private_hash{"A"};  # error: good, hash not in scope

The real code is more complex; the above is a simplified example.

Notice that this code uses Perl's lexical scope to hide the
%private_hash variable, but not the public_fn() function.

While I could convert this code to the following Python code:

 private_hash = dict( A=42, B=69 )
 def public_fn(param):
   return private_hash[param]
 print public_fn("A") # good:  prints 42
 x = private_hash["A"]# works: oops, hash is in scope


Why would you do that if you do not want to do that?


I'm not happy with that because I'd like to limit the scope of the
private_hash variable so that it is known only inside public_fn.


def public_fn():
  private_hash = dict( A=42, B=69 )
  def public_fn(param):
return private_hash[param]
  return public_fn
public_fn = public_fn()
print (public_fn("A"))
x = private_hash["A"]

# outputs
42
Traceback (most recent call last):
  File "C:\Programs\Python31\misc\t1", line 8, in 
x = private_hash["A"]
NameError: name 'private_hash' is not defined

Terry Jan Reedy

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


Re: Lexical scope: converting Perl to Python

2009-06-12 Thread Mike Kazantsev
On Fri, 12 Jun 2009 22:02:53 -0700 (PDT)
Andrew Savige  wrote:

> I'd like to convert the following Perl code to Python:
> 
>  use strict;
>  {
>    my %private_hash = ( A=>42, B=>69 );
>    sub public_fn {
>  my $param = shift;
>  return $private_hash{$param};
>    }
>  }
>  print public_fn("A");    # good:  prints 42
>  my $x = $private_hash{"A"};  # error: good, hash not in scope
>
...
> 
> What is the Pythonic equivalent of Perl's lexical scope, as
> illustrated by the code snippet above?

If you're using scope for garbage-collecting purposes, there's "with"
statement and contextlib:

  from contextlib import contextmanager

  @contextmanager
  def get_hash():
complex_hash = dict(A=42, B-69)
try: yield complex_hash
except Exception as ex:
  del complex_hash # complex destructor ;)
  raise ex

  with get_hash() as hash:
# do stuff with hash

Note that this only makes sense if you need to implement some complex
operation on hash destruction, and do that whatever-happens-inside-with
to close the object, obviously not the case with simple dict above.

And if you want to obfuscate one part of your code from another, you'll
probably have better luck with languages like java, since no one seem
to care about such stuff with python, so it'd be a hack against the
language, at best.
Why would you want to hide the code from itself, anyway? It's not like
you'd be able to accomplish it - code can easily grep it's process body
in memory and harvest all the "private" values, so I'd suggest getting
some fresh air when you start to feel like doing that.

-- 
Mike Kazantsev // fraggod.net


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


Re: Question about None

2009-06-12 Thread Steven D'Aprano
Paul LaFollette wrote:

> 3) (this is purely philosophical but I am curious)  Would it not be
> more intuitive if
> isinstance(None, ) returned true?

Good grief no!!!

None is an object. It has a type, NoneType. It's *not* a string, or a float,
or an int, or a list, so why would you want isinstance() to *lie* and say
that it is?


Python is good for testing these sorts of ideas:

>>> _isinstance = isinstance
>>> def isinstance(obj, type):
... if obj is None: return True
... return _isinstance(obj, type)
...
>>> x = "parrot"
>>> if isinstance(x, str):
... print x.upper() 
...
PARROT
>>> x = None
>>> if isinstance(x, str): print x.upper()
...
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'NoneType' object has no attribute 'upper'




-- 
Steven

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


Re: Question about None

2009-06-12 Thread Steven D'Aprano
Jean-Michel Pichavant wrote:

> 
>>   def setNext(nxt):
>> assert nxt==None or isinstance(nxt, Node), "next must be a Node"
>> self.next = nxt
>>
>> works ok, but it's uglier than it ought to be.
>>
>>   
> I don't find it that ugly. It's accurate, easy to read and understand.

Actually, it's inaccurate. There are *three* bugs in that code, two in the
same line. (Admittedly, one of the three is closer to a nitpick than a
bug.) You already allude to one of them:


> "What else ?" would say a famous coffee representative.
> If you like perfection, replace nxt==None by nxt is None.

Delete the "if you like perfection" part. Testing for equality against None
in this case is simply *wrong*. Arbitrary objects can be made to test equal
to None -- for instance, the Null object pattern. Unless you wish to allow
such "null" objects as well as None, then "nxt == None" does not do what
you want to do: it fails to reject some things that should be rejected.

The second bug is that the line uses assert for runtime value/type testing.
That's bad, because asserts are disabled when you run Python with the
optimisation flag. That means that your program will stop performing the
necessary test.

assert is for testing program logic[1], not argument testing. If you're ever
tempted to write an if...elif...else block that includes the comment, "this
should never happen, but just in case" then you have a good candidate for
an assert. A good use for assert is for checking that your program logic is
correct, not for testing user-arguments:

def process(text):
for word in text.split():
word = somefunction(word)
# say that it's important that word contains no newlines
# you're sure that somefunction() *won't* introduce any,
# but you want to be positive
assert "\n" not in word
do_something_with(word)

In this case, assert is appropriate: the code *should* work if the assert is
disabled, but it will give you some protection from bugs in your code.
Whenever you're tempted to use assert, ask yourself "if I deleted this test
from my code, would the program still run correctly?". If the answer
is "possibly not", then don't use an assert.


The third bug (the nitpick) is a bug in the API: you name the argument "nxt"
with no e, but in the error message, you call it "next" with an e. The fact
that any intelligent person should be able to guess what parameter the
error is referring to doesn't make it less wrong.

So, fixing the three issues:

def setNext(next):
if not (next is None or isinstance(next, Node)):
raise ValueError("next must be a Node")
self.next = next




[1] Arguably, it's also good for poor-man's unit testing when you're too
lazy to write proper tests.



-- 
Steven

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