Renaming Excel Spreadsheets

2008-08-26 Thread James Matthews
-- Forwarded message --
From: Waldemar Osuch <[EMAIL PROTECTED]>
Date: Tue, Aug 26, 2008 at 7:59 PM
Subject: Re: [python-win32] Fwd: Renaming Excel Spreadsheets
To: Python-Win32 List <[EMAIL PROTECTED]>


On Tue, Aug 26, 2008 at 12:57 PM, James Matthews <[EMAIL PROTECTED]>
wrote:
>
>
> -- Forwarded message --
> From: Greg Lindstrom <[EMAIL PROTECTED]>
> Date: Tue, Aug 26, 2008 at 11:54 AM
> Subject: Renaming Excel Spreadsheets
> To: python-list@python.org
>
>
> Hello,
>
> I am working with Python to create Excel spreadsheets and have run into a
> couple of problems I hope you can help me with.
>
> First...are there any bindings/libraries into Open Office?
>
> Now, back to Excel.
>
> --> Does anyone know a way to create N worksheets?  By default, 3 are
> created, but I would like more.
>
> --> Is it possible to rename a worksheet inside of the workbook (change
> "Sheet1" to "July 08", for example).
>
> I've been working with Mark Hammond's book on Windows programming with
> Python, but these have me stumped.
>
> Better yet, an Open Source reporting system (ala Crystal Reports) would
keep
> me from having to write this.  I've looked at Jasper and DataVision;
>
> Thanks,
> --greg
>

That should get you started

>>> from win32com.client import Dispatch
>>> app = Dispatch('Excel.Application')
>>> app.Visible = True
>>> wrk = app.Workbooks.Add()
>>> wrk.Sheets.Count
3
>>> sh = wrk.Sheets.Add()
>>> wrk.Sheets.Count
4
>>> sh.Name
u'Sheet4'
>>> sh.Name = 'New Name 4'
>>> wrk.Sheets[0].Name
u'New Name 4'
>>> wrk.Sheets[2].Name
u'Sheet2'
>>> wrk.Sheets[2].Name = 'Hello'
>>> wrk.Save()
>>> wrk.Close(0)
>>> app.Quit()
>>>

But I would recommend using xlwt (friendly fork of pyExcelerator) for
Excel generation.
It lets you bypass having to install Microsoft Office.
https://secure.simplistix.co.uk/svn/xlwt/trunk/README.html

The OpenOffice comes with its own version of python that can be used
for automation.
http://wiki.services.openoffice.org/wiki/Python

Another option is to manipulate the OpenOffice documents directly.
http://openoffice-python.origo.ethz.ch/

Or create OpenOffice document as a template with all the formatting you
desire
and generate new document by judicious modification of the template's XML.
The OpenOffice documents are just a bunch of XML files zipped together.
Change the extension to *.zip and use your favorite unzipping program
to see for yourself.

Waldemar
___
python-win32 mailing list
[EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/python-win32



-- 
http://www.goldwatches.com/
--
http://mail.python.org/mailman/listinfo/python-list

Baume & Mercier Hampton Ladies Watch 8440 Recommendation Discount Watches

2008-08-26 Thread hualibao004
Baume & Mercier Hampton Ladies Watch 8440 Recommendation Discount
Watches

Baume & Mercier Hampton Ladies Watch 8440 Site:
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-165.html

Thank you for choosing http://www.pxhelp.com/

Quality Baume & Mercier Watches: http://baume-mercier-watches.pxhelp.com/


Baume & Mercier Hampton Ladies Watch 8440 AdditionalInfo :

Watches Brand :   Baume & Mercier Watches ( 
http://baume-mercier-watches.pxhelp.com/
)
Gender :  Mens
Model :   Baume-8440
Also Called : MOA8440, 8440, Baume-Mercier-8440, Baume-et-
Mercier-8440
Case Material :   Stainless Steel
Movement :Quartz
Crystal : Scratch Resistant Sapphire
Dial Color :  White Mother-of-pearl
Clasp :   White Leather
Bezel :   Fixed
Case Thickness :   20.5mm x 33mm
Water Resistant : 30m/100ft

Stainless Steel Case with a Mother of Pearl Dial. White  Leather
Strap. Cartier Deployment Buckle Clasp. Quartz Movement. Fixed Bezel.
Scratch Resistant Sapphire Crystal. Solid  Back Case. 30m Water
Resistant. 20.5mm x 33mm Case Diameter. 7mm Case Thickness. Special
Limited Edition model with numeral 10 on the dial and case back
Decorated center of dial with Baume & Mercier Logo.

Other Baume & Mercier Watches You Might Like

Baume & Mercier Hampton Milleis Ladies Watch 6901
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-197.html
Baume and Mercier Riviera Chronograph Mens Watch 8625
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-343.html
Baume & Mercier Hampton Milleis Mens Watch 8190
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-200.html
Baume & Mercier Hampton City Ladies Watch 8352
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-224.html
Baume and Mercier Capeland S Steel Black Unisex Watch 8469
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-261.html
Baume and Mercier Hampton Spirit Moonphase Mens Watch 8487
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-213.html
Baume and Mercier Riviera Diamond Ladies Watch 8463
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-355.html
Baume and Mercier Hampton Classic Ladies Watch 8504
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-162.html
Baume & Mercier Hampton Mens Watch 8479
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-164.html
Baume and Mercier Hampton Classic Square Chronograph Mens Watch 8607
http://baume-mercier-watches.pxhelp.com/Baume-Mercier-wristwatch-157.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: atomic increment

2008-08-26 Thread Paul Rubin
Frank Millman <[EMAIL PROTECTED]> writes:
> Just out of interest, would the following, without a lock, be safe?
> old, atomic_int = atomic_int, atomic_int+1

No I don't think so.  But I'm told that in CPython, you can say
   
  counter = iter(xrange(1000))  # some number that exceeds what you'll use
  ...

  atomic_int = counter.next()

and the GIL keeps it safe.  When in doubt, use a lock or communicate
with other threads through Queues.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes: loading .so file on Linux

2008-08-26 Thread castironpi
On Aug 27, 12:03 am, Paddy <[EMAIL PROTECTED]> wrote:
> On Aug 23, 2:33 pm, Paddy <[EMAIL PROTECTED]> wrote:
> > Hi,
> > I am am falling at the first hurdle when trying to access a library
> > using ctypes.
>
> > I have a file libucdb.so which the file command says is shared object,
> > but I cannot get it to load:
>
> > Any help would be appreciated:
>
> > dmccarthy: file /opt/questasim_6.4/questasim/linux/libucdb.a /opt/
> > questasim_=
> > 6.4/questasim/linux/libucdb.so
> > /opt/questasim_6.4/questasim/linux/libucdb.a:  current ar archive
> > /opt/questasim_6.4/questasim/linux/libucdb.so: ELF 32-bit LSB shared
> > object,=
> >  Intel 80386, version 1 (SYSV), not stripped
> > dmccarthy: python
> > ActivePython 2.5.1.1 (ActiveState Software Inc.) based on
> > Python 2.5.1 (r251:54863, May  2 2007, 08:46:07)
> > [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > cdll.LoadLibrary("libc.so.6")
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > NameError: name 'cdll' is not defined>>> from ctypes import *
> > >>> ^[[A^[[A
>
> >     ^e "", line 1
> > SyntaxError: invalid syntax>>> cdll.LoadLibrary("libc.so.6")
>
> > >>> 
> > cdll.LoadLibrary("libucdb.so")
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "/software/unix-soft/linux/ActivePython-2.5.1.1-linux-x86_64/
> > lib/pyth=
> > on2.5/ctypes/__init__.py", line 423, in LoadLibrary
> >     return self._dlltype(name)
> >   File "/software/unix-soft/linux/ActivePython-2.5.1.1-linux-x86_64/
> > lib/pyth=
> > on2.5/ctypes/__init__.py", line 340, in __init__
> >     self._handle =3D _dlopen(self._name, mode)
> > OSError: libucdb.so: cannot open shared object file: No such file or
> > directo=
> > ry>>> cdll.LoadLibrary("libc.so.6")
>
> > >>> libc =3D 
> > CDLL("libc.so.6")
> > >>> libc
>
> > >>> libc =3D 
> > CDLL("libucdb.so")
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "/software/unix-soft/linux/ActivePython-2.5.1.1-linux-x86_64/
> > lib/pyth=
> > on2.5/ctypes/__init__.py", line 340, in __init__
> >     self._handle =3D _dlopen(self._name, mode)
> > OSError: libucdb.so: cannot open shared object file: No such file or
> > directo=
> > ry>>> libc =3D CDLL("/opt/questasim_6.4/questasim/linux/libucdb.so")

Try 'open( "libucdb.so", "rb" )' to see if you're looking in the right
place.
--
http://mail.python.org/mailman/listinfo/python-list


Re: atomic increment

2008-08-26 Thread Frank Millman
On Aug 26, 5:56 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Alexandru  Mosoi wrote:
> > how can i do an atomic read+increment? something like
>
> > with lock:
> >    old = atomic_int
> >    atomic_int += 1
>
> > but in one operation
>
> As above - the lock (under the assumption that it is actually a
> threading.Lock) will ensure that.
>
> Diez

Just out of interest, would the following, without a lock, be safe?

old, atomic_int = atomic_int, atomic_int+1

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


Re: Struct class random access

2008-08-26 Thread castironpi
On Aug 26, 12:41 am, castironpi <[EMAIL PROTECTED]> wrote:
> On Aug 25, 11:47 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> > On Mon, 25 Aug 2008 14:49:14 -0700, castironpi wrote:
> > > I'm interested in the speed benefit, so you don't have to reconstruct
> > > the entire 'record' just to read/write one 'field'.  How in ctypes?
>
> > Only the field accessed is converted.
>
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
> I know that.  I was asking how to write 'unpack_from( buf, off, 2 )',
> when buf is a non-ctypes buffer.

The code with ctypes is more elegant than I thought.

from ctypes import *
prototype= PYFUNCTYPE( c_int, py_object, POINTER(c_void_p),
POINTER(c_uint) )
PyObject_AsWriteBuffer= prototype( ( "PyObject_AsWriteBuffer",
pythonapi ) )
def refas( buf, offset, tp ):
''' return an instance of |tp| that refers to |offset| bytes into
buffer |buf| '''
_b, _s= c_void_p(0), c_uint(0)
PyObject_AsWriteBuffer( buf, byref(_b), byref(_s) ) #should return
0
c= cast( _b.value+ offset, POINTER( tp ) )
return c.contents

'tp' can be any class that is derived from ctypes.Structure.  'buf'
can be any object that supports the buffer protocol, including
'mmap'.  Remember when mapping pointers to store offsets, not memory
addresses.

I'd like to know how supported this is considered to be, across
platforms and versions.  Can I rely on this in the future?
--
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes: loading .so file on Linux

2008-08-26 Thread Paddy
On Aug 23, 2:33 pm, Paddy <[EMAIL PROTECTED]> wrote:
> Hi,
> I am am falling at the first hurdle when trying to access a library
> using ctypes.
>
> I have a file libucdb.so which the file command says is shared object,
> but I cannot get it to load:
>
> Any help would be appreciated:
>
> dmccarthy: file /opt/questasim_6.4/questasim/linux/libucdb.a /opt/
> questasim_=
> 6.4/questasim/linux/libucdb.so
> /opt/questasim_6.4/questasim/linux/libucdb.a:  current ar archive
> /opt/questasim_6.4/questasim/linux/libucdb.so: ELF 32-bit LSB shared
> object,=
>  Intel 80386, version 1 (SYSV), not stripped
> dmccarthy: python
> ActivePython 2.5.1.1 (ActiveState Software Inc.) based on
> Python 2.5.1 (r251:54863, May  2 2007, 08:46:07)
> [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> cdll.LoadLibrary("libc.so.6")
>
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'cdll' is not defined>>> from ctypes import *
> >>> ^[[A^[[A
>
>     ^e "", line 1
> SyntaxError: invalid syntax>>> cdll.LoadLibrary("libc.so.6")
>
> >>> 
> cdll.LoadLibrary("libucdb.so")
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/software/unix-soft/linux/ActivePython-2.5.1.1-linux-x86_64/
> lib/pyth=
> on2.5/ctypes/__init__.py", line 423, in LoadLibrary
>     return self._dlltype(name)
>   File "/software/unix-soft/linux/ActivePython-2.5.1.1-linux-x86_64/
> lib/pyth=
> on2.5/ctypes/__init__.py", line 340, in __init__
>     self._handle =3D _dlopen(self._name, mode)
> OSError: libucdb.so: cannot open shared object file: No such file or
> directo=
> ry>>> cdll.LoadLibrary("libc.so.6")
>
> >>> libc =3D 
> CDLL("libc.so.6")
> >>> libc
>
> >>> libc =3D 
> CDLL("libucdb.so")
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/software/unix-soft/linux/ActivePython-2.5.1.1-linux-x86_64/
> lib/pyth=
> on2.5/ctypes/__init__.py", line 340, in __init__
>     self._handle =3D _dlopen(self._name, mode)
> OSError: libucdb.so: cannot open shared object file: No such file or
> directo=
> ry>>> libc =3D CDLL("/opt/questasim_6.4/questasim/linux/libucdb.so")
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/software/unix-soft/linux/ActivePython-2.5.1.1-linux-x86_64/
> lib/pyth=
> on2.5/ctypes/__init__.py", line 340, in __init__
>     self._handle =3D _dlopen(self._name, mode)
> OSError: /opt/questasim_6.4/questasim/linux/libucdb.so: cannot open
> shared o=
> bject file: No such file or directory>>> ^[[A
>
>   File "", line 1
>     ^
> SyntaxError: invalid syntax
>
>
>
> - Paddy.

Any help would be appreciated.

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


Re: Extracting path of a program from a list.

2008-08-26 Thread Gabriel Genellina
En Wed, 27 Aug 2008 01:15:58 -0300, aditya shukla  
<[EMAIL PROTECTED]> escribi�:


I wanna know how can i extract path of a program whose path i have added  
to

the PATH variable.

This is what i have done

import os

x=os.getenv("PATH")

print x


%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\Program

Files\Microsoft SQL Server\90\Tools\binn\;C:\Program
Files\QuickTime\QTSystem\;C:\folder1\folder2\prog

Now i have to extract the path of my program ie  
(C:\folder1\folder2\prog) .I

mean i can split the string using

y=x.split(';')

a=y[-1]

but i dont wanna do this way ,i  wanna search for my program from this  
list

and then return its path


Can't you get the program name and path from the place you got it  
originally, before adding it to the PATH variable?

Or store it in some other place. I think it's a lot safer that way.

Anyway, once you split the PATH, you get a list. You should iterate over  
the list looking if your program is located on each directory... Something  
like this:


path = os.getenv("PATH")
dirs = path.split(os.pathsep)
for dir in dirs:
  fullfn = os.path.join(dir, your_application_name_including_exe_extension)
  if os.path.isfile(fullfn):
# found

--
Gabriel Genellina

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

Tkinter Unix and Windows incompatibility

2008-08-26 Thread akineko
Hello everyone,

I'm trying to create custom Tkinter/Pmw widgets for my project.
After testing my widgets under Unix (Solaris), I have tried them under
Windows and I got a surprise.

The widgets came out differently.
The following simple code snippet demonstrates the difference:

root = Tk()

w = Canvas(root, width=12, height=12, bd=4, relief=RAISED,
bg='cyan')
w.create_rectangle(5,5,16,16,fill='blue', outline='black')
w.pack()

w2 = Canvas(root, width=12, height=12, bd=0, relief=RAISED,
bg='purple')
w2.create_oval(0,0,12+1,12+1,fill='blue', outline='')
w2.pack()

w3 = Canvas(root, width=32, height=32, bd=4, relief=RAISED,
bg='purple')
w3.create_oval(4+0,4+0,4+32+1,4+32+1,fill='blue', outline='')
w3.pack()

root.mainloop()

//

I noticed the difference because rectangle (or oval) object on the
canvas covers the entire canvas such that small differences in size
are very noticeable.
As Tkinter is a thin wrapper layer for Tk, I'm suspecting the
differences are rooted in Tk.
I'm using TK8.5 under Unix while Python under Windows uses TK8.4.

As I don't have any access to Python under Windows with TK8.5, I
cannot verify if this problem is fixed under TK8.5 for Windows.

//

So, here are my questions:
(1) Can anybody who has access to Python under Windows with TK8.5 to
verify if the problem is fixed.
If the problem is fixed, rectangle and ovals are inscribed to the
canvas boundary nicely.
If not, you see the rectangle is off by one pixel and the radius is
one pixel larger, I think. The boundary width is also not correct
(right side is one pixel wider).
(2) As the official distribution of Python under Windows uses TK8.4,
what is the best approach to make my widgets to work correctly under
both environment?
 - I could use sys.platform to code differently so that they look the
same.
  - I'm afraid this creates a problem when TK8.5 is finally introduced
to Python under Windows.

Any suggestions?

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


Re: floating point arithmetic

2008-08-26 Thread Gabriel Genellina

En Tue, 26 Aug 2008 18:11:30 -0300, fred8865 <[EMAIL PROTECTED]> escribi�:


I understand that due to different arithmetic used in floating points
they are just approximations. Hence, 180/100=1 in my python interpreter.
How can I tackle this problem of inaccurate floating point numbers?
thank you


In the current Python versions (2.2 and up), 180/100 means integer  
division (because both operands are integer).
If you want a floating point result, use 180.0/100 or  
float(some_variable)/100


Starting with Python 3.0, the / operator will return a floating point  
result ("true division"). So in that Python version, 180/100 gives 1.8
To enable that behavior on Python 2.x, execute "from __future__ import  
division":



180/100

1

from __future__ import division
180/100

1.8

In any Python version, 180//100 always means integer division:


180//100

1

--
Gabriel Genellina

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

Re: Identifying the start of good data in a list

2008-08-26 Thread Scott David Daniels

[EMAIL PROTECTED] wrote:

I have a list that starts with zeros, has sporadic data, and then has
good data. I define the point at  which the data turns good to be the
first index with a non-zero entry that is followed by at least 4
consecutive non-zero data items (i.e. a week's worth of non-zero
data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9], I would define the point at which data turns good to be 4 (1
followed by 2, 3, 4, 5).

I have a simple algorithm to identify this changepoint, but it looks
crude: is there a cleaner, more elegant way to do this?

flag = True
i=-1
j=0
while flag and i < len(retHist)-1:
i += 1
if retHist[i] == 0:
j = 0
else:
j += 1
if j == 5:
flag = False

del retHist[:i-4]

Thanks in advance for your help

Thomas Philips



Here is one that can go iterator-to-iterator:

def started(source):
src = iter(source)
lead = []
for x in src:
if x:
lead.append(x)
if len(lead) == 5:
return itertools.chain(lead, src)
else:
lead = []


print list(started([0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))


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


Re: Memory Leak?

2008-08-26 Thread Gabriel Genellina
En Tue, 26 Aug 2008 23:27:45 -0300, Kevin McKinley <[EMAIL PROTECTED]>  
escribi�:


So i've complete my first program with a GUI interface.  I've noticed  
that everytime  i click a tab or button the amount of memory the program  
takes up goes up by 50-200 kb.  The program will start off at 4.5mb and  
by the time i'm done it can get up over 10 or 15 mb.  The program will  
start running little slower also.  Is this a sign that i might have done  
something wrong?


Probably. Unable to tell more without looking at the code.
Try to remove things from your current version until you get something  
that don't leak memory anymore (and then you know what was the cause) or  
it's small enough to post here.


--
Gabriel Genellina

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

Re: python multitask

2008-08-26 Thread Gabriel Genellina
En Tue, 26 Aug 2008 11:50:04 -0300, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribi�:



Hi !
I want use many comands in same python script .
I want to use openoffice and pyuno .
I try this

cmdoo="openoffice.org -accept='socket,host=localhost,port=2002;urp;'"
subprocess.call(cmdoo, shell=True)

but i need to execute another comand and need to stop subprocess


Instead of subprocess.call, use subprocess.Popen and later wait() for the  
processes to finish.


--
Gabriel Genellina

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

Re: Setting my Locale

2008-08-26 Thread Gabriel Genellina
En Tue, 26 Aug 2008 07:52:21 -0300, Robert Rawlins  
<[EMAIL PROTECTED]> escribi�:



I'm running python 2.5 on a Debian based system and I'm looking for your
advice on how to set the locale for my application. I've read through the
locale module documentation http://docs.python.org/lib/module-locale.html
and tried a couple of the examples but can't seem to get it working.


For instance, when I attempt to run the following code:


import locale

locale.setlocale(locale.LC_ALL, 'de_DE')


I get an exception raised by the application which says:


Traceback (most recent call last):

  File "locale_test.py", line 2, in 

locale.setlocale(locale.LC_ALL, 'de_DE')

  File "/usr/lib/python2.5/locale.py", line 478, in setlocale

return _setlocale(category, locale)

locale.Error: unsupported locale setting


My questions are; what would be causing this error? Do I need any  
additional
packages installed on the system for this locale support to work  
properly?


Probably you don't have support for 'de_DE' locale.
Try using locale.setlocale(locale.LC_ALL, '')
and see what you get in response.


How can I get a list of available locales?


I'd like to know how to retrieve that too...

--
Gabriel Genellina

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

Re: Ctypes module - looking for a way to dynamically call exported function from a set of dlls

2008-08-26 Thread Gabriel Genellina

En Tue, 26 Aug 2008 07:42:50 -0300, <[EMAIL PROTECTED]> escribi�:


Hi,

I'm using the ctypes module to load my dlls.

I have some 10 dlls the names of those are passed to a fucntion which
then loads the passed dll.

Now every dll has a getversion function.
eg: A.dll, B.dll, C.dll are the dlls
and GetVersion functions are as:
A_getVersion(), B_getVersion(),
C_getVesion()



The functionality I'm lookking for is that depending on the dll passed
the right getVersion should be passed.

I'm able to load the all the dlls passed to the function but I'm not
able to call the function names dynamically


Use getattr - same as with any other object.
Suppose some_dll is your loaded DLL, then:

function = getattr(some_dll, function_name)

--
Gabriel Genellina

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

Extracting path of a program from a list.

2008-08-26 Thread aditya shukla
Hello folks,

I wanna know how can i extract path of a program whose path i have added to
the PATH variable.

This is what i have done

import os

x=os.getenv("PATH")

print x

>>%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\Program
Files\Microsoft SQL Server\90\Tools\binn\;C:\Program
Files\QuickTime\QTSystem\;C:\folder1\folder2\prog

Now i have to extract the path of my program ie (C:\folder1\folder2\prog) .I
mean i can split the string using

y=x.split(';')

a=y[-1]

but i dont wanna do this way ,i  wanna search for my program from this list
and then return its path

Please help me on this.

Thanks in advance.


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

Re: Retrieve Win32 domain name

2008-08-26 Thread Gabriel Genellina
En Tue, 26 Aug 2008 05:39:55 -0300, Salim Fadhley <[EMAIL PROTECTED]>  
escribi�:



I'm looking for a method to retrieve a Windows Domain name (not a DNS
Domain name).

I know this can be done by simply reading an environment variable,
however on the machines I need to work with sometimes the environment
variables can be messed-up and are not trustworthy.

Is there somebody who knows the Win32 library who can point me to the
function I need? The Win32Net seems to contain a whole load of
functions for manipulating Windows networking resources, however I
couldn't find a function which simply returned information about the
local computer.


You didn't search enough then: try win32net.NetWkstaGetInfo(None, 100)

--
Gabriel Genellina

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

Re: Python + Mac Help

2008-08-26 Thread Benjamin Kaplan
On Tue, Aug 26, 2008 at 11:07 PM, William Purcell <[EMAIL PROTECTED]
> wrote:

> FYI...I found the site that I installed from besides MacScience. I think
> that I have installed just about everything on this site.
> http://www.pythonmac.org/packages/py25-fat/index.html
>
>
> On Tue, Aug 26, 2008 at 10:05 PM, William Purcell <
> [EMAIL PROTECTED]> wrote:
>
>> I am new to the Mac/OS X world. I am trying to get Python set up with
>> Numpy, Scipy, Matplotlib, and wxPython. It seems that everything is working
>> fine except Scipy. To explain my problem, it is probably best to see the
>> following
>>
>> Simply trying to import Scipy...
>> 
>> william-purcells-macbook:~ william$ python -c "import scipy"
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> ImportError: No module named scipy
>> 
>>
>> Importing pylab works fine
>> 
>> william-purcells-macbook:~ william$ python -c "import pylab"
>> william-purcells-macbook:~ william$
>> 
>>
>> My Python version...
>> 
>> william-purcells-macbook:~ william$ python -V
>> Python 2.5
>> 
>>
>> But when I run 'ipython -python -p scipy' everything seems to be working
>> great. Except that it seems to be a little different version of Python
>> maybe.
>> 
>> Last login: Tue Aug 26 19:43:32 on ttys000
>> william-purcells-macbook:~ william$ ipython -pylab -p scipy
>> Leopard libedit detected.
>> SciPy profile successfully loaded.
>> Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
>> Type "copyright", "credits" or "license" for more information.
>>
>> IPython 0.8.3.svn.r3001 -- An enhanced Interactive Python.
>> ? -> Introduction and overview of IPython's features.
>> %quickref -> Quick reference.
>> help  -> Python's own help system.
>> object?   -> Details about 'object'. ?object also works, ?? prints more.
>>
>>   Welcome to pylab, a matplotlib-based Python environment.
>>   For more information, type 'help(pylab)'.
>>
>> =
>>
>> I installed the Macscience Scipy Superpack to try to get everything I
>> needed. I have also tried a couple random installs from other places, but
>> I'm not for sure exactly what I have going on. Can someone point me in a
>> direction to start trouble shooting this? I have been trying to get this
>> working off and on for about three months, but have not had the time to dig
>> in and learn a new OS (I have Ubuntu installed also, which is what I'm used
>> to).
>>
>> Thanks for your time,
>> Bill
>>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list


SciPy won't work with Apple's Python. You have to install Python from
python.org to use it.
--
http://mail.python.org/mailman/listinfo/python-list

Re: What's your first choice if you have to write a C module for python?

2008-08-26 Thread Carl Banks
On Aug 26, 8:19 am, 一首诗 <[EMAIL PROTECTED]> wrote:
> What's your first choice when you have write a C/C++ module for Python?


1. Plain C code
2. Implement my own C extension code generator in Python
3. ctypes
...
...
Infinity. SWIG


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

Re: Non-evil multithreaded WSGI server?

2008-08-26 Thread Gabriel Genellina
En Tue, 26 Aug 2008 03:20:53 -0300, Gerhard Häring <[EMAIL PROTECTED]>  
escribi�:



In a recent experiment I've done this:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from wsgiref.simple_server import make_server, demo_app
from SocketServer import ThreadingMixIn

# Let's make a WSGI server that can use multiple threads.

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
 """Handle requests in a separate thread."""

# Evil! ;-)
from wsgiref.simple_server import WSGIServer as MyWSGIServer
MyWSGIServer.__bases__ = (ThreadedHTTPServer,)

Now I wonder if there's a less evil way that does not involve copy &  
paste of the WSGIServer code (only couple of lines, but I hate  
duplication)?!


I'm not sure I understand completely the question - does the code below  
work for you?


class MyWSGIServer(ThreadingMixIn, wsgiref.simple_server.WSGIServer):
pass

def make_server(
host, port, app, server_class=MyWSGIServer,  
handler_class=WSGIRequestHandler):
return wsgiref.simple_server.make_server(host, port, app,  
server_class, handler_class)


--
Gabriel Genellina

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

Re: Need help with extension modules built in debug mode

2008-08-26 Thread Gabriel Genellina

En Tue, 26 Aug 2008 01:11:10 -0300, <[EMAIL PROTECTED]> escribi�:


I've come to the conclusion that posting about Embedded Python on the
Python forums is a complete waste of time.  I hope I can get some
useful insights here.

I'm looking for some help with extension modules built using Visual
Studio. I'm using the simple extension module example "hello" (taken
from the "Programming Python" book). I'm building it successfully in
both release and debug mode using a Visual Studio project.

I can successfully import the release build of the module into the
release build of Python.  For example:

[E:\]python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more
information.
>>> import hello
>>> hello.message("Bob")
'Hello, Bob'
>>> quit()


I cannot, however, load the debug build of the exact same code (stored
in the exact same location) into the debug build of Python:


Does anybody know what tricks or coding magic might be required to get
debug extension modules to load into debug Python?


In debug mode, python looks for hello_d.pyd - NOT hello.pyd.
Note that neither hello.dll nor hello_d.dll are recognized anymore since  
version 2.5


--
Gabriel Genellina

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

Re: Python + Mac Help

2008-08-26 Thread William Purcell
FYI...I found the site that I installed from besides MacScience. I think
that I have installed just about everything on this site.
http://www.pythonmac.org/packages/py25-fat/index.html

On Tue, Aug 26, 2008 at 10:05 PM, William Purcell <[EMAIL PROTECTED]
> wrote:

> I am new to the Mac/OS X world. I am trying to get Python set up with
> Numpy, Scipy, Matplotlib, and wxPython. It seems that everything is working
> fine except Scipy. To explain my problem, it is probably best to see the
> following
>
> Simply trying to import Scipy...
> 
> william-purcells-macbook:~ william$ python -c "import scipy"
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named scipy
> 
>
> Importing pylab works fine
> 
> william-purcells-macbook:~ william$ python -c "import pylab"
> william-purcells-macbook:~ william$
> 
>
> My Python version...
> 
> william-purcells-macbook:~ william$ python -V
> Python 2.5
> 
>
> But when I run 'ipython -python -p scipy' everything seems to be working
> great. Except that it seems to be a little different version of Python
> maybe.
> 
> Last login: Tue Aug 26 19:43:32 on ttys000
> william-purcells-macbook:~ william$ ipython -pylab -p scipy
> Leopard libedit detected.
> SciPy profile successfully loaded.
> Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
> Type "copyright", "credits" or "license" for more information.
>
> IPython 0.8.3.svn.r3001 -- An enhanced Interactive Python.
> ? -> Introduction and overview of IPython's features.
> %quickref -> Quick reference.
> help  -> Python's own help system.
> object?   -> Details about 'object'. ?object also works, ?? prints more.
>
>   Welcome to pylab, a matplotlib-based Python environment.
>   For more information, type 'help(pylab)'.
>
> =
>
> I installed the Macscience Scipy Superpack to try to get everything I
> needed. I have also tried a couple random installs from other places, but
> I'm not for sure exactly what I have going on. Can someone point me in a
> direction to start trouble shooting this? I have been trying to get this
> working off and on for about three months, but have not had the time to dig
> in and learn a new OS (I have Ubuntu installed also, which is what I'm used
> to).
>
> Thanks for your time,
> Bill
>
--
http://mail.python.org/mailman/listinfo/python-list

Python + Mac Help

2008-08-26 Thread William Purcell
I am new to the Mac/OS X world. I am trying to get Python set up with Numpy,
Scipy, Matplotlib, and wxPython. It seems that everything is working fine
except Scipy. To explain my problem, it is probably best to see the
following

Simply trying to import Scipy...

william-purcells-macbook:~ william$ python -c "import scipy"
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named scipy


Importing pylab works fine

william-purcells-macbook:~ william$ python -c "import pylab"
william-purcells-macbook:~ william$


My Python version...

william-purcells-macbook:~ william$ python -V
Python 2.5


But when I run 'ipython -python -p scipy' everything seems to be working
great. Except that it seems to be a little different version of Python
maybe.

Last login: Tue Aug 26 19:43:32 on ttys000
william-purcells-macbook:~ william$ ipython -pylab -p scipy
Leopard libedit detected.
SciPy profile successfully loaded.
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
Type "copyright", "credits" or "license" for more information.

IPython 0.8.3.svn.r3001 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help  -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

  Welcome to pylab, a matplotlib-based Python environment.
  For more information, type 'help(pylab)'.

=

I installed the Macscience Scipy Superpack to try to get everything I
needed. I have also tried a couple random installs from other places, but
I'm not for sure exactly what I have going on. Can someone point me in a
direction to start trouble shooting this? I have been trying to get this
working off and on for about three months, but have not had the time to dig
in and learn a new OS (I have Ubuntu installed also, which is what I'm used
to).

Thanks for your time,
Bill
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python and database unittests

2008-08-26 Thread alex23
Daniel <[EMAIL PROTECTED]> wrote:
> Does anyone know about a module that acts as a database stub for
> python unittests?

It's not database-specific, but the Mock module should help you here:

http://python-mock.sourceforge.net/

There's even an example on that page for mocking a database.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying the start of good data in a list

2008-08-26 Thread Terry Reedy



Matthew Fitzgibbons wrote:

[EMAIL PROTECTED] wrote:




reHist = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
count = 0
for i, d in enumerate(reHist):
if d == 0:
count = 0
else:
count += 1
if count == 5:
break
else:
raise Exception("No data found")
reHist = reHist[i-4:]
print reHist


This is what I would have suggested, except that the 'if count' test 
should be left under the else clause, as in the original, so I consider 
it the best of the responses ;-)


I thought of the repeated slicing alternative, but it would be slightly 
slower.  However, for occasional runs, the difference would be trivial.


Worrying about what Psyco does for this problem is rather premature 
optimization.


My quarter's worth

tjr


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


Re: JSON from Python mysqldb

2008-08-26 Thread jpuopolo
On Aug 26, 3:15 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> jpuopolo wrote:
> > All:
>
> > I am using Python to read some records from the MySQL database. I am
> > using the mysqldb library, and things are working well.
>
> > Now, I would like to pass back the results of the query to a Web-based
> > front end, and I would like to use JSON. Is there a library/example of
> > creating a JSON array from a mysqldb row or row set?
>
> > Thanks,
> > jpuopolo
>
> Google turns up several high quality links, just look for 'python json'.
>
> -Larry

Larry:

Thank you for the reply. Unfortunately, some of the libs the Google
search returns bail when
converting a database record into a JSON object. I may be using it/
them incorrectly, so I'll post
results to this newsgroup accordingly.

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


Utah Open Source Conference, August 28-30

2008-08-26 Thread jazbees
Apologies if this is too regional and not of interest to the broader
Python community, but I felt I should pass along the link to an event
I stumbled across today:

http://2008.utosc.com/pages/home/

Some talks on the schedule are either directly about Python ("Vim and
Python", "Using Lasers, Webcams, and Python to Create a Halloween Game
in my Driveway") or about related topics ("A Django Miscellany"), not
to mention all the general open-source topics.  If you're in the
neighborhood of Salt Lake Community College later this week and have
the time, it might be worth a visit.

I'm not connected with the event in any way.  Just found it and wanted
to share the info.  Cheers!

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


Re: floating point arithmetic

2008-08-26 Thread Terry Reedy



John Machin wrote:

On Aug 27, 7:11 am, fred8865 <[EMAIL PROTECTED]> wrote:


I understand that due to different arithmetic used in floating points
they are just approximations. Hence, 180/100=1 in my python interpreter.


It's not "hence". What you are seeing is truncating integer division.


How can I tackle this problem of inaccurate floating point numbers?



180 / 100

1

180 / 100.

1.8

180 / float(100)

1.8

from __future__ import division
180 / 100

1.8
--


Or start using 3.0, which fixed this ;-)

>>> 180/100
1.8

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


Re: Identifying the start of good data in a list

2008-08-26 Thread tkpmep
On Aug 26, 7:23 pm, Emile van Sebille <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I have a list that starts with zeros, has sporadic data, and then has
> > good data. I define the point at  which the data turns good to be the
> > first index with a non-zero entry that is followed by at least 4
> > consecutive non-zero data items (i.e. a week's worth of non-zero
> > data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
> > 9], I would define the point at which data turns good to be 4 (1
> > followed by 2, 3, 4, 5).
>
> > I have a simple algorithm to identify this changepoint, but it looks
> > crude: is there a cleaner, more elegant way to do this?
>
>  >>> for ii,dummy in enumerate(retHist):
> ...     if 0 not in retHist[ii:ii+5]:
> ...         break
>
>  >>> del retHist[:ii]
>
> Well, to the extent short and sweet is elegant...
>
> Emile

This is just what the doctor ordered. Thank you, everyone, for the
help.

Sincerely

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


Re: sum up numbers in a list

2008-08-26 Thread Terry Reedy



sharon kim wrote:


is there a way to sum up all the numbers in a list?


>>> help(sum)
sum(...)
sum(iterable[, start]) -> value

Returns the sum of an iterable of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the iterable is
empty, returns start.

>>> L=[28,39,20,78490,37373,22,2,33,4,5]
>>> sum(L)
116016

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


Re: Date Comparison and Manipulation Functions?

2008-08-26 Thread Benjamin Kaplan
On Tue, Aug 26, 2008 at 9:24 PM, W. eWatson <[EMAIL PROTECTED]> wrote:

> John Machin wrote:
>
>> On Aug 27, 10:21 am, "W. eWatson" <[EMAIL PROTECTED]> wrote:
>>
>>> I'm using IDLE for Python 2.4, and put pfydate distribution in
>>> C:\Python24\Lib\site-packages\pfydate, as required by the
>>>  page.
>>> How to install pyfdate.
>>>
>>> Save pyfdate.py into your PythonNN/Lib/site-packages directory.
>>> I copied it into C:\Python24\Lib\site-packages\pfydate
>>>
>>
>> If that means that you ended up with
>>   C:\Python24\Lib\site-packages\pfydate\pyfdate.py
>> then you have *not* followed the instructions "Save pyfdate.py into
>> your PythonNN/Lib/site-packages directory".
>> You need to end up with
>>   C:\Python24\Lib\site-packages\pyfdate.py
>>
> None of the folders in C:\Python24\Lib\site-packages\ have py as a suffix
> (as seen either by the IDLE path browser or XP). My folder is exactly
> C:\Python24\Lib\site-packages\pfydate in XP and it contains about 12 py
> files.
> There are exactly three folders under
> C:\Python24\Lib\site-packages\ according to the IDLE path browser. This
> does not agree with XP, which has:
> Numeric
> pfydate
> scipy
> numpy
> PIL
>
>>

You're not supposed to use the entire folder, just the pyfdate.py file
inside the folder.
--
http://mail.python.org/mailman/listinfo/python-list

Memory Leak?

2008-08-26 Thread Kevin McKinley
So i've complete my first program with a GUI interface.  I've noticed that 
everytime  i click a tab or button the amount of memory the program takes up 
goes up by 50-200 kb.  The program will start off at 4.5mb and by the time i'm 
done it can get up over 10 or 15 mb.  The program will start running little 
slower also.  Is this a sign that i might have done something wrong?  



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


Re: Python Strinh Immutability Broken!

2008-08-26 Thread Terry Reedy



Hendrik van Rooyen wrote:


Terry Reedy:



Which essentially is the bytearray type of 3.0.


How does it differ from plain old array.array(b,”The quick brown fox”)?


The typecode must be quoted as 'b'.
In 3.0, strings become unicode, so an added b prefix is needed.
>>> import array
>>> a = array.array('b', b'fox')
>>> b=bytearray(b'fox')

As to your question: the underlying implementation of bytearrays is 
based on that of array('b')s. Bytearrays are built in so no import is 
needed.  Dir() shows that both have all sequence methods, but arrays 
also have list methods, while bytearrays also have string/bytes methods.


They have different representations
>>> a
array('b', [102, 111, 120])
>>> b
bytearray(b'fox')

Bytearrays, like lists/arrays, have the __setitem__ method needed to 
make them mutable via indexing.


>>> a[0]=ord(b'b')
>>> b[0]=ord(b'b')
>>> a
array('b', [98, 111, 120])
>>> b
bytearray(b'box')

Arrays can extend bytearrays but not vice versa.  This may be a glitch.

>>> c = a + b
Traceback (most recent call last):
  File "", line 1, in 
c = a + b
TypeError: can only append array (not "bytearray") to array
>>> c = b + a
>>> c
bytearray(b'boxbox')

Either can initialize the other

>>> d = array.array('b',c)
>>> d
array('b', [98, 111, 120, 98, 111, 120])
>>> c=bytearray(d)
>>> c
bytearray(b'boxbox')

So if one does more that the common mutable sequence operations, there 
is a basis for choosing one or the other.


Terry Jan Reedy

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


Re: iterparse and unicode

2008-08-26 Thread George Sakkis
On Aug 25, 4:45 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> George Sakkis wrote:
> > It depends on what you mean by "compatible"; e.g. you can't safely do
> > [s.decode('utf8') for s in strings] if you have byte strings mixed
> > with unicode.
>
> why would you want to decode strings given to you by a library that
> returns decoded strings?
>
> if you meant to write "encode", you can indeed safely do
> [s.encode('utf8') for s in strings] as long as all strings are returned
> by an ET implementation.

I was replying to the general assertion that "in 2.x ASCII byte
strings and unicode strings are compatible", not specifically about
the strings returned by ET.

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


Re: Enhanced property decorator

2008-08-26 Thread Benjamin
On Aug 25, 9:00 pm, Daniel <[EMAIL PROTECTED]> wrote:
> On 25 Aug, 21:52, Benjamin <[EMAIL PROTECTED]> wrote:
>
> > ... I think Python 2.6 may have
> > want you want:
>
> > class A(object):
>
> >     @property
> >     def my_prop(): return self._prop
>
> >     @my_prop.setter
> >     def my_prop(prop): self._prop = prop
>
> >     @my_prop.deleter
> >     def my_prop(): del self._prop
>
> Hmm, interesting. I wonder if it suppports setting the doc-string in a
> similar way? I'll have to look into that. Thanks for pointing this
> out.

It takes the getter's docstring as usual.
>
> ~ Daniel

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


Environment variables

2008-08-26 Thread aditya shukla
Hello folks,


How can i create environment variables using python?






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

Re: Date Comparison and Manipulation Functions?

2008-08-26 Thread W. eWatson

John Machin wrote:

On Aug 27, 10:21 am, "W. eWatson" <[EMAIL PROTECTED]> wrote:

I'm using IDLE for Python 2.4, and put pfydate distribution in
C:\Python24\Lib\site-packages\pfydate, as required by the
 page.
How to install pyfdate.

 Save pyfdate.py into your PythonNN/Lib/site-packages directory.
I copied it into C:\Python24\Lib\site-packages\pfydate


If that means that you ended up with
   C:\Python24\Lib\site-packages\pfydate\pyfdate.py
then you have *not* followed the instructions "Save pyfdate.py into
your PythonNN/Lib/site-packages directory".
You need to end up with
   C:\Python24\Lib\site-packages\pyfdate.py
None of the folders in C:\Python24\Lib\site-packages\ have py as a suffix 
(as seen either by the IDLE path browser or XP). My folder is exactly 
C:\Python24\Lib\site-packages\pfydate in XP and it contains about 12 py files.

There are exactly three folders under
C:\Python24\Lib\site-packages\ according to the IDLE path browser. This does 
not agree with XP, which has:

Numeric
pfydate
scipy
numpy
PIL


If in doubt, get to a command prompt and type
   dir C:\Python24\Lib\site-packages\pfydate*
and tell us what you see.


Execution in IDLE produced:
-
Traceback (most recent call last):
   File
"C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\date_example.py",
line 1, in ?
 from pyfdate import *
ImportError: No module named pyfdate
-
Looking in the Path Browser, I don't see pyfdate. I see PIL package and
scipy package.



--
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Re: Return a string result with out breaking loop

2008-08-26 Thread castironpi
On Aug 26, 11:46 am, Andrew <[EMAIL PROTECTED]> wrote:
...
>          results = change_handle
>          for action, files in results:
>              full_filename = os.path.join(path_to_watch, files)
>              theact = ACTIONS.get(action, "Unknown")
>              out2 = str(full_filename) +  " " + str(theact)
>          yield str(out2)

I think you have the yield in the wrong place.  Should you tab it over
one?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Micro-threading PEP proposal announcement

2008-08-26 Thread Terry Reedy



Pau Freixes wrote:


When can I read this PEP ? I'm interesting



I wanted to make everybody aware that I've posted a (rather long and
involved) PEP proposal for adding micro-threading to Python on
python-ideas for feedback and review.


Python-ideas is another mailing list at python.org.  You can also read 
and post via the list-newsgroups gateway news.gmane.org as 
gmane.comp.python.ideas.


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


Re: Date Comparison and Manipulation Functions?

2008-08-26 Thread John Machin
On Aug 27, 10:21 am, "W. eWatson" <[EMAIL PROTECTED]> wrote:
>
> I'm using IDLE for Python 2.4, and put pfydate distribution in
> C:\Python24\Lib\site-packages\pfydate, as required by the
>  page.
> How to install pyfdate.
>
>  Save pyfdate.py into your PythonNN/Lib/site-packages directory.
> I copied it into C:\Python24\Lib\site-packages\pfydate

If that means that you ended up with
   C:\Python24\Lib\site-packages\pfydate\pyfdate.py
then you have *not* followed the instructions "Save pyfdate.py into
your PythonNN/Lib/site-packages directory".
You need to end up with
   C:\Python24\Lib\site-packages\pyfdate.py

If in doubt, get to a command prompt and type
   dir C:\Python24\Lib\site-packages\pfydate*
and tell us what you see.

>
> Execution in IDLE produced:
> -
> Traceback (most recent call last):
>File
> "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\date_example.py",
> line 1, in ?
>  from pyfdate import *
> ImportError: No module named pyfdate
> -
> Looking in the Path Browser, I don't see pyfdate. I see PIL package and
> scipy package.
--
http://mail.python.org/mailman/listinfo/python-list


Re: why in returns values for array and keys for dictionary

2008-08-26 Thread Terry Reedy



Lie wrote:


Anyway, there is two obvious choice when dealing with dictionary
looping: return the keys and return the key and value.

> The python designer thought...

The issue of whether there should be a default iterator and if so, which 
of the two obvious choices should be picked, was discussed on the py-dev 
list by several developers in addition to GvR.  'Yes, iterkeys' was the 
majority choice as the most useful for the most users.


The rationale for no default would have been 'explicit is better than 
implicit' and the easy prediction (proven true ;-) that either choice 
would be challenged.  Of course, no default would have been criticized 
also.


tjr

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


Re: Date Comparison and Manipulation Functions?

2008-08-26 Thread W. eWatson

[EMAIL PROTECTED] wrote:

check out Pyfdate: http://www.ferg.org/pyfdate

from pyfdate import *

t = Time().add(hours=14)
print "It is now", t.wdt

datestring1 = "2005/10/05" #year,month,day
datestring2 = "2002/09/22" #year,month,day
datestring3 = "2007/11/11" #year,month,day

year,month,day = numsplit(datestring1)  # split into integers
t1 = Time(year,month,day)
for datestring in (datestring2,datestring1,datestring3):
year,month,day = numsplit(datestring)
t2 = Time(year,month,day)

if t1 > t2:
print t1.isodate, "is later than  ", t2.isodate
elif t1 == t2:
print t1.isodate, "is the same as ", t2.isodate
elif t1 < t2:
print t1.isodate, "is earlier than", t2.isodate

print

t1 = Time(2000,2,28)
print "The date after", t1.d, "is", t1.plus(day=1).d
t1 = Time(2001,2,28)
print "The date after", t1.d, "is", t1.plus(day=1).d
t1 = Time(2004,2,28)
print "The date after", t1.d, "is", t1.plus(day=1).d

print
datestring1 = "2005/10/05 20:10:08"
datestring2 = "2005/10/05 20:10:06"
datestring3 = "2005/10/05 20:10:09"

t1 = Time(*numsplit(datestring1))
for datestring in (datestring2,datestring1,datestring3):
t2 = Time(*numsplit(datestring))

if t1 > t2:
print t1.d, t1.civiltime2, "is later than  ", t2.d, 
t2.civiltime2
elif t1 == t2:
print t1.d, t1.civiltime2, "is the same as ", t2.d, 
t2.civiltime2
elif t1 < t2:
print t1.d, t1.civiltime2, "is earlier than", t2.d, 
t2.civiltime2
I'm using IDLE for Python 2.4, and put pfydate distribution in 
C:\Python24\Lib\site-packages\pfydate, as required by the 
 page.

How to install pyfdate.

Save pyfdate.py into your PythonNN/Lib/site-packages directory.
I copied it into C:\Python24\Lib\site-packages\pfydate

Execution in IDLE produced:
-
Traceback (most recent call last):
  File 
"C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\date_example.py", 
line 1, in ?

from pyfdate import *
ImportError: No module named pyfdate
-
Looking in the Path Browser, I don't see pyfdate. I see PIL package and 
scipy package.


Comments?

--
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Re: Return a string result with out breaking loop

2008-08-26 Thread Andrew
mmk guess I will have to look for alternate solutions for this project. 
Thank you all for your help


cheers Andrew!

Fredrik Lundh wrote:

Andrew wrote:

Yield returns the result I am looking for... however it does not 
continue looping. It does the same thing as return would


the XML-RPC protocol doesn't really support your use case; for each 
call, the client issues a complete request package, and the server 
produces a complete response in return.





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


Free huge source codes collection

2008-08-26 Thread Albertos
Hello, I've collected huge source codes collection of any kinds : work
with text files, database, GUI etc. You can download it here
http://freactor.com/get.php?file=Python
--
http://mail.python.org/mailman/listinfo/python-list


've collected huge source codes collection of any kinds

2008-08-26 Thread Albertos
Hello, I've collected huge source codes collection of any kinds : work
with text files, database, GUI etc.
You can download it here http://freactor.com/get.php?file=Python+source+code
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying the start of good data in a list

2008-08-26 Thread tdmj
On Aug 26, 5:49 pm, [EMAIL PROTECTED] wrote:
> I have a list that starts with zeros, has sporadic data, and then has
> good data. I define the point at  which the data turns good to be the
> first index with a non-zero entry that is followed by at least 4
> consecutive non-zero data items (i.e. a week's worth of non-zero
> data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
> 9], I would define the point at which data turns good to be 4 (1
> followed by 2, 3, 4, 5).
>
> I have a simple algorithm to identify this changepoint, but it looks
> crude: is there a cleaner, more elegant way to do this?
>
> flag = True
> i=-1
> j=0
> while flag and i < len(retHist)-1:
> i += 1
> if retHist[i] == 0:
> j = 0
> else:
> j += 1
> if j == 5:
> flag = False
>
> del retHist[:i-4]
>
> Thanks in advance for your help
>
> Thomas Philips

With regular expressions:

import re

hist = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
hist_str = ''.join(str(i) for i in hist)
match = re.search(r'[1-9]{5, }', hist_str)
hist = hist[-5:] if match is None else hist[match.start():]

Or slightly more concise:

import re

hist = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
match = re.search(r'[1-9]{5, }', ''.join(str(i) for i in hist))
hist = hist[-5:] if match is None else hist[match.start():]

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


Re: extract text from ods TableCell using odfpy

2008-08-26 Thread norseman

Ciaran Farrell wrote:

2008/8/26 norseman <[EMAIL PROTECTED]>:

frankentux wrote:

Ok. Sorted it out, but only after taking a round trip over
xml.minidom. Here's the working code:

#!/usr/bin/python
from odf.opendocument import Spreadsheet
from odf.opendocument import load
from odf.table import TableRow,TableCell
from odf.text import P
doc = load("/tmp/match_data.ods")
d = doc.spreadsheet
rows = d.getElementsByType(TableRow)
for row in rows[:2]:
   cells = row.getElementsByType(TableCell)
   for cell in cells:
   tps = cell.getElementsByType(P)
   if len(tps) > 0:
   for x in tps:
   print x.firstChild
--
http://mail.python.org/mailman/listinfo/python-list


=
cd /opt
find . -name "*odf*" -print
(empty)
cd /usr/local/lib/python2.5
find . -name "*odf*" -print
(empty)


OK - where is it? :)


Sorry. Stupid of me. The module is not part of the standard libary.
It's at http://opendocumentfellowship.com/projects/odfpy

Ciaran


==
I got the download and all went pretty well. Setup.py compiled OK and 
install put it where it belongs.


As a test I went to try odflint and keep getting a zlib not found error. 
It is installed (/usr/local/lib) and the python zlib things .py, .pyc 
and .pyo all seem present. Not sure what is happening.



I took a look at Python.2.5.2's  zipfile.py

statement:  import zlib   was changed to   import libz as zlib
 (ALL libs are prefixed with lib... by convention)
Problem below the test happens with or without my change.

Test I ran:

python
(sign on yah de yah yah)
import zipfile
zipfile.is_zipfile("zx")
False
zipfile.is_zipfile("zz.zip")
True
zipfile.is_zipfile("zx.zip")
False  (file non existent - no error generated, but answer correct)

Thus all returned correct answers.  Distro Python code runs as expected.

However:

odflint OOstuf2.odt   |\__
python /usr/local/bin/odflint OOstuf2.odt |/   Both return following:

Traceback (most recent call last):
  File "/usr/local/bin/odflint", line 213, in 
lint(sys.argv[1])
  File "/usr/local/bin/odflint", line 197, in lint
content = zfd.read(zi.filename)
  File "/usr/local/lib/python2.5/zipfile.py", line 498, in read
"De-compression requires the (missing) zlib module"
RuntimeError: De-compression requires the (missing) zlib module

Anybody:
What did I miss correcting?  Seems odflint only uses zipfile.references.

System: Slackware 10.2 on 2.4GgHz Laptop


Steve
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying the start of good data in a list

2008-08-26 Thread Emile van Sebille

[EMAIL PROTECTED] wrote:

I have a list that starts with zeros, has sporadic data, and then has
good data. I define the point at  which the data turns good to be the
first index with a non-zero entry that is followed by at least 4
consecutive non-zero data items (i.e. a week's worth of non-zero
data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9], I would define the point at which data turns good to be 4 (1
followed by 2, 3, 4, 5).

I have a simple algorithm to identify this changepoint, but it looks
crude: is there a cleaner, more elegant way to do this?


>>> for ii,dummy in enumerate(retHist):
... if 0 not in retHist[ii:ii+5]:
... break

>>> del retHist[:ii]

Well, to the extent short and sweet is elegant...

Emile

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


Re: Identifying the start of good data in a list

2008-08-26 Thread Mensanator
On Aug 26, 4:49 pm, [EMAIL PROTECTED] wrote:
> I have a list that starts with zeros, has sporadic data, and then has
> good data. I define the point at  which the data turns good to be the
> first index with a non-zero entry that is followed by at least 4
> consecutive non-zero data items (i.e. a week's worth of non-zero
> data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
> 9], I would define the point at which data turns good to be 4 (1
> followed by 2, 3, 4, 5).
>
> I have a simple algorithm to identify this changepoint, but it looks
> crude: is there a cleaner, more elegant way to do this?
>
>     flag = True
>     i=-1
>     j=0
>     while flag and i < len(retHist)-1:
>         i += 1
>         if retHist[i] == 0:
>             j = 0
>         else:
>             j += 1
>             if j == 5:
>                 flag = False
>
>     del retHist[:i-4]
>
> Thanks in advance for your help
>
> Thomas Philips

Here's my attempt:

LL = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

i = 0

while (ihttp://mail.python.org/mailman/listinfo/python-list


Re: What is class method?

2008-08-26 Thread Matthew Fitzgibbons

Medardo Rodriguez (Merchise Group) wrote:

On Tue, Aug 26, 2008 at 4:10 PM, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:

In Python, there's *no* relationship between classmethods and metaclasses.


In OOP the concept of meta-class has everything to do with class
methods, regardless if is in Python, SmallTalk or CLOSS. "classmethod"
decorator it's just a syntax sugar structure to define them. There is
no difference (conceptually) on "method1" and "method2":

class MetaXClass(type):
def Method1(self): pass
class Xclass(object):
__metaclass__ = MetaXClass
@classmethod
def Method2(self): pass



Not quite:

>>> class MetaXClass(type):
... def method1(self): pass
...
>>> class XClass(object):
... __metaclass__ = MetaXClass
... @classmethod
... def method2(self): pass
...
>>> xc = XClass()
>>> xc.method1
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'XClass' object has no attribute 'method1'
>>> xc.method2
>
>>>

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


Re: floating point arithmetic

2008-08-26 Thread fred8865
thanks guys

fred8865 wrote:

> Hi all,
> 
> I understand that due to different arithmetic used in floating points
> they are just approximations. Hence, 180/100=1 in my python interpreter.
> How can I tackle this problem of inaccurate floating point numbers?
> thank you
> 
> regards
> xtd

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


Re: Python LDAP

2008-08-26 Thread Juan
On 26 ago, 13:42, Michael Ströder <[EMAIL PROTECTED]> wrote:
> Juan wrote:
> >     self.conn = ldap.initialize(self.host, self.port)
>  > [..]
> > LDAPError: (2, 'No such file or directory')
>
> You have to pass in a LDAP URI as documented 
> here:http://python-ldap.sourceforge.net/doc/html/ldap.html#ldap.initialize
>
> Use of compability function ldap.open() is deprecated and might vanish
> in future versions of python-ldap.
>
> See also Demo/initialize.py in python-ldap's source distribution.
>
> Ciao, Michael.

Perfect! Thank you very much.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying the start of good data in a list

2008-08-26 Thread Matthew Fitzgibbons

[EMAIL PROTECTED] wrote:

I have a list that starts with zeros, has sporadic data, and then has
good data. I define the point at  which the data turns good to be the
first index with a non-zero entry that is followed by at least 4
consecutive non-zero data items (i.e. a week's worth of non-zero
data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9], I would define the point at which data turns good to be 4 (1
followed by 2, 3, 4, 5).

I have a simple algorithm to identify this changepoint, but it looks
crude: is there a cleaner, more elegant way to do this?

flag = True
i=-1
j=0
while flag and i < len(retHist)-1:
i += 1
if retHist[i] == 0:
j = 0
else:
j += 1
if j == 5:
flag = False

del retHist[:i-4]

Thanks in advance for your help

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



Maybe this will do?

reHist = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
count = 0
for i, d in enumerate(reHist):
if d == 0:
count = 0
else:
count += 1
if count == 5:
break
else:
raise Exception("No data found")
reHist = reHist[i-4:]
print reHist


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


SQL package

2008-08-26 Thread Juan
Hi

I am trying to write a little a script that can be configurable. This
script should access to a database, that can be of any type (MySQL,
Postgres, SQLite, MS, etc).It has only to perform 2 or 3 simple plain
SQL queries. Hi have tested SQLAlchemy, and it is great, but too much
for my requirements, and I don't have any object relation with the
database tables. All I need is to access any database type in the same
way (mysql://user:[EMAIL PROTECTED]/database, pgsqll://user:[EMAIL 
PROTECTED]/database,
...) and run some basic queries. I have searched for this, but I have
not found any solution. Could you help me please?

If not, how can I run a simple query in SQLAlchemy? And iter the
results? I have tried this without success:

engine = create_engine('postgres://user:[EMAIL PROTECTED]/database',
echo=True)
results = engine.execute("SELECT * FROM TABLE")
for result in results:
print result
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and database unittests

2008-08-26 Thread Daniel
Hey gordy,

Thanks for the reply.  I am actually using sqlite in part of my
application and I don't feel the need to stub that.  Even though I
don't use the in memory option, it is still zero configuration so I
build up my database in each test then delete it.

However, the way I interact with the MySQL database is different than
the sqlite portion.

Thanks again,
Daniel


On Aug 26, 4:12 pm, gordyt <[EMAIL PROTECTED]> wrote:
> Daniel I don't know if it would work for your situation or not, but if
> you are using Python 2.5, you could use the now built-in sqlite3
> module.  If you didn't even want to create a temporary database file
> you could use the special memory-only syntax like this:
>
> >>> import sqlite3
> >>> conn =sqlite3.connect(":memory:")
> >>> # use the connection
> >>> conn.close()
>
> --gordy

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


Re: Identifying the start of good data in a list

2008-08-26 Thread bearophileHUGS
Sorry, in the Psyco version replace this line:
for i, el in enumerate(alist):

With:
for i in xrange(len(alist)):

because Psyco doesn't digest enumerate well.

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


Re: logging - how to use in a library?

2008-08-26 Thread Ben Finney
Thomas Heller <[EMAIL PROTECTED]> writes:

> If the script using the library does NOT configure logging, and
> somewhere the library calls logger.error(...) or
> logger.critical(...) then he gets a message on stderr saying:
> 
>   No handlers could be found for logger "foo"

Right. So, part of the requirements for using your library now is that
the caller is responsible for configuring logging before using the
library.

> I assume it would not be a good idea to configure logging in the
> library itself, possibly overwriting explicit configuration that the
> user has done... I don't get it.

The logging system needs to be configured in a way that makes sense
for the application, so it's the application (somewhere near the top
level) that's responsible for configuring it. You're right that this
can't be done without that context; there's no sane default.

You need to document that assumption of your library for those who
will use it.

-- 
 \   “The cost of education is trivial compared to the cost of |
  `\ ignorance.” —Thomas Jefferson |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Identifying the start of good data in a list

2008-08-26 Thread bearophileHUGS
First solutions I have found, not much tested beside the few doctests:

from itertools import islice

def start_good1(alist, good_ones=4):
"""
Maybe more efficient for Python

>>> start_good = start_good1
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
4
>>> start_good([])
-1
>>> start_good([0, 0])
-1
>>> start_good([0, 0, 0])
-1
>>> start_good([0, 0, 0, 0, 1])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 3])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4])
4
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5])
4
>>> start_good([1, 2, 3, 4])
0
>>> start_good([1, 2, 3])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 0, 4])
-1
"""
for i in xrange(len(alist) - good_ones + 1):
if all(islice(alist, i, i+good_ones)):
return i
return -1



def start_good2(alist, good_ones=4):
"""
Maybe more efficient for Psyco

>>> start_good = start_good2
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
4
>>> start_good([])
-1
>>> start_good([0, 0])
-1
>>> start_good([0, 0, 0])
-1
>>> start_good([0, 0, 0, 0, 1])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 3])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4])
4
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5])
4
>>> start_good([1, 2, 3, 4])
0
>>> start_good([1, 2, 3])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 0, 4])
-1
"""
n_good = 0
for i, el in enumerate(alist):
if alist[i]:
if n_good == good_ones:
return i - good_ones
else:
n_good += 1
else:
n_good = 0
if n_good == good_ones:
return len(alist) - good_ones
else:
return -1


if __name__ == "__main__":
import doctest
doctest.testmod()
print "Doctests done\n"

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


Re: smart quotes

2008-08-26 Thread Adrian Smith
On Aug 26, 4:13 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> Adrian Smith wrote:
> > Can anyone tell me how to get rid of smart quotes in html using
> > Python? I've tried variations on
> > stuff = string.replace(stuff, "\“", "\""), but to no avail, presumably
> > because they're not standard ASCII.
>
> Convert the string to unicode. For that you have to know its encoding. I
> assume UTF-8:
>
> >>> s = "a “smart quote” example"
> >>> u = s.decode("utf-8")
>
> Now you can replace the quotes (I looked up the codes in wikipedia):
>
> >>> u.replace(u"\u201c", "").replace(u"\u201d", "")
>
> u'a smart quote example'
>
> Alternatively, if you have many characters to remove translate() is more
> efficient:
>
> >>> u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019]))
>
> u'a smart quote example'
>
> If necessary convert the result back to the original encoding:
>
> >>> clean = u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019]))
> >>> clean.encode("utf-8")
>
> 'a smart quote example'
>
> Peter

Brilliant, thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Creating environment variables.

2008-08-26 Thread aditya shukla
Hello folks,

I am writing a program(prog 1) in python , which requires to know the path
of another program(prog 2) in order to execute.I can get my prog1 to work
when i hard code the path of the existing program(prog2).But since the path
of prog could be anywhere on the file system , thus i cannot hard codes its
path.And i am not supposed to take the path of prog2 as an input to prog1.So
is there anyway to solve this problem , by the creation of environment
variable (whose value is set as the path of prog 2)?Also how do i create
environment variable for prog1?


Thanks in advance

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

Re: File copying from a menu

2008-08-26 Thread Brandon
Turns out I was missing a few lines of code here-and-there, but now it's 
visible and working.  Thanks to anyone who was looking into this for me.


"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Brandon wrote:
>
>> I'm attempting to have a file copied from a menu selection.  The menu 
>> already exists, but it won't even create the menu item.  If anyone has 
>> any ideas, please let me know.
>
> try cutting down your code to a minimal example that illustrates the 
> problem, and post that code (that'll also allow us to figure out what 
> library you're using to create the menu...).
>
>  


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


Re: Python and database unittests

2008-08-26 Thread gordyt
Daniel I don't know if it would work for your situation or not, but if
you are using Python 2.5, you could use the now built-in sqlite3
module.  If you didn't even want to create a temporary database file
you could use the special memory-only syntax like this:

>>> import sqlite3
>>> conn =sqlite3.connect(":memory:")
>>> # use the connection
>>> conn.close()

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


Re: What's your first choice if you have to write a C module for python?

2008-08-26 Thread Christian Heimes

一首诗 wrote:

Hi all,

I read this interesting post comparing Boost.Python with Pyd:

http://pyd.dsource.org/vsboost.html

What's your opinion about it?

What's your first choice when you have write a C/C++ module for Python?


I'm using handwritten C code or Cython/Pyrex to create Python C 
extensions. Handwritten C code is sometimes required when you need full 
control over the C code and performance (speed or memory) is crucial to 
the project. Handwritten C code is the only option when you need 
readable, debugable C code.


However Cython is great for most applications these days. It's my 
preferred way to wrap small to large libraries, I was able to get quick 
and sufficient results in a matter of minutes.


ctypes is nice for small applications but I don't use it for serious 
work. It's too fragile across computer architectures, e.g. big/little 
endian machines or more important i386, AMD64/Unix and AMD64/Win32 
operation systems.


SIP claims to be the fastest and easiest system to wrap C++ code. The 
Cython wiki says it's about 40% faster than SWIG.


Christian

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

Re: Read dbf file as read only

2008-08-26 Thread Ricardo Aráoz

ajak_yahoo wrote:

Hi,
 
How can I access a foxpro dbf file from my python program.

 I just want to read it as a read only file.
Regards,




Check Paul McNett's article in FoxTalk "Exploring Python from a Visual 
Foxpro Perspective" and check the code in :


http://www.paulmcnett.com/vfp/09MCNESC.zip


HTH

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


RE: Adding Icons to my Programs

2008-08-26 Thread Support Desk
Take a look at this:

http://www.velocityreviews.com/forums/t332696-setting-icon-using-py2exe.html


-Original Message-
From: Kevin McKinley [mailto:[EMAIL PROTECTED] 
Sent: Tuesday, August 26, 2008 4:37 PM
To: python-list@python.org
Subject: Adding Icons to my Programs

I've been turn my script into executible programs with Py2exe.  Is there a
way to change the icon for the main exe file? 

Thank you, 
Kevin McKinley



  


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


RE: Adding Icons to my Programs

2008-08-26 Thread Support Desk


Sincerely,
Michael H.
 

-Original Message-
From: Kevin McKinley [mailto:[EMAIL PROTECTED] 
Sent: Tuesday, August 26, 2008 4:37 PM
To: python-list@python.org
Subject: Adding Icons to my Programs

I've been turn my script into executible programs with Py2exe.  Is there a
way to change the icon for the main exe file? 

Thank you, 
Kevin McKinley



  


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


RE: Adding Icons to my Programs

2008-08-26 Thread Support Desk

-Original Message-
From: Kevin McKinley [mailto:[EMAIL PROTECTED] 
Sent: Tuesday, August 26, 2008 4:37 PM
To: python-list@python.org
Subject: Adding Icons to my Programs

I've been turn my script into executible programs with Py2exe.  Is there a
way to change the icon for the main exe file? 

Thank you, 
Kevin McKinley



  


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


Re: What is class method?

2008-08-26 Thread Raymond Hettinger
On Aug 24, 5:32 am, Hussein B <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm familiar with static method concept, but what is the class method?
> how it does differ from static method? when to use it?

I use them when I need alternative constructors for a class.

class Angle(object):

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

   @classmethod
   def from_radians(cls, radians):
  return cls(radians / pi * 180.0)

This lets me construct a new angle with either Angle(45) or
Angle.from_radians(pi/4).

The example shows what is special about classmethods.  The first
argument is a class, not an instance.


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


Re: Decorators using instance variables

2008-08-26 Thread Robert Kaplan



Bruno Desthuilliers a écrit :

<...>

2/ don't bother reading anything from someone named 'castironpi', it's 
one of our currently active resident troll, and he is worse than 
clueless.




Actually, I found his response to the point, his sample code helpful, 
and his solution similar to yours.


<...>


Thanks for the help and pointers.

Bob  


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


Re: FW: Using Python to shared memory resources between Linux and Windows

2008-08-26 Thread Emile van Sebille

Blubaugh, David A. wrote:

Diez,

What you have said is extremely concerning.  
I am now using VMware.  With Linux as the Master and windows as the

guest operating system.  I was wondering if you have ever had to develop
a share memory resource between Linux and windows within a Vmware setup?




Maybe you can explain what you're trying to get done.  There're ways of 
sharing _data_, but if you're trying to have simultaneous access to 
physical memory from both host and guest, then yes, VMWare tries hard to 
prevent that...


Emile

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


Re: What is class method?

2008-08-26 Thread Medardo Rodriguez (Merchise Group)
On Tue, Aug 26, 2008 at 4:10 PM, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> In Python, there's *no* relationship between classmethods and metaclasses.

In OOP the concept of meta-class has everything to do with class
methods, regardless if is in Python, SmallTalk or CLOSS. "classmethod"
decorator it's just a syntax sugar structure to define them. There is
no difference (conceptually) on "method1" and "method2":

class MetaXClass(type):
def Method1(self): pass
class Xclass(object):
__metaclass__ = MetaXClass
@classmethod
def Method2(self): pass


> You can drop the 'global' - there's nothing like a real global scope in
> Python.


Yes, they are. Functions defined at module level or using staticmethod
decorator don't receive the instance as argument, they are globa,
You can study in Python:
 * global keyword
 * globals function

> Nope. Functions wrapped by a method object receive the instance as *first*
> (not 'special') argument. In Python, a method is only a wrapper object
> around the function, the class and the instance. This wrapper is built by
> the function object's __get__ method (descriptor protocol) each time the
> attribute is looked up.

Seriously, I'm a programmer, not a intermediate code engineer. I know
very well how python work in its inner, but this forum is to talk
about Python programming.
Nevertheless, in some level is always call the original defined
function, that YES, it receives the self as an argument.

> Why "theoretically speaking" ?

Why not?

 isinstance(Foo, object)
> True

That's only means that python is nice because fulfills very well the
best OOP theory.

> 
> pep08 : method names should be all_lower
> 

Not for me. I use to be consistent in being pythonic, but there are
some few exceptions.

> 
> The convention for classmethod is to name the first function argument 'cls'.
> 

I just wanted the guy who made the question, don't see other
differences but classmethod decorator.
Sorry!

> Nope. There's nothing like "coercion" in Python.

http://docs.python.org/ref/coercion-rules.html

> If you really intend to go into low-level explanations of Python's object


I NEVER pretended to do that. Programming I like is high level,
because of that Python is right now my preferred language,
nevertheless I know every thing I'm interested in inner Python.

My best regards
--
http://mail.python.org/mailman/listinfo/python-list


Identifying the start of good data in a list

2008-08-26 Thread tkpmep
I have a list that starts with zeros, has sporadic data, and then has
good data. I define the point at  which the data turns good to be the
first index with a non-zero entry that is followed by at least 4
consecutive non-zero data items (i.e. a week's worth of non-zero
data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9], I would define the point at which data turns good to be 4 (1
followed by 2, 3, 4, 5).

I have a simple algorithm to identify this changepoint, but it looks
crude: is there a cleaner, more elegant way to do this?

flag = True
i=-1
j=0
while flag and i < len(retHist)-1:
i += 1
if retHist[i] == 0:
j = 0
else:
j += 1
if j == 5:
flag = False

del retHist[:i-4]

Thanks in advance for your help

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


FW: Using Python to shared memory resources between Linux and Windows

2008-08-26 Thread Blubaugh, David A.
Diez,

What you have said is extremely concerning.  
I am now using VMware.  With Linux as the Master and windows as the
guest operating system.  I was wondering if you have ever had to develop
a share memory resource between Linux and windows within a Vmware setup?




Thanks for the help.  It will not be forgotten,


David Blubaugh


   

-Original Message-
From: Diez B. Roggisch [mailto:[EMAIL PROTECTED]
Sent: Tuesday, August 26, 2008 4:54 PM
To: python-list@python.org
Subject: Re: Using Python to shared memory resources between Linux and
Windows

Blubaugh, David A. schrieb:
> To All,

To whom else if I may ask?

> I was wondering if it was possible to utilize python to share a memory

> resource between a linux and windows system??  It should be stated 
> that both the Linux (CENTOS 5) and windows are physically located on 
> the same computer.  Is any of this possible?

No, not as that. You can use IPC-mechanisums such as XMLRPC, CORBA or
Pyro. But software such as VMWare or VirtualBox tries hard to *not* let
guest and host os influence each other.

Diez


This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


RE: Using Python to shared memory resources between Linux and Windows

2008-08-26 Thread Blubaugh, David A.
Diez,

What you have said is extremely concerning.  
I am now using VMware.  With Linux as the Master and windows as the
guest operating system.  I was wondering if you have ever had to develop
a share memory resource between Linux and windows within a Vmware setup?




Thanks for the help.  I will not be forgotten,


David Blubaugh


   

-Original Message-
From: Diez B. Roggisch [mailto:[EMAIL PROTECTED] 
Sent: Tuesday, August 26, 2008 4:54 PM
To: python-list@python.org
Subject: Re: Using Python to shared memory resources between Linux and
Windows

Blubaugh, David A. schrieb:
> To All,

To whom else if I may ask?

> I was wondering if it was possible to utilize python to share a memory

> resource between a linux and windows system??  It should be stated 
> that both the Linux (CENTOS 5) and windows are physically located on 
> the same computer.  Is any of this possible?

No, not as that. You can use IPC-mechanisums such as XMLRPC, CORBA or
Pyro. But software such as VMWare or VirtualBox tries hard to *not* let
guest and host os influence each other.

Diez


This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


Python and database unittests

2008-08-26 Thread Daniel
Hello,

I'm writing an application that interacts with a database.  As I think
about how to write the unittests, I want them to be able to run
without actually having to access a live database.  The pattern that
best describes this is here:

http://martinfowler.com/eaaCatalog/serviceStub.html

I have found http://qualitylabs.org/pdbseed/, which helps with
unittests for a live database.  This isn't what I'm after.

Does anyone know about a module that acts as a database stub for
python unittests?

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


Adding Icons to my Programs

2008-08-26 Thread Kevin McKinley
I've been turn my script into executible programs with Py2exe.  Is there a way 
to change the icon for the main exe file? 

Thank you, 
Kevin McKinley



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


Re: floating point arithmetic

2008-08-26 Thread John Machin
On Aug 27, 7:11 am, fred8865 <[EMAIL PROTECTED]> wrote:

> I understand that due to different arithmetic used in floating points
> they are just approximations. Hence, 180/100=1 in my python interpreter.

It's not "hence". What you are seeing is truncating integer division.

> How can I tackle this problem of inaccurate floating point numbers?

>>> 180 / 100
1
>>> 180 / 100.
1.8
>>> 180 / float(100)
1.8
>>> from __future__ import division
>>> 180 / 100
1.8
--
http://mail.python.org/mailman/listinfo/python-list


Re: floating point arithmetic

2008-08-26 Thread Mensanator
On Aug 26, 4:11 pm, fred8865 <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I understand that due to different arithmetic used in floating points
> they are just approximations. Hence, 180/100=1 in my python interpreter.
> How can I tackle this problem of inaccurate floating point numbers?

Try actually using floating point numbers, not integers:

>>> 180.0/100
1.8

or

>>> float(180)/100
1.8


> thank you
>
> regards
> xtd

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


Re: floating point arithmetic

2008-08-26 Thread Rob Clewley
> I understand that due to different arithmetic used in floating points
> they are just approximations. Hence, 180/100=1 in my python interpreter.

No, that's not the reason you get 1, it's because the current version
of python does integer division by default. Try doing 180.0/100 or
including

from __future__ import division

at the top of your scripts before dividing your numbers.

> How can I tackle this problem of inaccurate floating point numbers?

There are few occasions for "regular" users to worry about the
inaccuracy of floating point, unless you are doing very technical
calculations at high precision. If you need decimals to be represented
"perfectly" in python (e.g. you are writing scripts for financial
applications), try importing the decimal package (look it up in the
python docs).

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


RE: libxml2dom - parsing maligned html

2008-08-26 Thread bruce
hi paul...

so you're the guy behind the libxml2dom ehh..!! glad to say hey!

so this really is an issue with libxml2dom. ok, good, at least i know where
the issue is. and yeah, i know the real issue is the fact that the html
isn't valid!! shouldn't have multiple "html" trees...

from what i can tell, this isn't really solved via tidy/beautifulsoup
either, as a multiple html tree structure probably won't be looked at as
being invalid fom a token perspective.

ok, i can somehow live with this, i can accommodate it. but tell me, when
the parse module/class for libxml2dom does its thing, why does it not go
forward on the tree when it comes to a , if there's more text in the
string to process???

oh, also, regarding screen parsing/crawling, i've seen a number of sites
that have discussed using a web testing app, like selinium, and driving a
browser process, in order to really capture all the required data. any
thoughts on the pros/cons of this kind of approach to scraping data...

thanks

-bruce


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of Paul Boddie
Sent: Tuesday, August 26, 2008 8:48 AM
To: python-list@python.org
Subject: Re: libxml2dom - parsing maligned html


On 26 Aug, 17:28, "bruce" <[EMAIL PROTECTED]> wrote:
> so it's as if the parseString only reads the initial "html" tree. i've
> reviewed as much as i can find regarding libxml2dom to try to figure out
how
> i can get it to read/parse/handle both html trees/nodes.

Maybe there's some possibility to have libxml2 read directly from a
file descriptor and to stop after parsing the first document, leaving
the descriptor open; currently, this isn't supported by libxml2dom,
however. Another possibility is to feed text to libxml2 until it can
return a well-formed document, which I do as part of the
libxml2dom.xmpp module, but I don't really support this feature in the
public API.

Again, improvements to libxml2dom may happen if I find the time to do
them.

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

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


floating point arithmetic

2008-08-26 Thread fred8865
Hi all,

I understand that due to different arithmetic used in floating points
they are just approximations. Hence, 180/100=1 in my python interpreter.
How can I tackle this problem of inaccurate floating point numbers?
thank you

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


Re: Using Python to shared memory resources between Linux and Windows

2008-08-26 Thread Diez B. Roggisch

Blubaugh, David A. schrieb:

To All,


To whom else if I may ask?


I was wondering if it was possible to utilize python to share a memory
resource between a linux and windows system??  It should be stated that
both the Linux (CENTOS 5) and windows are physically located on the same
computer.  Is any of this possible?  


No, not as that. You can use IPC-mechanisums such as XMLRPC, CORBA or 
Pyro. But software such as VMWare or VirtualBox tries hard to *not* let 
guest and host os influence each other.


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


Re: Decorators using instance variables

2008-08-26 Thread Bruno Desthuilliers

Bruno Desthuilliers a écrit :

robert2821 a écrit :


(snip - sorry, hit the 'send' button too soon)


def getdec(f):
   dec = decorator(f)
   return dec.docall




class decorator:
   def __init__ (self, f):
   self.f = f

   def docall (self, *a):
   return self.f(*a)

class test:
   @getdec
   def doit (self, message):
   print message

if __name__ == '__main__':
   foo = test ()
   foo.doit ('Hello, world')




I'm wondering if the following program should work. I think it
should print 'Hello, World', but instead it produces a

>>> TypeError. Is this a bug in decorators, a feature of them, or a
>>> mistake or misunderstanding on my part?


Last point : post the whole error message and traceback if possible


Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/tmp/python-10426amG.py", line 19, in 
foo.doit ('Hello, world')
  File "/usr/tmp/python-10426amG.py", line 10, in docall
return self. f(*a)
TypeError: doit() takes exactly 2 arguments (1 given)


This has to do with how Python makes methods from functions. Your getdec 
function - which is the real decorator - returns a class instance, not 
another function. This actually prevents doit() to be wrapped in a 
method when looked up on a test instance, so doit doesn't receive the 
instance as first param (hence the error message).


Here's a working version of your code using new-style classes:

def getdec(f):
dec = Decorator(f)
return dec

class Decorator(object):
def __init__ (self, f):
self.f = f
self.instance = None

def __get__(self, instance, cls):
self.instance = instance
return self

def __call__(self, *args):
args = (self.instance,) + args
return self.f(*args)

class Test(object):
@ getdec
def doit(self, message):
print message

if __name__ == '__main__':
foo = Test ()

FWIW, note that the getdec function here is useless - you'd have the 
same result directly applying the Decorator class as a decorator.


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


Re: extract text from ods TableCell using odfpy

2008-08-26 Thread John Machin
On Aug 27, 3:04 am, norseman <[EMAIL PROTECTED]> wrote:
> frankentux wrote:
> > Ok. Sorted it out, but only after taking a round trip over
> > xml.minidom. Here's the working code:
>
> > #!/usr/bin/python
> > from odf.opendocument import Spreadsheet
> > from odf.opendocument import load
> > from odf.table import TableRow,TableCell
> > from odf.text import P
> > doc = load("/tmp/match_data.ods")
> > d = doc.spreadsheet
> > rows = d.getElementsByType(TableRow)
> > for row in rows[:2]:
> > cells = row.getElementsByType(TableCell)
> > for cell in cells:
> > tps = cell.getElementsByType(P)
> > if len(tps) > 0:
> > for x in tps:
> > print x.firstChild
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> =
> cd /opt
> find . -name "*odf*" -print
> (empty)
> cd /usr/local/lib/python2.5
> find . -name "*odf*" -print
> (empty)
>
> OK - where is it? :)
>

Consider using:
find --http --google "odfpy"
;-)

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


Re: Programmatically exit the REPL

2008-08-26 Thread Matthew Fitzgibbons

Matthew Fitzgibbons wrote:
I've got a pretty complex interactive command line program. Instead of 
writing my own REPL, I'm using the Python interpreter (an infinitely 
better solution). This program has two threads, a background thread and 
the REPL thread. When you call quit() or sys.exit() in the REPL thread, 
everything is perfectly happy. However, the background thread does some 
long-running jobs, and I want it to have the ability to exit the program 
when the job is complete. When I call quit() or sys.exit() from the 
background thread, the REPL merrily continues on its way.


This is a very frustrating problem, so I'm hoping someone can shed some 
light on it. Am I missing something simple? Or is this just impossible? 
I don't see anything about breaking out of interact() in the code module 
docs.



Here's a minimal example:

#!/usr/bin/env python -i
# You get the same behavior using code.interact()

import sys
import time
import threading

def end_the_program():
# works if you call it from the REPL thread,
# but not the background thread
print "called end_the_program()"
sys.exit()
# quit() # using quit() rather than sys.exit()
 # results in identical behavior

keep_going = True
def runner():
while keep_going:
time.sleep(0.1)
end_the_program()
threading.Thread(target=runner).start()

# end example


Here's the console session (edited for clarity):

Desktop$ ./exit_repl.py
 >>> keep_going = False
called end_the_program()
# notice we didn't exit here
 >>> end_the_program()
called end_the_program()
# but we did exit here
Desktop$


-Matt



Here's a modified example that _almost_ works:

#!/usr/bin/env python

import code
import time
import threading

keep_going = True
def runner():
while keep_going:
time.sleep(0.1)
ic.push("quit()") # this will exit the InteractiveConsole loop!
threading.Thread(target=runner).start()

ic = code.InteractiveConsole(locals())
ic.interact("InteractiveConsole")

# end example


It uses code.InteractiveConsole instead of python -i. When you push 
"quit()" to the InteractiveConsole, the loop exits, but the raw_input 
call is still blocking. Argh!


Console session:

Desktop$ ./exit_repl.py && echo done
InteractiveConsole
>>> keep_going = False
>>> 
done
Desktop$


Does anyone know how to make raw_input think it has gotten input?

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


RE: The Importance of Terminology's Quality

2008-08-26 Thread Phil Runciman


Apologies: By the time my posts have been added the discussion has moved
on a lot. I have to make a correction too.

It was not a System 4 machine but an ICL 2900 series (Once known as the
New Range Series). Hey it was a long time ago and I have moved countries
4 times since then and anno domini catches up with you.

However, the notion that microcode just fills in the gaps for
instructions not implemented directly in hardware may have been the case
in some systems, but it was not the case in several UK computers. The
micro code enabled interleaving of the execution of machine code so that
different parts of the hardware were active in executing adjacent
instructions at any one instant. 

It also meant that as assembler programmers we could detect performance
improvements when new microcode was implemented. On the HSD DCC2 one of
our microcode programmers was a Cambridge undergrad called Robert. (He
was the sort of guy who saw humour in a mathematical text. A breed
apart?)

He obviously did a good job because my navigational simulator programs
were a third shorter on DCC2 than on the 4130. Shame we did not have
floating point though. Spherical trig was tricky enough in reverse* but
in fixed point hardware it all got a bit convoluted. 

Phil (KDF9 Fan)
 


-Original Message-
From: Phil Runciman 
Sent: Friday, 22 August 2008 8:32 a.m.
To: python-list@python.org
Subject: RE: The Importance of Terminology's Quality




>On Thu, 21 Aug 2008 02:36:39 +, sln wrote:

>>>Whats os interresting about all this hullabaloo is that nobody has
coded
>>>machine code here, and know's squat about it.
>>>
>>>I'm not talking assembly language. Don't you know that there are
>>>routines that program machine code? Yes, burned in, bitwise encodings
>>>that enable machine instructions? Nothing below that.
>>>
>>>There is nobody here, who ever visited/replied with any thought
>>>relavence that can be brought foward to any degree, meaning anything,
>>>nobody
>>>
>>>sln
>> 
>> At most, your trying to validate you understanding. But you don't
pose
>> questions, you pose terse inflamatory declarations.
>> 
>> You make me sick!

>Could you elaborate a little on what it is that you're upset about?  I 
>suspect that there are probably quite a few readers of these posts that

>have designed and built their own processors, and coded them in their
own 
>machine language.  I have, and that was before FPGAs started to make
that 
>exercise quite commonplace.  But I don't see how that's at all relevant

>to the debate about the power or other characteristics of programming 
>languages.  Certainly anyone who's programmed a machine in assembly 
>language has a pretty fair understanding of what the machine and the 
>machine language is doing, even though they don't choose to bang the
bits 
>together manually.

>Hope you get better.

>-- 
>Andrew
>

I hope he gets better too. 

I cannot remember the boot sequences for either the TAC computer or the
H16 series. I used to know them but it became so automatic I could do
them in my sleep... and sometimes did. Late nights were common.

However, no-one has mentioned the fact that even machine code is
interpreted when the actual execution of each instruction is managed by
a micro program. I am not up with modern architectures but many
computers used micro programming to enable them to emulate rival
computers back in the late 60's and 70's. 

I believe ICL in South Africa supplied as a 1900 series that in reality
was System 4 hardware running the 1900 instruction set. It was a 1906T
if I remember correctly. (circa 1977). Perhaps someone out there can
confirm this snippet? (To a customer in Bloemfontein?)

FWIW even high-level language programmers got to know machine code if
they had to interpret memory dumps. I know this was very useful to work
out what went wrong with PL/1 code.

Phil (KDF9 Fan)





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


Re: Decorators using instance variables

2008-08-26 Thread Bruno Desthuilliers

robert2821 a écrit :


Hi,

I'm new; greetings all!


Hello.

Since you're new here, first a couple advises:
1/ the python mailing list is relayed to the comp.lang.python usenet 
newsgroup (from where I'm reading your post and answering it), so please 
avoid attachments. Either put the full code in your post, or provide an 
url to somewhere we can read it.
2/ don't bother reading anything from someone named 'castironpi', it's 
one of our currently active resident troll, and he is worse than clueless.


I'm wondering if the following program should work.  I think it should 
print 'Hello, World', but instead it produces a TypeError.  Is this a 
bug in decorators, a feature of them, or a mistake or misunderstanding 
on my part?


I doubt this is a bug. But it can be both a feature and a mistake or 
misunderstanding !-)



Please read pep08. Coding convention are very strong in Python. And 
preferably, use spaces (4 spaces per tab) for indentation.

http://www.python.org/dev/peps/pep-0008/




def getdec(f):
   dec = decorator(f)
   return dec. docall

class decorator: 



- pep08 : class names should be CamelCased
- unless you have a compelling reason to stick to a by now antiquated 
object model, better to use "new-style" classes. Part of what you'll 
read here about Python's OO features apply only to new-style classes, 
and most of the remaining apply to both object models.


IOW, make this:

class Decorator(object):



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

   def docall (self, *a):
   return self.f(*a)



You can write your own callable types by implementing the __call__ method.



class test:
   @getdec
   def doit (self, message):
   print message

if __name__ == '__main__':
   foo = test ()
   foo.doit ('Hello, world')


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


Using Python to shared memory resources between Linux and Windows

2008-08-26 Thread Blubaugh, David A.
To All,



I was wondering if it was possible to utilize python to share a memory
resource between a linux and windows system??  It should be stated that
both the Linux (CENTOS 5) and windows are physically located on the same
computer.  Is any of this possible?  




Thanks,



David Blubaugh





This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


Re: Books about Python.

2008-08-26 Thread Mike Driscoll
On Aug 24, 10:32 pm, [EMAIL PROTECTED] wrote:
> I'm up to write a 20-30 research paper for my computer science course,
> and I was considering choosing to do mine on Python.  I was curious if
> anybody knows of any good books about python they could recommend that
> have more of a technical view rather than a Teach-yourself-in-24-hours
> type.
>
> Thanks

If you want technical, I would recommend Lutz's "Programming Python"
3rd Ed or Chun's "Core Python Programming". Both are huge and have
tons of information!

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


Re: What is class method?

2008-08-26 Thread Bruno Desthuilliers

Hussein B a écrit :

Hi,
I'm familiar with static method concept,


Which is more often than not useless in Python - we have true functions 
and modules.



but what is the class method?


Short answer : It's a method that can be looked up upon both the class 
or an instance of it, and takes the class itself (instead of the 
instance) as first parameter.



how it does differ from static method?


static methods don't receive the class object as first param.


when to use it?


When you need to access the class (using polymorphic dispatch), don't 
care about the instance itself, and want to be able to call the method 
on both the class or an instance.


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


Re: Programmatically exit the REPL

2008-08-26 Thread Matthew Fitzgibbons

Almar Klein wrote:

Hi,

If you insist on writing your own shell, you can also consider running 
the commands in another python process.
I took the source code of Pype as an example, which uses a wx.Process. 
I've tried the subprocess module as well, but could not get it to work.


Almar

2008/8/26 Matthew Fitzgibbons <[EMAIL PROTECTED] 
>


Alexander Schmolck wrote:

Without reading your post properly or having tried to do the
same thing
myself: I think you might want to have a look at ipython; it
gives a better
REPL and "embedding ipython" should give you plenty of hits as well.


Thanks for the tip; I hadn't heard of ipython before. I will
certainly check it out. However, if anyone knows how to break out of
the interactive interpreter from another thread, I'd still very much
like to hear about it. :)


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




The whole point is that I *don't* want to write my own shell, I want to 
use the Python interactive shell (iPython, while very neat, is overkill 
for this purpose, and an extra dependency).


I use subprocess regularly, but it doesn't work in this case because (a) 
the point of using an interactive interpreter is so that I can interact 
with the job *while it's running* and (b) I *still* wouldn't be able 
exit the interactive shell cleanly (I'd have to look up the PID and kill 
it via the shell -- very ugly and not portable).


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


Re: What is class method?

2008-08-26 Thread Bruno Desthuilliers

Medardo Rodriguez (Merchise Group) a écrit :

On Sun, Aug 24, 2008 at 4:32 AM, Hussein B <[EMAIL PROTECTED]> wrote:

I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?


"Class Methods" are related to the meta-class concept introduced since
the first beginning of OOP but not known enough so far.
If you are capable to reason (to model) using that concept, the you
will need "classmethod" decorator in Python.


In Python, there's *no* relationship between classmethods and 
metaclasses. A classmethod is just a descriptor class attribute that act 
as a wrapper around a function in such a way that when the attribute is 
looked up (weither on the class or an instance of it) yields another 
(callable) wrapper around the function and the class, this last wrapper 
being responsible for calling the function with the class itself as 
first argument.



"Static Methods" are global operations but are declared in the
name-space context of a class; so, they are not strictly methods.

In Python everything is an object, but functions declared in the
module scope not receive the instance of the module, so they are not
module methods, they are not methods, they are global functions


You can drop the 'global' - there's nothing like a real global scope in 
Python.



that
are in the name-space context of the module in this case.

Methods always receive the instance as a special argument (usually
declared as self in Python).


Nope. Functions wrapped by a method object receive the instance as 
*first* (not 'special') argument. In Python, a method is only a wrapper 
object around the function, the class and the instance. This wrapper is 
built by the function object's __get__ method (descriptor protocol) each 
time the attribute is looked up.



Classes (theoretically speaking) are also
objects 


Why "theoretically speaking" ?

>>> class Foo(object): pass
...
>>> isinstance(Foo, object)
True
>>>

Python's classes *are* objects.



(dual behavior).

Let's be explicit:

#
class Test(object):
   def NormalMethod(self):
   print 'Normal:', self



pep08 : method names should be all_lower



   @staticmethod
   def StaticMethod(self=None):
   print 'Static:', self

   @classmethod
   def ClassMethod(self):
   print 'Class:', self



The convention for classmethod is to name the first function argument 'cls'.




test = Test()
test.NormalMethod()
test.StaticMethod()
test.ClassMethod()   # the instance "test" is coerced to it's class to
call the method.


Nope. There's nothing like "coercion" in Python. It's just that the 
descriptor protocol pass both the instance and it's class (or only the 
class if the lookup happens on the class itself) to the __get__ method, 
so the classmethod's __get__ method can store a reference to it and use 
that reference as first arg when calling the wrapped function.


If you really intend to go into low-level explanations of Python's 
object model, please get your facts right first. It's already difficult 
enough to explain, no need to add misleading or inexact stuff.

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


Re: dynamically adding some of one module's functions to another

2008-08-26 Thread Bruno Desthuilliers

Gabriel Rossetti a écrit :

Hello everyone,

I'm trying to import some modules into another's namespace (network_utils)

network_utils.py:

import utils
import constants as main_const
from services import constants as srv_const
from plugins import constants as plg_const

#
# Import all the message creation functions
#
f = dict([ (f, eval("utils." + f)) for f in dir(utils) if 
f.startswith("create") ])


As usual, you don't need eval here. Use getattr instead:

create_functions = dict(
   (name, getattr(utils, name)
   for name in dir(utils)
   if name.startswith('create')
   )


__builtins__.update(f)



Python 2.5.1 (r251:54863, Apr  6 2008, 17:20:35)
[GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> __builtins__

>>> type(__builtins__)

>>> __builtins__.update
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'update'
>>>

Anyway, adding to builtins is certainly not the best thing to do. I 
don't know what you're trying to do here, but looks like a very ugly 
mess to me.



del utils

#
# Create a virgin namespace
#
class constants:
   """
   An aggragation of L{constants},
   L{services.constants}, &
   L{plugins.constants}
   """
   pass




#
# Import all the constants into the new namespace
#
f = dict([ (f, eval("main_const." + f)) for f in dir(main_const) if 
f.isupper() ])

constants.__dict__.update(f)
del main_const
f = dict([ (f, eval("srv_const." + f)) for f in dir(srv_const) if 
f.isupper() ])

constants.__dict__.update(f)
del srv_const
f = dict([ (f, eval("plg_const." + f)) for f in dir(plg_const) if 
f.isupper() ])

constants.__dict__.update(f)
del plg_const


Yuck.

In your constants.py file, just add the relevant imports:

  from services.constants import *
  from plugins.constants import *

And then in your network_utils file:

  import constants

But this is still a mess to me. The nice point with explicit import and 
modules namespaces is that you at least have a chance to know where a 
given symbol comes from.




now, if I import network_utils somewhere, and try to call 
network_utils.myFunction() I get :


 >>> import network_utils
 >>> network_utils.myFunction
Traceback (most recent call last):
 File "", line 1, in 
AttributeError: 'module' object has no attribute 'myFunction'


And ? Where is the name myFunction bound in the above code ?


but if I try to access the constants class:

 >>> from network_utils import constants
 >>> constants.NO_DATA_TYPE
'none'

it works, how come?


I suppose NO_DATA_TYPE is defined somewhere in one of your constants.py 
files.


Instead of messing with eval and builtins and wonder why something 
"works" and why something else doesn't, I strongly suggest you (re)read 
the part about imports, packages, modules etc in the FineManual.

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


struct.Struct random access

2008-08-26 Thread castironpi
I'd like to seriously nominate this idea and get a considered opinion
on it.

struct.Struct lets you encode Python objects into structured memory.
It accepts a format string, and optionally a buffer and offset to/from
which to read/write the structure.  What do you think of random access
to the results?  To avoid Marc's concern about meaningless anonymous
record entries, model the constructor after 'namedtuple' type.

(unproduced)
>>> packer= struct.Struct( 'IIIf255p', 'i1 i2 i3 afloat name' )
>>> packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' )
>>> packer.unpack_from( buf, off, 'i3' )
30
>>> packer.unpack_from( buf, off )
( 10, 20, 30, 0.5, 'abc' )
>>> packer.pack_into( buf, off, 'i1', 12 )

Even in sequential access speed benefits, by avoiding the construction
of n-1 objects.

PS: If you don't have time or don't want to consider it seriously, or
want to see more specifics, just say so.
--
http://mail.python.org/mailman/listinfo/python-list


RE: Renaming Excel Spreadsheets

2008-08-26 Thread Reedick, Andrew
Excel object model:  

http://msdn.microsoft.com/en-us/library/bb149081.aspx

I think the Sheets object is where you add more sheets to a workbook.

 

You can google for code examples on how to use COM with Excel.  You
don't have to limit  yourself to Python code examples since COM is
"generic".

 

 

From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Greg
Lindstrom
Sent: Tuesday, August 26, 2008 2:54 PM
To: python-list@python.org
Subject: Renaming Excel Spreadsheets

 

Hello,

I am working with Python to create Excel spreadsheets and have run into
a couple of problems I hope you can help me with.

First...are there any bindings/libraries into Open Office?

Now, back to Excel.  

--> Does anyone know a way to create N worksheets?  By default, 3 are
created, but I would like more.

--> Is it possible to rename a worksheet inside of the workbook (change
"Sheet1" to "July 08", for example).

I've been working with Mark Hammond's book on Windows programming with
Python, but these have me stumped.

Better yet, an Open Source reporting system (ala Crystal Reports) would
keep me from having to write this.  I've looked at Jasper and
DataVision;

Thanks,
--greg

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

Re: Renaming Excel Spreadsheets

2008-08-26 Thread Emile van Sebille

Greg Lindstrom wrote:

Hello,

I am working with Python to create Excel spreadsheets and have run into 
a couple of problems I hope you can help me with.


First...are there any bindings/libraries into Open Office?

Now, back to Excel. 

--> Does anyone know a way to create N worksheets?  By default, 3 are 
created, but I would like more.


--> Is it possible to rename a worksheet inside of the workbook (change 
"Sheet1" to "July 08", for example).


Here's some code from years back that adds sheets to a workbook and then 
renames them.


Sheets = [["SlsSrce",None,1],
  ["SalesReps",None,1],
  ["Control",None,1]]

replist = []
for k in repkeys:
if k in currentReps:
replist.append([k, reps[k]])
Sheets.append(['Rep-%s' % k, None, 1])

def WorkBookSetup(Sheets):
# xl.Visible = 1
wbi = xl.Workbooks.Add()
wbi.Activate()
sheetcount = xl.Sheets.Count
index = 0
for name, ref, nextline in Sheets:
if index >= sheetcount:
wbi.Sheets.Add()
index = index + 1
index = 0
for name, ref, nextline in Sheets:
wbi.Sheets[index].Name = name
Sheets[index][1] = wbi.Sheets[index]
index = index + 1
return wbi

HTH,

Emile

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


Re: JSON from Python mysqldb

2008-08-26 Thread Larry Bates

jpuopolo wrote:

All:

I am using Python to read some records from the MySQL database. I am
using the mysqldb library, and things are working well.

Now, I would like to pass back the results of the query to a Web-based
front end, and I would like to use JSON. Is there a library/example of
creating a JSON array from a mysqldb row or row set?

Thanks,
jpuopolo


Google turns up several high quality links, just look for 'python json'.

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


Re: Are dictionaries the same as hashtables?

2008-08-26 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>Cameron Laird wrote:
>
>> In article <[EMAIL PROTECTED]>,
>> Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>>>Martin Marcher wrote:
>>>
 On 2008-08-26 00:32:20, cnb wrote:
> Are dictionaries the same as hashtables?
>> .
>> .
>> .
>>>Python does not have a "one key maps to a list of values"-semantics -
>>>which I consider the sane choice...
>>>
>>>However, you can have that using the defaultdict for example:
>>>
>>>listdict = defaultdict(list)
>>>
>>>listdict[key].append(value)
>>>
>>>Diez
>> 
>> ?  I'm lost.  As I understand your terms, Python's dictionaries
>> map keys to objects, but you would prefer that Python's
>> dictionaries map keys only to lists of values.  That *sounds*
>> like a complexification, at best.  Are you trying to make a
>> point about implementation aligning with semantics?
>
>The OP seems to want that (or at least sees it as one of two viable design
>choices), see his other answer in this thread.
>
>I certainly *don't* agree with that, I merely pointed out that python comes
>with means to easily create such a data-structure in the case it is needed.
>
>Diez

Oh!  Thanks for clearing *that* up; I certainly had a different 
impression.

To the original poster then:  please be aware that the values of
Python's dictionaries not only can be any first-class objects,
but it's quite common--quite common in *my* code, anyway--for
dictionaries to range over lists, tuples, functions, other
dictionaries, and more.  Python needn't change to allow you to
write any of this.
--
http://mail.python.org/mailman/listinfo/python-list


JSON from Python mysqldb

2008-08-26 Thread jpuopolo
All:

I am using Python to read some records from the MySQL database. I am
using the mysqldb library, and things are working well.

Now, I would like to pass back the results of the query to a Web-based
front end, and I would like to use JSON. Is there a library/example of
creating a JSON array from a mysqldb row or row set?

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


logging - how to use in a library?

2008-08-26 Thread Thomas Heller
I'm using the logging module in my comtypes library to log
'interesting' things that happen.  In other words, the idea
is if the user of the library is interested in the details that
happen in the package internally, he (she?) would configure
a logging level and handlers that write the log messages where it
is convenient.

This works great, with one exception:
If the script using the library does NOT configure logging, and somewhere the 
library calls
logger.error(...) or logger.critical(...) then he gets a message on stderr 
saying:

  No handlers could be found for logger "foo"

Of course this can be avoided by configuring a NULL-Handler, or raising the
loglevel to a very high value - but why is this necessary?
I would assume that if no handlers are configured than simply the logging
package should not output anything...

Why does logging insist on a default level of ERROR even if unconfigured, and
why does it insist to output something even if no handler is defined?

I assume it would not be a good idea to configure logging in the library itself,
possibly overwriting explicit configuration that the user has done...  I don't 
get it.

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


  1   2   3   >