Re: piping input to an external script

2009-05-11 Thread Steve Howell
On May 11, 11:31 pm, norseman  wrote:
> Steve Howell wrote:
> > On May 11, 10:16 pm, norseman  wrote:
> >> Tim Arnold wrote:
> >>> Hi, I have some html files that I want to validate by using an external
> >>> script 'validate'. The html files need a doctype header attached before
> >>> validation. The files are in utf8 encoding. My code:
> >>> ---
> >>> import os,sys
> >>> import codecs,subprocess
> >>> HEADER = ''
> >>> filename  = 'mytest.html'
> >>> fd = codecs.open(filename,'rb',encoding='utf8')
> >>> s = HEADER + fd.read()
> >>> fd.close()
> >>> p = subprocess.Popen(['validate'],
> >>>                     stdin=subprocess.PIPE,
> >>>                     stdout=subprocess.PIPE,
> >>>                     stderr=subprocess.STDOUT)
> >>> validate = p.communicate(unicode(s,encoding='utf8'))
> >>> print validate
> >>> ---
> >>> I get lots of lines like this:
> >>> Error at line 1, character 66:\tillegal character number 0
> >>> etc etc.
> >>> But I can give the command in a terminal 'cat mytest.html | validate' and
> >>> get reasonable output. My subprocess code must be wrong, but I could use
> >>> some help to see what the problem is.
> >>> python2.5.1, freebsd6
> >>> thanks,
> >>> --Tim
> >> 
> >> If you search through the recent Python-List for UTF-8 things you might
> >> get the same understanding I have come to.
>
> >> the problem is the use of python's 'print' subcommand or what ever it
> >> is. It 'cooks' things and someone decided that it would only handle 1/2
> >> of a byte (in the x'00 to x'7f' range) and ignore or send error messages
> >> against anything else. I guess the person doing the deciding read the
> >> part that says ASCII printables are in the 7 bit range and chose to
> >> ignore the part about the rest of the byte being undefined. That is
> >> undefined, not disallowed.  Means the high bit half can be used as
> >> wanted since it isn't already taken. Nor did whoever it was take a look
> >> around the computer world and realize the conflict that was going to be
> >> generated by using only 1/2 of a byte in a 1byte+ world.
>
> >> If you can modify your code to use read and write you can bypass print
> >> and be OK.  Or just have python do the 'cat mytest.html | validate' for
> >> you. (Apply a var for html and let python accomplish the the equivalent
> >> of Unix's:
> >>     for f in *.html; do cat $f | validate; done
> >>                          or
> >>      for f in *.html; do validate $f; done  #file name available this way
>
> >> If you still have problems, take a look at os.POPEN2 (and its popen3)
> >> Also take look at os.spawn.. et al
>
> > Wow.  Unicode and subprocessing and printing can have dark corners,
> > but common sense does apply in MOST situations.
>
> > If you send the header, add the newline.
>
> > But you do not need the header if you can cat the input file sans
> > header and get sensible input.
>
> Yep!  The problem is with 'print'
>

Huh?  Print is printing exactly what you expect it to print.

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


Re: install pyPgSQL on Windows for python 2.5

2009-05-11 Thread ralf321
On 24 Mrz., 18:25, someon  wrote:
> On Mar 24, 4:57 pm, Dietmar Schwertberger 
> wrote:
>
> > someone wrote:
> > > Hi,
>
> > > does anyone know how to install pyPgSQL on Windows? There is no
> > > package for Python 2.5 on Homepage:
> > > I've installed newest Visual C++ Studio 2008 from Microsoft, but still
> > > no luck
>
> > Hello Pet,
>
> > you need Visual Studio 2003 to compile extensions for Python 2.5
> > If you want, I can send you a binary.
>
> O, thank you very much!
> Where should I put hole thing?
>
> > Regards,
>
> > Dietmar
>
>

Hello,
i need the binary files too.
can you send me or upload anywhere?
thanks.

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


Re: How do I test the integrity of a Python installation in Debian and Ubuntu

2009-05-11 Thread Geoff Gardiner
Lawrence D'Oliveiro wrote:
> .. I expect an apology. 
> Otherwise, it becomes grounds for an abuse complaint to your ISP.
>   
Yes, I do apologize profusely and publicly, and would have done so
regardless of threat.

I had trouble with posts making it through to the list and so was also
posting in parallel to the original posters. In doing so, your address
initially bounced the message - so I changed it unthinkingly in a to: line.

I did not realize until this morning that they made it through
python-list unchanged, as they obviously do.

All the best,
Geoff


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


Re: piping input to an external script

2009-05-11 Thread norseman

Steve Howell wrote:

On May 11, 10:16 pm, norseman  wrote:

Tim Arnold wrote:

Hi, I have some html files that I want to validate by using an external
script 'validate'. The html files need a doctype header attached before
validation. The files are in utf8 encoding. My code:
---
import os,sys
import codecs,subprocess
HEADER = ''
filename  = 'mytest.html'
fd = codecs.open(filename,'rb',encoding='utf8')
s = HEADER + fd.read()
fd.close()
p = subprocess.Popen(['validate'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
validate = p.communicate(unicode(s,encoding='utf8'))
print validate
---
I get lots of lines like this:
Error at line 1, character 66:\tillegal character number 0
etc etc.
But I can give the command in a terminal 'cat mytest.html | validate' and
get reasonable output. My subprocess code must be wrong, but I could use
some help to see what the problem is.
python2.5.1, freebsd6
thanks,
--Tim


If you search through the recent Python-List for UTF-8 things you might
get the same understanding I have come to.

the problem is the use of python's 'print' subcommand or what ever it
is. It 'cooks' things and someone decided that it would only handle 1/2
of a byte (in the x'00 to x'7f' range) and ignore or send error messages
against anything else. I guess the person doing the deciding read the
part that says ASCII printables are in the 7 bit range and chose to
ignore the part about the rest of the byte being undefined. That is
undefined, not disallowed.  Means the high bit half can be used as
wanted since it isn't already taken. Nor did whoever it was take a look
around the computer world and realize the conflict that was going to be
generated by using only 1/2 of a byte in a 1byte+ world.

If you can modify your code to use read and write you can bypass print
and be OK.  Or just have python do the 'cat mytest.html | validate' for
you. (Apply a var for html and let python accomplish the the equivalent
of Unix's:
for f in *.html; do cat $f | validate; done
 or
 for f in *.html; do validate $f; done  #file name available this way

If you still have problems, take a look at os.POPEN2 (and its popen3)
Also take look at os.spawn.. et al



Wow.  Unicode and subprocessing and printing can have dark corners,
but common sense does apply in MOST situations.

If you send the header, add the newline.

But you do not need the header if you can cat the input file sans
header and get sensible input.



Yep!  The problem is with 'print'


Finally, if you are concerned about adding the header, then it belongs
in the original input file; otherwise, you are creating a false
positive.



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


Re: Fwd: Re: Unable to install Pywin32 for Python 2.6.2

2009-05-11 Thread Mark Hammond
Probably some import statement is finding a .pyd module built against 
Python 2.5 instead of Python 2.6; it might be that PYTHONPATH points 
somewhere wrong, or the registry for Python 2.6 is setup wrong, or 
something else entirely...


Cheers,

Mark

On 12/05/2009 3:13 PM, David Lyon wrote:

Hi,

hmmm... that's annoying..

Whilst I don't have an exact answer I have a few hunches...

Perphaps what has happened is that the windows installer between
the versions of pywin32 has installed newer versions of the same
dlls over the top of older ones.

Or, possibly, the installer hasn't wanted to replace older dll's
because they already exist on the system.

This would result in a mismatch.

You may be lucky and find an install log. This might tell you which
files were actually installed. And you could play around with
moving them around.

Good luck with your night vision task

David


On Tue, 12 May 2009 02:22:56 GMT, David Lees
wrote:

I have no problem installing Python 2.6.2 for windows under XP SP3 and
IDLE and the command line versions work fine.  When I run the pywin32
installer downloaded from sourceforge (pywin32-212.win32-py2.6.exe) I
get the following error message:

Traceback (most recent call last):
File "", line 565, in
File "", line 291, in install
ImportError: Module use of python25.dll conflicts with this version of
Python.
*** run_installscript: internal error 0x ***

I have tried uninstalling Python 2.6 and reinstalling, but still get the
same message.  I do have Python 2.5.4 and its associated Pywin32 on the
same machine, but I have a laptop with pywin32 installed for both python
2.5 and 2.6.

TIA

David Lees


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


Re: piping input to an external script

2009-05-11 Thread Steve Howell
On May 11, 10:16 pm, norseman  wrote:
> Tim Arnold wrote:
> > Hi, I have some html files that I want to validate by using an external
> > script 'validate'. The html files need a doctype header attached before
> > validation. The files are in utf8 encoding. My code:
> > ---
> > import os,sys
> > import codecs,subprocess
> > HEADER = ''
>
> > filename  = 'mytest.html'
> > fd = codecs.open(filename,'rb',encoding='utf8')
> > s = HEADER + fd.read()
> > fd.close()
>
> > p = subprocess.Popen(['validate'],
> >                     stdin=subprocess.PIPE,
> >                     stdout=subprocess.PIPE,
> >                     stderr=subprocess.STDOUT)
> > validate = p.communicate(unicode(s,encoding='utf8'))
> > print validate
> > ---
>
> > I get lots of lines like this:
> > Error at line 1, character 66:\tillegal character number 0
> > etc etc.
>
> > But I can give the command in a terminal 'cat mytest.html | validate' and
> > get reasonable output. My subprocess code must be wrong, but I could use
> > some help to see what the problem is.
>
> > python2.5.1, freebsd6
> > thanks,
> > --Tim
>
> 
> If you search through the recent Python-List for UTF-8 things you might
> get the same understanding I have come to.
>
> the problem is the use of python's 'print' subcommand or what ever it
> is. It 'cooks' things and someone decided that it would only handle 1/2
> of a byte (in the x'00 to x'7f' range) and ignore or send error messages
> against anything else. I guess the person doing the deciding read the
> part that says ASCII printables are in the 7 bit range and chose to
> ignore the part about the rest of the byte being undefined. That is
> undefined, not disallowed.  Means the high bit half can be used as
> wanted since it isn't already taken. Nor did whoever it was take a look
> around the computer world and realize the conflict that was going to be
> generated by using only 1/2 of a byte in a 1byte+ world.
>
> If you can modify your code to use read and write you can bypass print
> and be OK.  Or just have python do the 'cat mytest.html | validate' for
> you. (Apply a var for html and let python accomplish the the equivalent
> of Unix's:
>     for f in *.html; do cat $f | validate; done
>                          or
>      for f in *.html; do validate $f; done  #file name available this way
>
> If you still have problems, take a look at os.POPEN2 (and its popen3)
> Also take look at os.spawn.. et al
>

Wow.  Unicode and subprocessing and printing can have dark corners,
but common sense does apply in MOST situations.

If you send the header, add the newline.

But you do not need the header if you can cat the input file sans
header and get sensible input.

Finally, if you are concerned about adding the header, then it belongs
in the original input file; otherwise, you are creating a false
positive.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping comments

2009-05-11 Thread Arnaud Delobelle
Tobias Weber  writes:

> In article ,
>  David Robinow  wrote:
>
>> (define-key key-translation-map [?\M-3] "#")
>> 
>> 
>> or, if you prefer, just be sick.
>
> Thanks, but I don't believe using releases from people who think I jump 
> should through hoops just to make my keyboard work is a good plan for a 
> relaxed future. According to their release notes this was (once) fixed 
> years ago.

No need for editing .emacs.

Click 'Options' on the menu bar, hover down to the 'Option Key >' item,
then select the 'Meta & British' option.  This is IMHO the best option
(if you have a UK keyboard, of course!).  This way, Alt-3 gives you a
'#'.

It would be a shame to abandon Aquamacs just for this, they have made a
lot of efforts to make it integrate well with OSX and I think this is
one of the few hurdles that are left.

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


Re: piping input to an external script

2009-05-11 Thread norseman

Tim Arnold wrote:
Hi, I have some html files that I want to validate by using an external 
script 'validate'. The html files need a doctype header attached before 
validation. The files are in utf8 encoding. My code:

---
import os,sys
import codecs,subprocess
HEADER = ''

filename  = 'mytest.html'
fd = codecs.open(filename,'rb',encoding='utf8')
s = HEADER + fd.read()
fd.close()

p = subprocess.Popen(['validate'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
validate = p.communicate(unicode(s,encoding='utf8'))
print validate
---

I get lots of lines like this:
Error at line 1, character 66:\tillegal character number 0
etc etc.

But I can give the command in a terminal 'cat mytest.html | validate' and 
get reasonable output. My subprocess code must be wrong, but I could use 
some help to see what the problem is.


python2.5.1, freebsd6
thanks,
--Tim




If you search through the recent Python-List for UTF-8 things you might 
get the same understanding I have come to.


the problem is the use of python's 'print' subcommand or what ever it 
is. It 'cooks' things and someone decided that it would only handle 1/2 
of a byte (in the x'00 to x'7f' range) and ignore or send error messages 
against anything else. I guess the person doing the deciding read the 
part that says ASCII printables are in the 7 bit range and chose to 
ignore the part about the rest of the byte being undefined. That is 
undefined, not disallowed.  Means the high bit half can be used as 
wanted since it isn't already taken. Nor did whoever it was take a look 
around the computer world and realize the conflict that was going to be 
generated by using only 1/2 of a byte in a 1byte+ world.


If you can modify your code to use read and write you can bypass print 
and be OK.  Or just have python do the 'cat mytest.html | validate' for 
you. (Apply a var for html and let python accomplish the the equivalent 
of Unix's:

   for f in *.html; do cat $f | validate; done
or
for f in *.html; do validate $f; done  #file name available this way

If you still have problems, take a look at os.POPEN2 (and its popen3)
Also take look at os.spawn.. et al

HTH

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


Fwd: Re: Unable to install Pywin32 for Python 2.6.2

2009-05-11 Thread David Lyon
Hi,

hmmm... that's annoying..

Whilst I don't have an exact answer I have a few hunches...

Perphaps what has happened is that the windows installer between
the versions of pywin32 has installed newer versions of the same
dlls over the top of older ones.

Or, possibly, the installer hasn't wanted to replace older dll's 
because they already exist on the system.

This would result in a mismatch.

You may be lucky and find an install log. This might tell you which
files were actually installed. And you could play around with
moving them around.

Good luck with your night vision task

David


On Tue, 12 May 2009 02:22:56 GMT, David Lees 
wrote:
> I have no problem installing Python 2.6.2 for windows under XP SP3 and 
> IDLE and the command line versions work fine.  When I run the pywin32 
> installer downloaded from sourceforge (pywin32-212.win32-py2.6.exe) I 
> get the following error message:
> 
> Traceback (most recent call last):
>File "", line 565, in 
>File "", line 291, in install
> ImportError: Module use of python25.dll conflicts with this version of 
> Python.
> *** run_installscript: internal error 0x ***
> 
> I have tried uninstalling Python 2.6 and reinstalling, but still get the 
> same message.  I do have Python 2.5.4 and its associated Pywin32 on the 
> same machine, but I have a laptop with pywin32 installed for both python 
> 2.5 and 2.6.
> 
> TIA
> 
> David Lees
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to install Pywin32 for Python 2.6.2

2009-05-11 Thread David Lyon

Hi,

hmmm... that's annoying..

Whilst I don't have an exact answer I have a few hunches...

Perphaps what has happened is that the windows installer between
the versions of pywin32 has installed newer versions of the same
dlls over the top of older ones.

Or, possibly, the installer hasn't wanted to replace older dll's 
because they already exist on the system.

This would result in a mismatch.

You may be lucky and find an install log. This might tell you which
files were actually installed. And you could play around with
moving them around.

Good luck with your night vision task

David


On Tue, 12 May 2009 02:22:56 GMT, David Lees 
wrote:
> I have no problem installing Python 2.6.2 for windows under XP SP3 and 
> IDLE and the command line versions work fine.  When I run the pywin32 
> installer downloaded from sourceforge (pywin32-212.win32-py2.6.exe) I 
> get the following error message:
> 
> Traceback (most recent call last):
>File "", line 565, in 
>File "", line 291, in install
> ImportError: Module use of python25.dll conflicts with this version of 
> Python.
> *** run_installscript: internal error 0x ***
> 
> I have tried uninstalling Python 2.6 and reinstalling, but still get the 
> same message.  I do have Python 2.5.4 and its associated Pywin32 on the 
> same machine, but I have a laptop with pywin32 installed for both python 
> 2.5 and 2.6.
> 
> TIA
> 
> David Lees
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to install Pywin32 for Python 2.6.2

2009-05-11 Thread David Lyon
On Tue, 12 May 2009 02:22:56 GMT, David Lees 
wrote:
> I have no problem installing Python 2.6.2 for windows under XP SP3 and 
> IDLE and the command line versions work fine.  When I run the pywin32 
> installer downloaded from sourceforge (pywin32-212.win32-py2.6.exe) I 
> get the following error message:
> 
> Traceback (most recent call last):
>File "", line 565, in 
>File "", line 291, in install
> ImportError: Module use of python25.dll conflicts with this version of 
> Python.
> *** run_installscript: internal error 0x ***
> 
> I have tried uninstalling Python 2.6 and reinstalling, but still get the 
> same message.  I do have Python 2.5.4 and its associated Pywin32 on the 
> same machine, but I have a laptop with pywin32 installed for both python 
> 2.5 and 2.6.
> 
> TIA
> 
> David Lees
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-11 Thread kay
On 12 Mai, 02:10, Tomasz Rola  wrote:
> On Mon, 11 May 2009, rump...@web.de wrote:
> > > One question I ask myself upon seeing a new language is if it is possible
> > > to program amb (amb=ambiguous) operator in it. This page gives a very
> > > nice, "code first" explanation of amb and how it is supposed to work:
>
> > >http://www.randomhacks.net/articles/2005/10/11/amb-operator
>
> > Hm. I am not sure either. To me, it looks like a constraint solver by
> > using brute force.
>
> Yes, kind of. From what I understand [1], it's goal is to simulate
> nondeterministic "get right answer in one try", only this "one try"
> requires browsing the solution space (because we have only "classic"
> hardware). It is easy to use amb in wrong way, but I can see some cases
> when I would like it.

In Python you can use a generator expression. Dan Piponis example can
be stated as

g = ((i,j) for i in range(2,100) for j in range(2,i) if i*j == 481)

which doesn't require any call/cc hacks but is a deterministic "get
right in one try". Once Nimrod has coroutines it's just a matter of
sugaring them into comprehensions.

>
> [1] John McCarthy's paper still waits to be read by me, so... Ok, I have
> just had a look at it and it seems that Ruby implementation is a bit
> primitive compared to original concept. But still, this is what would be
> needed in most real life cases, I suppose.
>
> I think ability to define amb would allow me to write more concise code.
> As far as I can tell, this kind of stuff plays more and more important
> role in my programing.
>
> > It seems to require continuations. AFAIK
> > continuations are extremely hard to implement efficiently, so probably
> > it won't be done in Nimrod.
>
> Pity, a little. But not really big problem for me. Nimrod may be
> interesting anyway, time will tell :-).
>
> Regards,
> Tomasz Rola
>
> --
> ** A C programmer asked whether computer had Buddha's nature.  **
> ** As the answer, master did "rm -rif" on the programmer's home**
> ** directory. And then the C programmer became enlightened...  **
> ** **
> ** Tomasz Rola  mailto:tomasz_r...@bigfoot.com **

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


Re: piping input to an external script

2009-05-11 Thread Steve Howell
On May 11, 11:04 am, "Tim Arnold"  wrote:
> Hi, I have some html files that I want to validate by using an external
> script 'validate'. The html files need a doctype header attached before
> validation. The files are in utf8 encoding. My code:
> ---
> import os,sys
> import codecs,subprocess
> HEADER = ''
>
> filename  = 'mytest.html'
> fd = codecs.open(filename,'rb',encoding='utf8')
> s = HEADER + fd.read()
> fd.close()
>
> p = subprocess.Popen(['validate'],
>                     stdin=subprocess.PIPE,
>                     stdout=subprocess.PIPE,
>                     stderr=subprocess.STDOUT)
> validate = p.communicate(unicode(s,encoding='utf8'))
> print validate
> ---
>
> I get lots of lines like this:
> Error at line 1, character 66:\tillegal character number 0
> etc etc.
>
> But I can give the command in a terminal 'cat mytest.html | validate' and
> get reasonable output. My subprocess code must be wrong, but I could use
> some help to see what the problem is.
>

Newline missing after the header is my guess.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web access through vpn client

2009-05-11 Thread Gabriel Genellina
En Fri, 01 May 2009 21:41:03 -0300, Stephen Hansen   
escribió:



urllib2 and BeautifulSoup work pretty well to do what I want, and the
first little routine actually gets the data from the web page...
except if my VPN client is turned on.


Usually when something like that happens with a VPN its because the VPN  
has been configured to do so. Its the default usually and is a security
precaution.  The exact wording of the option varies from VPN client to  
VPN client; and its usually hidden deep in 'advanced'. E.g., on the mac 
its "Send all traffic over VPN connection", on Windows I /believe/ its  
something like "Set as default gateway" but its been awhile since I had 
to tweak my windows install. No idea what it looks like on the Cisco 
client.


Reading c.l.p. helps even for non-Python questions! A friend of mine had a  
problem with a VPN, I vaguely remembered this post and looked for it, and  
in a few minutes we fixed the problem. Thanks!


--
Gabriel Genellina

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


Re: dict would be very slow for big data

2009-05-11 Thread Steve Howell
On May 11, 8:28 pm, forrest yang  wrote:
> hi
> i am trying to insert a lot of data into a dict, which may be
> 10,000,000 level.
> after inserting 10 unit, the insert rate become very slow, 50,000/
> s, and the entire time used for this task would be very long,also.
> would anyone know some solution for this case?
>

Are you running out of memory?  What are your keys?  Are you able to
gather any more specific data about the slowdown--do all operations
slow down equally or are there spurts of slowness?

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


piping input to an external script

2009-05-11 Thread Tim Arnold
Hi, I have some html files that I want to validate by using an external 
script 'validate'. The html files need a doctype header attached before 
validation. The files are in utf8 encoding. My code:
---
import os,sys
import codecs,subprocess
HEADER = ''

filename  = 'mytest.html'
fd = codecs.open(filename,'rb',encoding='utf8')
s = HEADER + fd.read()
fd.close()

p = subprocess.Popen(['validate'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
validate = p.communicate(unicode(s,encoding='utf8'))
print validate
---

I get lots of lines like this:
Error at line 1, character 66:\tillegal character number 0
etc etc.

But I can give the command in a terminal 'cat mytest.html | validate' and 
get reasonable output. My subprocess code must be wrong, but I could use 
some help to see what the problem is.

python2.5.1, freebsd6
thanks,
--Tim


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


Re: putting date strings in order

2009-05-11 Thread Paul Rubin
noydb  writes:
> Anyone have any good ideas?  I was curious to see what people came up
> with.

Is this a homework assignment?  Some hints:

1) figure out how to compare two month names for chronological order,
   leaving out the issue of the starting month not being january.
2) figure out how to adjust for the starting month.  The exact
   semantics of the "%" operator might help do this concisely.
-- 
http://mail.python.org/mailman/listinfo/python-list


dict would be very slow for big data

2009-05-11 Thread forrest yang
hi
i am trying to insert a lot of data into a dict, which may be
10,000,000 level.
after inserting 10 unit, the insert rate become very slow, 50,000/
s, and the entire time used for this task would be very long,also.
would anyone know some solution for this case?

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


Re: Can I get a value's name

2009-05-11 Thread Alan Brogan
Thank you Ken for your help answer

On Mon, May 11, 2009 at 8:11 PM, Ken Seehart  wrote:
> jalanb3 wrote:
>>

>> def replace_line(pattern,replacement):
>>    values = '\n' in pattern and [ pattern ] or []
>>    values += '\n' in replacement and [ replacement ] or []
>>
>> Can I later get the name "pattern" via values[0]?
>>


>  A value generally does not contain the
> "pattern" or any kind of name information (although class, method, and
> function instances contain some symbolic information in them).
>
That's why I took the question seriously at all:
 It was an entirely different project - pulling info out of
tracebacks into logs.
And I can get names from a reference for classes, modules, ...
Why not variables ?

> Study the concept of 'references' and all of this will become more clear.

I shall dive into that koan :-)

> The only way to do something like what you want would be to search globals()
> or locals() for the value (depending on the context), but that would be an
> extremely ugly hack.
Agreed

> Chances are that if you want to do this, you need to
> rethink the problem instead.
>
That does seem reasonable, but before I started writing Python it
would never occurred to me to add some attributes on to an object
whose definition I've never seen. So - unlikely, but I wouldn't rule
it out.



> Note that a value can have several different names (and unnamed references)
> pointing at it,

Ah - there's  the rub !

All it takes (from my earlier example) is
fred = pattern
values += [ fred ]

Now which is "the real name" of values[0]?
In my example I would have wanted "pattern", and now whatever ugly
hack we used to get at "the name" is turning into an complex module.

> so the above code is not very general, but it may illustrate
> some interesting points.

Thanks - it does indeed.

> My guess is that your entire approach may need rethinking.  What is the
> ultimate objective of your project?

Find out what some other Pythonista have thought about this problem

OTOH: the actual objective was to remove the redundancy of using the
string "pattern" when I already have a perfectly good eponymous
variable.  On balance I think allowing a little bit of redundancy is
prudent in this case :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OOP & Abstract Classes

2009-05-11 Thread alex23
On May 12, 1:22 am, Mike Driscoll  wrote:
> I've never used (or heard of) the Abstract type...and the guy who
> wrote the FAQ was being a jerk. It looks like he was just throwing in
> an undefined variable name just to make his Python program break while
> taking a pot shot at people who use that sort of thing. Whatever.

The IAQ's entry on Abstract classes predates the introduction of
Abstract Base Classes to Python 2.6/3.0. Rather than being a "jerk",
the example shows how to produce similar behaviour without code AS
WELL as demonstrating a more extended approach. (You're not breaking
your program if the behaviour is intentional...)

> Hopefully someone who has used Abstract classes will jump in here and
> give you more information about whether or not they matter in Python.

Abstract classes are one mechanism for defining interfaces, but as
we've covered it's not the only approach that can be taken. I've
always been happy defining abstract methods using 'raise
NotImplementedError', but clearly the ABC approach is perceived as
having value otherwise it would never have been introduced into
2.6/3.0.
-- 
http://mail.python.org/mailman/listinfo/python-list


putting date strings in order

2009-05-11 Thread noydb
All,

How best to go about this?  >>

I have a list containing strings referring to months, like ["x_apr",
"x_jul", "x_jan", "x_aug", "x_may", etc] -- always using the 3-chars
for month.  The list will contain all 12 months, however the starting
month may not necessarily be jan.  I want to order the list
chronologically, but starting with the user-defined starting month.
So a list could be [x_aug, x_sep,  x_jul].  The list might just
start off in any random order, but I need to ensure, in the end, that
the list is in chronological order and starting with the proper month
per user needs.

Anyone have any good ideas?  I was curious to see what people came up
with.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite single transaction without foreign key or triggers

2009-05-11 Thread Aahz
In article ,
Rob Williscroft   wrote:
>
>db.execute( '''
>   update "sessions" set "uid" = ?
>   where "uid" = ? 
>   and exists(
>   select * from "users" where "uid" = ?
> )
>''',
>(v['uid'],s.SID, v['uid']) 
>  )

This will be more efficient if you do "select uid from users".
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OS X: How to play .wav file w/Python?

2009-05-11 Thread alex23
On May 12, 11:55 am, kj  wrote:
> import pygame.mixer
>
> pygame.mixer.init()
> pygame.mixer.Sound("bell.wav").play
> print "done"
>
> What am I doing wrong?

Your first mistake is not pasting here the traceback you received.
That always makes it easier to assist with problems like this.

However, my guess is it's this line:

> pygame.mixer.Sound("bell.wav").play

'play' is a method, which means you need to call it. Try the following
instead:

> pygame.mixer.Sound("bell.wav").play()

And let us know how that goes :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Unable to install Pywin32 for Python 2.6.2

2009-05-11 Thread David Lees
I have no problem installing Python 2.6.2 for windows under XP SP3 and 
IDLE and the command line versions work fine.  When I run the pywin32 
installer downloaded from sourceforge (pywin32-212.win32-py2.6.exe) I 
get the following error message:


Traceback (most recent call last):
  File "", line 565, in 
  File "", line 291, in install
ImportError: Module use of python25.dll conflicts with this version of 
Python.

*** run_installscript: internal error 0x ***

I have tried uninstalling Python 2.6 and reinstalling, but still get the 
same message.  I do have Python 2.5.4 and its associated Pywin32 on the 
same machine, but I have a laptop with pywin32 installed for both python 
2.5 and 2.6.


TIA

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


Re: creating classes with mix-ins

2009-05-11 Thread Carl Banks
On May 11, 11:16 am, samwyse  wrote:
> I'm writing a class that derives it's functionality from mix-ins.
> Here's the code:
>
>     def boilerplate(what):   # This used to be a decorator, but all of
> the
>         ##what = f.__name__  # function bodies turned out to be
> 'pass'.
>         'Validate the user, then call the appropriate plug-in.'
>         def template(self, which, username, password, *args):
>             if not self.security.isAuthorised(username, password,
> which, what):
>                 raise Exception('Unauthorised access')
>             return getattr(self.blog, what)(which, *args)
>         template.__name__ = what
>         template.__doc__ = getattr(self.blog, what).__doc__
>         return template
>
>     class MetaWeblog(object):
>         def __init__(self,
>                      securityHandler=SimpleSecurityHandler,
>                      blogHandler=SimpleBlogHandler):
>             self.security = securityHandler()
>             self.blog = blogHandler()
>         newPost = boilerplate('newPost')
>         editPost = boilerplate('editPost')
>         getPost = boilerplate('getPost')
>         # etc, etc, etc
>
> I'd like to replace the method definitions with a loop:
>         for what in attr_list:
>             setattr(klass, what, boilerplate(what))
>
> That begs the question of where I define 'klass' and 'attr_list'.
> Should I use a class decorator, or a metaclass?

Here's the thing: unless you have advance knowledge of the methods
defined by self.blog, you can't get the attr_list at class definition
time, which means neither the metaclass nor the decorator would be a
good approach.  If that's the case, you should define newPost,
editPost, and whatever other methods of self.blog as ordinary
attributes of self, within the init function.  boilerplate would be
the same except you would pass self to it and allow template to use it
from its nested scope (it would no longer be an instance method since
it's an ordinary attribute).

If you do know what the methods of self.blog will be, then that's
where you get attr_list from.  So, for instance, if blogHandler always
returns an object of type Blog, then you could inspect Blog's type
dict to see what methods are defined in it; in fact you probably want
to check the whole MRO for Blog, like this (untested):

attr_list = []
for cls in Blog.__mro__:
for value in cls.__dict__:
if is_wrapped_method(value):
attr_list.append(value)


A metaclass is probably overkill to assign the wrapped blog methods.
I probably wouldn't even bother with the decorator, and just write the
loop after the class definition.  Then you can use MetaBlog directly
for klass.

class MetaBlog(object):
...

for what in attr_list:
setattr(MetaBlog, what, boilerplate(what))


If it were the kind of thing I found myself doing often I'd refactor
into a decorator.


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


OS X: How to play .wav file w/Python?

2009-05-11 Thread kj

Hi. I'm trying to learn how to play a .wav file in OS X with Python.
I tried the following, which ran without errors, but produced
nothing audible (even though the file bell.wav plays perfectly well
otherwise, e.g. view the Finder's Preview):

import pygame.mixer

pygame.mixer.init()
pygame.mixer.Sound("bell.wav").play
print "done"


What am I doing wrong?

TIA!

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OOP & Abstract Classes

2009-05-11 Thread Terry Reedy

Adam Gaskins wrote:

Wow, thanks Nick! This is just what I was looking for!


I agree that Nick's semi-abstract class is what you need.
After doing some subclasses, you may discover that there is more common 
code that you can factor out and push to the base class.  You may also 
find it convenient to derive a mock subclass that returns simulated data 
so you can test user code initially without involving (or waiting on) 
real devices.


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


Re: How do I test the integrity of a Python installation in Debian and Ubuntu

2009-05-11 Thread Lawrence D'Oliveiro
In message , Geoff 
Gardiner wrote:

> @Lawrence D'Oliveiro:
> ...

I see that you published my unobfuscated e-mail address on USENET for all to 
see. I obfuscated it for a reason, to keep the spammers away. I'm assuming 
this was a momentary lapse of judgement, for which I expect an apology. 
Otherwise, it becomes grounds for an abuse complaint to your ISP.

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


Re: Nimrod programming language

2009-05-11 Thread Lawrence D'Oliveiro
In message <57f4c81a-3537-49fa-a5f6-
a0cc0d43d...@o14g2000vbo.googlegroups.com>, rump...@web.de wrote:

> I am dissatisfied with Python's (or Java's) Unicode handling:
> 1) IO overhead to convert UTF-8 (defacto standard on UNIX) into
> UTF-16.

Are you sure they're using UTF-16? I would use UCS-2 or UCS-4.

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


Re: Re: Complete frustration

2009-05-11 Thread Dave Angel



norseman wrote:
hellcats 
wrote:

I have Python2.5 installed on Windows XP. Whenever I double click on a
something.pyw file, IDLE launches and opens something.pyw in the
editor. I would prefer to actually *RUN* the program, not edit it. If
I want to edit it then I'll choose the "Edit with IDLE" context menu.
So I then have to press F5 to get the program to execute. Now I have
my program's windows along with two IDLE windows cluttering my screen
and task bar. WHAT IS GOING ON? I've tried changing the file
association to python.exe, and that works, but just ONCE (even if I
choose "always use the slected program to launch this kind of file").
IDLE may be great and all, but I fricken' don't want to see it every
time I just want to run a python program!
--
http://mail.python.org/mailman/listinfo/python-list



I agree completely.  Check the Python-List archives. Look for a file 
that is dated July 8, 2008 (07/08/2008) that was sent by norseman.


It works for me.


Steve


For a Unix person, you sure act like you know Windows.  But changing the 
PATH environment variable affects a command typed in the shell, but does 
not affect what happens when you either type the name of a python script 
directly, or when you double-click on such a file.  That's controlled by 
file associations.  (PATH isn't the answer in Unix either, most shells 
use the shebang at the beginning of the script.)


File associations can be controlled in a number of ways.  OPEN-WITH is 
one way.  REGEDIT is another.  In fact, any program can modify these 
settings, including your own scripts.  Something is changing things back 
on you.  But once you're having the problem of things reverting 
"automatically," a command line tool is sometimes the easiest.


Two built-in commands (they're inside the cmd.exe shell) can help.  
They're ASSOC and FTYPE


Since the extension you're bothered by is .pyw, try the following:

C:>  assoc .pyw
.pyw=Python.NoConFile

C:> ftype Python.NoConFile
Python.NoConFile="C:\ProgFiles\Python26\pythonw.exe" "%1" %*


Type them once and copy/paste results somewhere.

Then fix the problem, and look again.  Check that they work by 
double-clicking a xxx.pyw file in Explorer.


Now, run other things, especially IDLE, and recheck these two commands 
to see if something changed.  If it did, then blame whatever program you 
just ran.


My guess is that it changed when some Python installation was done.  And 
some programs have a habit of continually resetting their own 
associations.  Sometimes this is configurable, sometimes you just have 
to stop using the brain-dead program.


Notes:  your path is unlikely to be the same as mine, so replace the 
C:\ProgFiles...  string as appropriate to your preferred Python version 
location. Note you want Pythonw.exe, or you'll wind up with an extra 
shell window.   You can do the same thing for the .py extension, which 
should wind up running python.exe.  And you can make a simple two-line 
batch file to set these (assoc/ftype).  If you had several such batch 
files you could change the default python very easily.  Unlike 
environment variables, these associations are global, across all users, 
across all applications.  So changes made in one shell affect any other 
shells, as well as the Explorer windows.


Final note:  once you've got these right, you can run a script in the 
obvious way (like Unix).

   myprogram.py  parm1 parm2
will actually runpython.exe  myprogram.py  parm1 parm2

And if you add a .PY and .PYW to  PATHEXT environment variable, you can 
just run

   myprogram parm1 parm2
without any extension on the script name.   This should normally be done 
in the Control Panel->Environment vars  so it'll work in multiple DOS 
boxes, same as all environment variable changes.


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


Re: how to consume .NET webservice

2009-05-11 Thread namekuseijin

Diez B. Roggisch wrote:

namekuseijin schrieb:

bav escreveu:

question from a python newbie;

  how can i consume in python language, a .NET web service, passing
  a string array as parameter in some easy steps?


Unless Microsoft extended the standard in any way, then it should be 
just as you consume any web service, I guess. ;)


Microsoft *created* the standard.. 


No:

http://en.wikipedia.org/wiki/Web_service

It's a W3C internet standard.  Microsoft is one of many software 
companies behind the Consortium.


Here's the relevant official standards:

http://www.w3.org/2002/ws/#documents
--
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-11 Thread Tomasz Rola
On Mon, 11 May 2009, rump...@web.de wrote:

> > One question I ask myself upon seeing a new language is if it is possible
> > to program amb (amb=ambiguous) operator in it. This page gives a very
> > nice, "code first" explanation of amb and how it is supposed to work:
> >
> > http://www.randomhacks.net/articles/2005/10/11/amb-operator
> >
> Hm. I am not sure either. To me, it looks like a constraint solver by
> using brute force.

Yes, kind of. From what I understand [1], it's goal is to simulate 
nondeterministic "get right answer in one try", only this "one try" 
requires browsing the solution space (because we have only "classic" 
hardware). It is easy to use amb in wrong way, but I can see some cases 
when I would like it.

[1] John McCarthy's paper still waits to be read by me, so... Ok, I have 
just had a look at it and it seems that Ruby implementation is a bit 
primitive compared to original concept. But still, this is what would be 
needed in most real life cases, I suppose.

I think ability to define amb would allow me to write more concise code. 
As far as I can tell, this kind of stuff plays more and more important 
role in my programing.

> It seems to require continuations. AFAIK
> continuations are extremely hard to implement efficiently, so probably
> it won't be done in Nimrod.

Pity, a little. But not really big problem for me. Nimrod may be 
interesting anyway, time will tell :-).

Regards,
Tomasz Rola

--
** A C programmer asked whether computer had Buddha's nature.  **
** As the answer, master did "rm -rif" on the programmer's home**
** directory. And then the C programmer became enlightened...  **
** **
** Tomasz Rola  mailto:tomasz_r...@bigfoot.com **
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-11 Thread Paul Rubin
rump...@web.de writes:
> I am dissatisfied with Python's (or Java's) Unicode handling:
> 1) IO overhead to convert UTF-8 (defacto standard on UNIX) into
> UTF-16.

So use UTF-8 internally.  You can still iterate through strings
efficiently.  Random access would take a performance hit.  When that's
an issue, the programmer can choose to use a char array (char =
UCS-4).  The same generic functions could largely handle both types.
 
> That is already the case: The Pascal version is translated to Nimrod
> and than compiles itself. Bootstrapping works.

I meant why not get rid of the translation step and implement the
compiler in idiomatic Nimrod.


> Or - if you don't want the "openarray[T]" restriction:
> proc map[T, S, U](data: T, op: proc(x: U): S): seq[S] =
>   result = @[]
>   for d in items(data): result.add(op(d))

This is hard for me to comprehend but I mayb look at the docs to try to
figure it out.

> The plan is to use LLVM as a backend and perhaps
> http://tinystm.org/. Of course, this is only wishful thinking. ;-)

Oh cool, I didn't know about tinystm.  But, my question about
mutability is how you protect STM transactions when other threads can
have references into shared mutable structures and clobber the
referents.  GHC uses its type system to prevent that, but I don't see
how Nimrod can really do the same, especially without GHC's rich set
of immutable types including stuff like immutable maps.

Have you ever looked at Tim Sweeney's presentation "The Next
Mainstream Programming Language"?  It's at:

http://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/sweeny.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Your Favorite Python Book

2009-05-11 Thread Shawn Milochik
On Mon, May 11, 2009 at 5:52 PM,   wrote:
> Sam,
>
> In no specific order (I brought them all):
>
> Wesley Chun's "Core Python Programming"
> David Mertz's "Text Processing in Python" (older, but excellent)
> Mark Lutz's "Learning Python"
>
> All highly recommended.
>
> Best of luck on your Python journey!
>
> Regards,
> Malcolm
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I second the Wesley Chun recommendation wholeheartedly. Also, "Text
Processing in Python" is available for free online.

http://gnosis.cx/TPiP/

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


Re: sqlite single transaction without foreign key or triggers

2009-05-11 Thread gert
On 11 mei, 23:07, Rob Williscroft  wrote:
> gert wrote in news:d7591495-4661-4243-ad7e-f142d8244e88
> @e24g2000vbe.googlegroups.com in comp.lang.python:
>
> > I am trying to do this in a single transaction, the 3 separate
> > statements work fine, but i am screwed if they are not executed
> > together.
>
> Well you're in luck, Python DBAPI 2 connections handle this
> for you, you do need to call commit() on the connection though.
>
> The default, for DBAPI 2 connections, is that all "work" occurs in a
> transaction (if the DB actually supports transactions) so you have to
> call commit() on the connection after doing updates.
>
>
>
> >  ### db.execute('BEGIN') #
> >  db.execute('UPDATE users SET uid=? WHERE uid=?',(v['uid'],s.UID))
>
> This is a fragile way to do it, your code won't work with a DB that
> has real foreign keys (and maybe sqlite will get them one day).
>
> A less fragile way of doing it is:
>
> db = connection.cursor()
>
> # First copy the row if it exists
>
> db.execute( '''
>         insert into "users"
>         select ?, "name", adress, city, country, phone, picture
>         from "users" where "uid" = ?        
>     ''', (v['uid'],s.UID)
>   )
>
> >  db.execute('UPDATE sessions SET uid=? WHERE sid=?',(v['uid'],s.SID))
>
> # Second update foriegn key tables to point to the new row
> # (but only if the new row exists )
>
> db.execute( '''
>         update "sessions" set "uid" = ?
>         where "uid" = ?
>         and exists(
>                 select * from "users" where "uid" = ?
>           )
>     ''',
>     (v['uid'],s.SID, v['uid'])
>   )
>
> #Do the same for the "groups" table, then
>
> # finally delete the original row (again only if the new row exists )
>
> db.execute( '''
>         delete from "users"
>         where "uid" = ?
>         and exists(
>                 select * from "users" where "uid" = ?
>           )
>     ''',
>     (s.SID, v['uid'])
>   )
>
> # Finally commit the transaction
>
> connection.commit()
>
> >  # only do this if there is no primary key conflict in the above
> >  if db.ERROR == None: db.execute('UPDATE groups SET uid=? WHERE uid=?',
> > (v['uid'],s.UID))
>
> Python reports errors by throwing exceptions, so if you needed somthing
> like this it would more likely be:
>
> try:
>
>   ... # somthing that errors up ...
>
> catch sqlite3.DatabaseError:
>   connection.rollback()
>
> Rob.
> --http://www.victim-prime.dsl.pipex.com/

ok go it, thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MacPython 3.0.1 installation problem, no /usr/local/bin/python*

2009-05-11 Thread Raoul Gough
Ned Deily  writes:

> In article 
> ,
>  Benjamin Kaplan  wrote:
>> On Sat, May 9, 2009 at 4:30 AM, Raoul Gough
>>  wrote:
[snip]
>> > So did something go wrong with the installer, or is it all
>> > supposed to work somehow differently?
>> 
>> Because Python 3 breaks compatibility with Python 2, the installers
>> don't install it as the default. The executable should be at
>> /usr/local/bin/python3.0
>
> By default, the 3.0.1 installer does not install any links in
> /usr/local/bin.  To do so, run or re-run the installer, click
> Customize, and then select the "UNIX command-line tools" package.
> That creates /usr/local/python3.0 and /usr/local/python links, among
> others.

Ah, I see! Thanks, I missed the "Customize" option during the install
dialogues. That takes care of the symlinks in /usr/local/bin, although
I notice that it still leaves some dangling symlinks under
/Library/Frameworks/Python.framework that point to a nonexistent
"Current" directory. I guess it's safe to ignore these.

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


Re: Wrapping comments

2009-05-11 Thread Rhodri James

On Mon, 11 May 2009 08:39:48 +0100, Tobias Weber  wrote:


In article ,
 "Rhodri James"  wrote:


What on earth are you talking about?  '#' has its own key on a UK layout


Not on Apple keyboards, and the emacs release in question is Mac only.


My commiserations.  That was a bad design decision on so many levels.

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


Re: issue with twisted and reactor. Can't stop reactor

2009-05-11 Thread Gabriel
Jean-Paul Calderone escribió:
 > None of the reactors in Twisted are restartable.  You can run and
stop them
> once.  After you've stopped a reactor, you cannot run it again.  This is
> the
> cause of your problem.
> 
> Jean-Paul

I see.
Is it possible to do what I want using twisted? or
I should found another way?

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


Re: There may be a much better way to manage artillery.

2009-05-11 Thread Rhodri James

On Mon, 11 May 2009 22:59:43 +0100, Tobiah  wrote:


On Mon, 11 May 2009 00:48:25 +0100, Rhodri James wrote:


On Mon, 11 May 2009 00:06:34 +0100, Tobiah  wrote:

[Snippety snip]


I wanted the bullets to be responsible for destroying themselves, but a
little Googling brought me to points about dangling references and how
an object is not allowed (nor does it seem to have the means) to  
destroy

itself. That's why I made this wrapper class for all of the bullets.


An object can, however, erase its representation from the screen and  
tell

whatever control system is keeping track of objects to forget about it.
Once the last reference to the object is deleted, the object will be
garbage collected.

What framework are you writing your game in?  Pygame has facilities for
handling this sort of thing fairly straightforwardly.


Actually I am using Pygame, although I'm quite new to it.  Which
module has the facilities that you describe?


Looking at the code, it's not quite as straightforward as I was making
out!  I'm used to writing games using a veneer library which has a
Screen class that handles all the basic drawing functions and the main
processing loop.  It keeps a list of objects, and is responsible for
calling appropriate methods on those objects when things happen.
The Object class has a destroy() method which erases the object and
asks the Screen to remove it from its internal list.  Needless to
say there is a lot of list copying going on in the Screen class
main loop to make sure that lists aren't corrupted as they are being
iterated through.

This code was written back in the days of Python 2.1, and hasn't had
more than simple bug-fixing done to it since.  We're contemplating a
rewrite when we shift to Python 3, and we're putting that decision
off as long as possible :-)  You're welcome to use or scavenge from
it, as it's on a fairly free license.  It's available here:

  http://www.livewires.co.uk/python/home

(though apparently I must go and bug the webmaster about putting the
latest version of the worksheets up.  What's there at the moment is
years out of date!)

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


Re: Nimrod programming language

2009-05-11 Thread Mensanator
On May 11, 4:55 pm, rump...@web.de wrote:
> On 10 Mai, 10:40, Paul Rubin  wrote:> Andreas 
> Rumpf  writes:
> > > I invented a new programming language called "Nimrod" that combines
> > > Python's readability with C's performance. Please check it out:
> > >http://force7.de/nimrod/Anyfeedback is appreciated.
>
> > Looks nice in many ways.  You also know about PyPy and Felix
> > (felix.sf.net)?
>
> Nimrod has very different goals from PyPy, I cannot comment on Felix.
>
> > It seems a little bit hackish that the character type is a byte.
> > Python did something like that but it ended up causing a lot of
> > hassles when dealing with real Unicode.  I think you have to bite
> > the bullet and have separate byte and char types, where char=unicode.
>
> I am dissatisfied with Python's (or Java's) Unicode handling:
> 1) IO overhead to convert UTF-8 (defacto standard on UNIX) into
> UTF-16.
> 2) For simple tasks the output file will be in the same encoding as
> the input file automatically.
> 3) Most text files have no header specifying the encoding anyway. How
> should the programm/programmer know? And often he does not need to
> know anyway.
> 4) UTF-16 (or 32) use more memory.
> 5) In particular using UTF-16 internally does not make sense: It just
> encourages programmers to ignore surrogates. Unicode has more than
> 2^16 characters nowadays.
>
> > It scares me a little about how there are references that can have
> > naked pointers, escape the gc, etc.  It would be good if the type
> > system were powerful enough to guarantee the absence of these effects
> > in some piece of data, unless the data is somehow marked with an
> > "unsafe" type.
>
> Well "ptr" is unsafe, "ref" is not; mixing the two requires a "cast".
> Basically "cast" is the only unsafe feature.
>
> > I'd like to see ML-like algebraic types with pattern matching, not
> > just tuple unpacking.  
>
> Me too.
>
> > The generic system should be able to analyze the AST of type
> > parameters, e.g. iterator would be able to automatically generate
> > an iterator over a list, a tree, or some other type of structure, by
> > actually figuring out at compile time how T is constructed.
>
> Interesting idea. Right now the generic iterator is named "items" and
> can be overloaded for user-defined types.
>
> > It's sort of surprising that the compiler is written in a Pascal
> > subset.  Why not implement in Nimrod directly, and bootstrap through C?
>
> That is already the case: The Pascal version is translated to Nimrod
> and than compiles itself. Bootstrapping works.
>
> > The language and library are missing arbitrary precision integer
> > arithmetic, using GMP or something like that.
>
> True, but currently not a high priority for me.

Too bad. That makes Nimrod officially "worthless", i.e., of no
value to me.

>
> > It would be good to also be able to have value serialization and
> > deserialization to both human readable (nested lists, etc) and binary
> > (for IPC) formats.
>
> Yes. Planned for version 0.9.0.
>
> > It's not obvious from the blurbs whether simple functional programming
> > is supported, e.g. how would you implement a function like "map" or
> > "filter"?  What would the types be of those two functions?
>
> proc map[T, S](data: openarray[T], op: proc(x: T): S): seq[S] =
>   result = @[]
>   for d in items(data): result.add(op(d))
>
> Or - if you don't want the "openarray[T]" restriction:
> proc map[T, S, U](data: T, op: proc(x: U): S): seq[S] =
>   result = @[]
>   for d in items(data): result.add(op(d))
>
> > The roadmap says you might implement threading with transactional
> > memory.  How will the transactional memory interact with mutable data?
> > Are you going to use OS threads, lightweight threads, or both?
>
> Probably both. Lightweight threads could be done using coroutines and
> explicit task switching. OS threads with transactional memory. The
> plan is to use LLVM as a backend and perhapshttp://tinystm.org/. Of
> course, this is only wishful thinking. ;-)

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


Re: how to consume .NET webservice

2009-05-11 Thread Diez B. Roggisch

namekuseijin schrieb:

bav escreveu:

question from a python newbie;

  how can i consume in python language, a .NET web service, passing
  a string array as parameter in some easy steps?


Unless Microsoft extended the standard in any way, then it should be 
just as you consume any web service, I guess. ;)


Microsoft *created* the standard.. .and how feasible it is to work with 
it, see this :


http://72.249.21.88/nonintersecting/?year=2006&monthnum=11&day=15&name=the-s-stands-for-simple&page=

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


Re: Nimrod programming language

2009-05-11 Thread rumpf_a
> One question I ask myself upon seeing a new language is if it is possible
> to program amb (amb=ambiguous) operator in it. This page gives a very
> nice, "code first" explanation of amb and how it is supposed to work:
>
> http://www.randomhacks.net/articles/2005/10/11/amb-operator
>
Hm. I am not sure either. To me, it looks like a constraint solver by
using brute force. It seems to require continuations. AFAIK
continuations are extremely hard to implement efficiently, so probably
it won't be done in Nimrod.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue with twisted and reactor. Can't stop reactor

2009-05-11 Thread Jean-Paul Calderone

On Mon, 11 May 2009 17:40:57 -0300, Gabriel  wrote:

Hello all!,

I'm trying to implement a simple one way communication using twisted.

[snip]

When I call send the first time it works fine, when I call send a
second time the sender hangs.
[snip]


None of the reactors in Twisted are restartable.  You can run and stop them
once.  After you've stopped a reactor, you cannot run it again.  This is the
cause of your problem.

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


Re: Your Favorite Python Book

2009-05-11 Thread python
Sam,

In no specific order (I brought them all):

Wesley Chun's "Core Python Programming"
David Mertz's "Text Processing in Python" (older, but excellent)
Mark Lutz's "Learning Python"

All highly recommended.

Best of luck on your Python journey!

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


Re: There may be a much better way to manage artillery.

2009-05-11 Thread Tobiah
On Mon, 11 May 2009 00:48:25 +0100, Rhodri James wrote:

> On Mon, 11 May 2009 00:06:34 +0100, Tobiah  wrote:
> 
> [Snippety snip]
> 
>> I wanted the bullets to be responsible for destroying themselves, but a
>> little Googling brought me to points about dangling references and how
>> an object is not allowed (nor does it seem to have the means) to destroy
>> itself. That's why I made this wrapper class for all of the bullets.
> 
> An object can, however, erase its representation from the screen and tell
> whatever control system is keeping track of objects to forget about it. 
> Once the last reference to the object is deleted, the object will be
> garbage collected.
> 
> What framework are you writing your game in?  Pygame has facilities for
> handling this sort of thing fairly straightforwardly.

Actually I am using Pygame, although I'm quite new to it.  Which
module has the facilities that you describe?

Thanks,

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


Re: Nimrod programming language

2009-05-11 Thread rumpf_a
On 10 Mai, 10:40, Paul Rubin  wrote:
> Andreas Rumpf  writes:
> > I invented a new programming language called "Nimrod" that combines
> > Python's readability with C's performance. Please check it out:
> >http://force7.de/nimrod/Any feedback is appreciated.
>
> Looks nice in many ways.  You also know about PyPy and Felix
> (felix.sf.net)?
>
Nimrod has very different goals from PyPy, I cannot comment on Felix.

> It seems a little bit hackish that the character type is a byte.
> Python did something like that but it ended up causing a lot of
> hassles when dealing with real Unicode.  I think you have to bite
> the bullet and have separate byte and char types, where char=unicode.
>
I am dissatisfied with Python's (or Java's) Unicode handling:
1) IO overhead to convert UTF-8 (defacto standard on UNIX) into
UTF-16.
2) For simple tasks the output file will be in the same encoding as
the input file automatically.
3) Most text files have no header specifying the encoding anyway. How
should the programm/programmer know? And often he does not need to
know anyway.
4) UTF-16 (or 32) use more memory.
5) In particular using UTF-16 internally does not make sense: It just
encourages programmers to ignore surrogates. Unicode has more than
2^16 characters nowadays.

> It scares me a little about how there are references that can have
> naked pointers, escape the gc, etc.  It would be good if the type
> system were powerful enough to guarantee the absence of these effects
> in some piece of data, unless the data is somehow marked with an
> "unsafe" type.
>
Well "ptr" is unsafe, "ref" is not; mixing the two requires a "cast".
Basically "cast" is the only unsafe feature.

> I'd like to see ML-like algebraic types with pattern matching, not
> just tuple unpacking.  
>
Me too.

> The generic system should be able to analyze the AST of type
> parameters, e.g. iterator would be able to automatically generate
> an iterator over a list, a tree, or some other type of structure, by
> actually figuring out at compile time how T is constructed.
>
Interesting idea. Right now the generic iterator is named "items" and
can be overloaded for user-defined types.

> It's sort of surprising that the compiler is written in a Pascal
> subset.  Why not implement in Nimrod directly, and bootstrap through C?
>
That is already the case: The Pascal version is translated to Nimrod
and than compiles itself. Bootstrapping works.

> The language and library are missing arbitrary precision integer
> arithmetic, using GMP or something like that.
>
True, but currently not a high priority for me.

> It would be good to also be able to have value serialization and
> deserialization to both human readable (nested lists, etc) and binary
> (for IPC) formats.
>
Yes. Planned for version 0.9.0.

> It's not obvious from the blurbs whether simple functional programming
> is supported, e.g. how would you implement a function like "map" or
> "filter"?  What would the types be of those two functions?
>
proc map[T, S](data: openarray[T], op: proc(x: T): S): seq[S] =
  result = @[]
  for d in items(data): result.add(op(d))

Or - if you don't want the "openarray[T]" restriction:
proc map[T, S, U](data: T, op: proc(x: U): S): seq[S] =
  result = @[]
  for d in items(data): result.add(op(d))


> The roadmap says you might implement threading with transactional
> memory.  How will the transactional memory interact with mutable data?
> Are you going to use OS threads, lightweight threads, or both?
Probably both. Lightweight threads could be done using coroutines and
explicit task switching. OS threads with transactional memory. The
plan is to use LLVM as a backend and perhaps http://tinystm.org/. Of
course, this is only wishful thinking. ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to replace constructor with factory method

2009-05-11 Thread Luis Zarrabeitia
On Monday 11 May 2009 04:39:41 pm roge...@gmail.com wrote:

> so o = A() instead being equivalent to:
>
> s = object()
> A.__init__(s)
> o = s

Actually, it would be more like this:

s = A.__new__(A)
if isinstance(s,A):
A.__init__(s)
o = s

> o = my_factory_function( A )

You could tweak:
*) A's constructor (__new__) [keep in mind the 'insinstance' part]
*) A's initializer (changing the type, and so on... ugly, fragile and 
dangerous, don't ever do it!)
*) A's metaclass (the instantiation happens in the metaclass' __call__ method,
you could rewrite it to suit your needs, as in [1]
*) or, just use a method named A instead of the A class (as the 
multiprocessing.Queue function does)

I would use the 4th option. The fact that python classes are callable allows 
you to switch from instantiation to function calling without having to change 
the user's code.


[1] http://trucosos.crv.matcom.uh.cu/snippets/95/

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Your Favorite Python Book

2009-05-11 Thread Chris Rebert
On Mon, May 11, 2009 at 1:44 PM, Sam Tregar  wrote:
> Greetings.  I'm working on learning Python and I'm looking for good books to
> read.  I'm almost done with Dive into Python and I liked it a lot. I found
> Programming Python a little dry the last time I looked at it, but I'm more
> motivated now so I might return to it.  What's your favorite?  Why?

I like "Python in a Nutshell" as a reference book, although it's now
slightly outdated given Python 3.0's release (the book is circa 2.5).

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating classes with mix-ins

2009-05-11 Thread samwyse
On May 11, 1:16 pm, samwyse  wrote:
> I'm writing a class that derives it's functionality from mix-ins.

While waiting, I gave a try at using class decorators.  Here's what I
came up with:

def add_methods(*m_list, **kwds):
def wrapper(klass):
for m_name in m_list:
def template(self, which, username, password, *args):
if not self.security.isAuthorised(username, password,
which, m_name):
raise Exception('Unauthorised access')
return getattr(self.blog, m_name)(which, *args)
dotted_name = kwds.get('prefix', '') + m_name
template.__name__ = dotted_name
template.__doc__ = dotted_name
setattr(klass, dotted_name, template)
return klass
return wrapper

@add_methods('newPost', 'editPost', 'getPost', 'newMediaObject',
 'getCategories', 'getRecentPosts',
 prefix='metaWeblog.')
class MetaWeblog(object):
def __init__(self,
 securityHandler=SimpleSecurityHandler,
 blogHandler=SimpleBlogHandler):
self.security = securityHandler()
self.blog = blogHandler()

if __name__ == '__main__':
server = SimpleXMLRPCServer(("localhost", 8080))
server.register_instance(MetaWeblog())
server.register_introspection_functions()
server.serve_forever()

The problem that I'm having is that when I call newPost,
SimpleBlogHandler.getRecentPosts gets invoked.  Apparently add_methods
isn't generating unique templates.  I think I need to move 'template'
into another function, but I'm starting to wonder if metaclasses might
work better.  Any ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-11 Thread rumpf_a
On 10 Mai, 07:36, k...@fiber-space.de wrote:
> On 8 Mai, 17:48, Andreas Rumpf  wrote:
>
> > Dear Python-users,
>
> > I invented a new programming language called "Nimrod" that combines 
> > Python's readability with C's performance. Please check it 
> > out:http://force7.de/nimrod/
> > Any feedback is appreciated.
>
> > Regards,
> > Andreas Rumpf
>
> > __
> > GRATIS für alle WEB.DE-Nutzer: Die maxdome Movie-FLAT!
> > Jetzt freischalten unterhttp://movieflat.web.de
>
> On a first impression it looks quite pleasant to me, your new
> language! Two obvious questions on a Python list.
>
> 1) How to interface with Nimrod from Python?
> 2) Lack of typed hash-tables. Is this one of those particular features
> that are planned to be implemented in version 0.80 and summarized
> under "generic containers"?

1) Via a wrapper that is in the works. It will work like embedding
Python into a C application.
2) Yes. Some syntactic sugar will probably be provided, e.g. a
constructor {} like Python. However, I have not made my mind
completely: Maybe they should be built-in? This would allow more
optimizations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I test the integrity of a Python installation in Debian and Ubuntu

2009-05-11 Thread Geoff Gardiner
Aahz wrote:
> ... That seems to demonstrate that regrtest.py is indeed a good mechanism for
> finding out whether it's a b0rked install!
>   

I agree that regrtest.py looks a good mechanism. It just appears that
`apt-get install python` on Debian and Ubuntu brings no tests with it.

@Lawrence D'Oliveiro:

`apt-get install debsums` does indeed show that the packages that it checks 
have matching checksums. `debsums [-a] python` checks all sorts of 
/usr/share/doc/python files while `debsums [-a] python2.5` checks 
/usr/share/doc/python2.5, /usr/lib/python2.5 and others as well. Although that 
wasn't what I was originally looking for it has been helpful.

Thank you for your suggestions.

All the best,
Geoff


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


[silly] Re: issue with twisted and reactor. Can't stop reactor

2009-05-11 Thread Tim Harig
On 2009-05-11, Gabriel  wrote:
> Subject: issue with twisted and reactor. Can't stop reactor

Not having written anything using twisted I cannot help you much with your
code; but, I cannot resist commenting about your subject line:

I suspect that if are having an issue with your reactor after being hit by
a twister[d], then you probably have more at issue then your networking.
My suggestion would be to run or drive away quickly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite single transaction without foreign key or triggers

2009-05-11 Thread Rob Williscroft
gert wrote in news:d7591495-4661-4243-ad7e-f142d8244e88
@e24g2000vbe.googlegroups.com in comp.lang.python:

> I am trying to do this in a single transaction, the 3 separate
> statements work fine, but i am screwed if they are not executed
> together.

Well you're in luck, Python DBAPI 2 connections handle this 
for you, you do need to call commit() on the connection though.

The default, for DBAPI 2 connections, is that all "work" occurs in a 
transaction (if the DB actually supports transactions) so you have to
call commit() on the connection after doing updates.

> 
>  ### db.execute('BEGIN') #
>  db.execute('UPDATE users SET uid=? WHERE uid=?',(v['uid'],s.UID))

This is a fragile way to do it, your code won't work with a DB that
has real foreign keys (and maybe sqlite will get them one day).

A less fragile way of doing it is:

db = connection.cursor()

# First copy the row if it exists

db.execute( '''
insert into "users"
select ?, "name", adress, city, country, phone, picture
from "users" where "uid" = ?
''', (v['uid'],s.UID)
  )

>  db.execute('UPDATE sessions SET uid=? WHERE sid=?',(v['uid'],s.SID))

# Second update foriegn key tables to point to the new row
# (but only if the new row exists )

db.execute( '''
update "sessions" set "uid" = ?
where "uid" = ? 
and exists(
select * from "users" where "uid" = ?
  )
''',
(v['uid'],s.SID, v['uid']) 
  )

#Do the same for the "groups" table, then

# finally delete the original row (again only if the new row exists )

db.execute( '''
delete from "users" 
where "uid" = ?
and exists(
select * from "users" where "uid" = ?
  )
''',
(s.SID, v['uid']) 
  )

# Finally commit the transaction

connection.commit()

>  # only do this if there is no primary key conflict in the above
>  if db.ERROR == None: db.execute('UPDATE groups SET uid=? WHERE uid=?',
> (v['uid'],s.UID))

Python reports errors by throwing exceptions, so if you needed somthing
like this it would more likely be:

try:
  
  ... # somthing that errors up ...

catch sqlite3.DatabaseError:
  connection.rollback()

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to replace constructor with factory method

2009-05-11 Thread Chris Rebert
On Mon, May 11, 2009 at 1:39 PM,   wrote:
> Hi,
>
> Just wonder if it's possible in Python.
>
> what I want is to tweak an existing Python class A with no
> constructor, so that A() results in fuctory method call?
>
> so o = A() instead being equivalent to:
>
> s = object()
> A.__init__(s)
> o = s
>
> becomes:
>
> o = my_factory_function( A )

I believe you'd need to override __new__ for that.
Docs on __new__: http://docs.python.org/reference/datamodel.html#object.__new__

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fill Javascript form

2009-05-11 Thread Shawn Milochik
How is the form "written in JavaScript"? Is it dynamically generated?

In any case, can you just send a POST request if you know the values required?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Your Favorite Python Book

2009-05-11 Thread Shawn Milochik
It depends on what you want to do. If you still want to beef up on
general knowledge, maybe skim through "The Python Cookbook" or
something reference-like.

If you feel ready to start doing something with Python, look into one
of the recent titles that applies Python for a specific purpose.
Examples:

"Gray Hat Python" (debugging, reverse engineering)
"Natural Language Processing with Python" (pre-order at this time)
Any up-to-date (version 1.0 and up) Django book (if you're into Web development)
"Expert Python Programming" (best practices)
"Beginning Python Visualization" (presenting data visually)
"Programming Collective Intelligence" (extracting valuable information
from public data sources, and more)

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


Your Favorite Python Book

2009-05-11 Thread Sam Tregar
Greetings.  I'm working on learning Python and I'm looking for good books to
read.  I'm almost done with Dive into Python and I liked it a lot. I found
Programming Python a little dry the last time I looked at it, but I'm more
motivated now so I might return to it.  What's your favorite?  Why?

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


issue with twisted and reactor. Can't stop reactor

2009-05-11 Thread Gabriel
Hello all!,

I'm trying to implement a simple one way communication using twisted.

Sender:
> send message
> close connection

Receiver:
> receive
> do something
> wait for other message

I'm testing with this simple examples:
Sender:
[code]
class SenderClient(protocol.Protocol):

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

def connectionMade(self):
self.transport.write(self.data)

def dataReceived(self, data):
self.transport.loseConnection()

def connectionLost(self, reason):
pass

class SenderFactory(protocol.ClientFactory):

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

def buildProtocol(self, addr):
return SenderClient(self.data)

def clientConnectionFailed(self, connector, reason):
logger.error("Connection failed. Reason %s" % reason)
reactor.stop()

def clientConnectionLost(self, connector, reason):
reactor.stop()

class Sender(object):

def __init__(self, host='localhost', port=61610):
self.host = host
self.port = port

def send(self, data):
reactor.connectTCP(self.host, self.port, SenderFactory(data))
reactor.run()
[/code]

Receiver:
[code]
from twisted.internet import reactor, protocol

class Receiver(protocol.Protocol):

def dataReceived(self, data):
self.transport.write("success")
print data

def main():
factory = protocol.ServerFactory()
factory.protocol = Receiver
reactor.listenTCP(61610,factory)
reactor.run()

if __name__ == '__main__':
main()
[/code]

When I call send the first time it works fine, when I call send a
second time the sender hangs.
If I hit ctrl+c it throws:

[quote]
.../twisted/internet/base.py", line 527, in stop
"Can't stop reactor that isn't running.")
twisted.internet.error.ReactorNotRunning: Can't stop reactor that isn't running.
[/quote]

Any idea why this is happening?
King regards.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to replace constructor with factory method

2009-05-11 Thread rogeeff
Hi,

Just wonder if it's possible in Python.

what I want is to tweak an existing Python class A with no
constructor, so that A() results in fuctory method call?

so o = A() instead being equivalent to:

s = object()
A.__init__(s)
o = s

becomes:

o = my_factory_function( A )

Thanks,

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


Fill Javascript form

2009-05-11 Thread Matteo
Hi everybody,
I have to fill a web form to authenticate and connect to the internet.
I thought it would have been easy to make a script to do that
automatically
on startup.

Unfortunately, it turned out that the form is written in JavaScript,
and
urllib2 therefore fails to even fetch the form.

The form itself is very simple, just name and password fields and a
"submit"
button.

Do you know of any workaround?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OOP & Abstract Classes

2009-05-11 Thread Adam Gaskins
Wow, thanks Nick! This is just what I was looking for!

Thanks to Peter as well. And as for your suggestion that I probably 
shouldn't mess with things I don't understand and learn the basics first... 
well, that is probably sound advice, but I figured out years ago that I 
learn things best by a) getting in over my head b) panicking a little c) 
sorting it all out, and fianlly d) (in the case of programming) refactoring 
to make it all proper later. It may be bss aackwards but it works for me :-)

I am going to work through these examples in the morning, thanks again guys! 


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


Re: how to consume .NET webservice

2009-05-11 Thread Mike Driscoll
On May 11, 3:09 pm, "bav"  wrote:
> question from a python newbie;
>
>   how can i consume in python language, a .NET web service, passing
>   a string array as parameter in some easy steps?
>
> best regards

You're being pretty vague here. Try using Google first...I got plenty
of hits with "python .net web service". This one sounds good:

http://www.beardygeek.com/2009/01/how-to-call-a-net-webservice-using-python/

It sounds like you consume it much like you do with other web
services...find the API and use Python to access it or create a parser
of some sort.

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


Re: how to consume .NET webservice

2009-05-11 Thread namekuseijin

bav escreveu:

question from a python newbie;

  how can i consume in python language, a .NET web service, passing
  a string array as parameter in some easy steps?


Unless Microsoft extended the standard in any way, then it should be 
just as you consume any web service, I guess. ;)


--
a game sig: http://tinyurl.com/d3rxz9
--
http://mail.python.org/mailman/listinfo/python-list


how to consume .NET webservice

2009-05-11 Thread bav
question from a python newbie;

  how can i consume in python language, a .NET web service, passing
  a string array as parameter in some easy steps?

best regards 


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


Re: Using Pygame with Python

2009-05-11 Thread Mike Driscoll
On May 11, 2:54 pm, cripplem...@gmail.com wrote:
> Hi. I would just like to know which of the versions of python and
> pygame would be best to download for use together. I am a windows xp
> user.

Look at the pygame website to see what the newest version of Python it
supports and go with that unless there are known issues listed. If you
plan to make an executable of the game, then I recommend Python 2.5
since there are some known issues with 2.6 (don't know if that's true
for 3.0 or not, but it's probable).

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


Re: Writing text to a Word Document

2009-05-11 Thread Mike Driscoll
On May 11, 11:27 am, gazath...@gmail.com wrote:
> Hi everyone,
>
> I am trying to write several attributes from a database table and
> using the code below I can write the values however it is only
> overwriting on the first line.
>
> I am new to the win32com bit and I would like to know what is the
> recommended reference to loop down the page and add multiple records
> rather than the worddoc.Content.
>
> I have read a little about writing this to an RTF or htmol but I am
> getting information overload and going nowhere.  Does anyone have a
> nice tutorial out there that simply explains how to do this?
>
> Much appreciated for any thoughts.
>
> Cheers,
>
> Gareth
>
> import win32com.client, arcgisscripting, sys, os
> gp = arcgisscripting.create(9.3)
>
> #Create word document component 
> -http://www.faqts.com/knowledge_base/view.phtml/aid/37034/fid/244
> wordapp = win32com.client.Dispatch("Word.Application") # Create new
> Word Object
> wordapp.Visible = 1 # Word Application should`t be visible
> worddoc = wordapp.Documents.Add() # Create new Document Object
> worddoc.Content.Font.Size = 11
> worddoc.Content.Paragraphs.TabStops.Add (100)
>
> #Setup of GDB Connection
> # Get the Featureclass from the Mobel - Property Box
> PropBox = "C:\\Avon Fire Rescue\\data\AvonFire_1.gdb\\PropertyBox"
>
> # Make a search cursor for the Property Box Feature class
> PBselCur = gp.searchcursor(PropBox)
> PBrow = PBselCur.reset()
> PBrow = PBselCur.next()
>
> #Using the search cursor get the Premise ID from a Property box
>
> while PBrow:
>     PBrowVal = PBrow.getvalue("PremisesID")
>     #Add data to Word Document
>     worddoc.Content.Text = (PBrowVal)
>     PBrow = PBselCur.next()
>
> #worddoc.Close() # Close the Word Document (a save-Dialog pops up)
>
> print "Fin"

What you probably want is something like this:

rng = worddoc.Range(0,0)
while PBrow:
rng.InsertAfter(PBrowVal + "\r\n")  # needs return and new line
character

At least, that's what I found in one of my books. It seemed to work
when I tested it in the interpreter.

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


Using Pygame with Python

2009-05-11 Thread cripplemeal
Hi. I would just like to know which of the versions of python and
pygame would be best to download for use together. I am a windows xp
user.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping comments

2009-05-11 Thread Simon Brunning
2009/5/10 Tobias Weber :
> (still not gonna use software that doesn't let me type # because it's
> alt+3 on a UK layout; having to re-learn or configure that is just sick)

To use Aquamacs with a UK keyboard, you want to select Options, Option
Key, Meta & British. Things just work then.

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


Re: OOP & Abstract Classes

2009-05-11 Thread Peter Otten
Adam Gaskins wrote:

> So I was beginning to learn OOP for PHP, and it seemed to me that abstract
> classes were just right for my application. In my application I must
> communicate with several peices of test equipment that communicate via
> RS-232. Most use SCPI instructions, some do not and require low level
> communication.
> 
> The way I understand abstract classes is that I could have a class that
> has all my abstract methods such as 'init', 'getMeasurement',
> 'setPressure', etc... then I could use this common interface to to control
> my different pieces of hardware (after I write a library for each of
> them).
> 
> Is this a valid application for abstract classes? Or am I making life more
> complicated than it need be?
> 
> Now, I have read that Pythons OOP implimentation is so much better and
> more complete then PHP's, but I cant find anything about abstract classes
> except this:
> http://norvig.com/python-iaq.html
> 
> ...which says it doesn't exist in Python and you can only do this hack to
> make it work (and I don't particularly understand how to impliment it from
> this article).

It is basically a non-implementaton. If you don't understand it you should 
not mess with abstract base classes and work your way through an 
introductory python textbook. 

That said, the page is outdated; Python 2.6 has some support for abstract 
classes. They even fail a bit earlier, when the class is instantiated 
instead of when the method is called. Example:

from abc import ABCMeta, abstractmethod, abstractproperty

class AbstractDevice:
__metaclass__ = ABCMeta

@abstractmethod
def init(self):
pass

@abstractproperty
def pressure(self):
pass


class Compressor(AbstractDevice):
def init(self):
print "starting compressor"

def set_pressure(self, value):
print "setting pressure to", value
pressure = property(fset=set_pressure)

c = Compressor()
c.init()
c.pressure = 42

a = AbstractDevice() # fails with TypeError

 
> This makes me suspect I am making things more comlicated than they need to
> be. Could someone help me understand the proper way to impliment a set
> classes/methods to deal with several peices of similar and not so similar
> hardware? Not looking for anyone to write code for me, just help
> understanding some of these OOP concepts and how they would apply to my
> situation.

Personally I would just write the class I need

class Compressor(object):
def init(self):
print "starting compressor"

def set_pressure(self, value):
print "setting pressure to", value
pressure = property(fset=set_pressure)

and forget about the bureaucracy. Instead I recommend that you learn about 
unit tests and write a few tests to ensure your classes work as specified.

Peter

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


Re: Wrapping comments

2009-05-11 Thread MRAB

norseman wrote:

Tobias Weber wrote:

Hi,
the guideline (PEP 8) is hard wrap to 7x characters. The reason given 
is that soft wrap makes code illegible.


So what if you hard wrap code but let comments and docstrings soft-wrap?

Otherwise it's hugely annoying to edit them. Say you remove the first 
three words of a 150 character sentence. Either keep the ugly or 
rewrap manually.


Or are there editors that can do a "soft hard wrap" while keeping 
indentation and #comment markers intact?




===
Paragraph 1:  65 and 72 cols are US typewriter standard 12 and 10 pt
  respectively. (MSDOS screen, business standard paper, ..)
  And yes, soft wrap does. Check the hardcopy which wraps
  code with lots of long lines.

Paragraph 2:  Comments? I vote no. These are in the code and should
  conform to helping at that location.
  Doc_stuff - I vote yes. For the obvious reason that it
  makes formating the Docs easier AND is to be 'extracted'
  to a separate file for that purpose in the first place.

Paragraph 3:  True

Could you give a short example of what you are referring to in your last 
paragraph?  I showed this to several friends and got several 'views' as 
to what is intended.



I think he means something like:

# 65 and 72 cols are US typewriter standard 12 and 10 pt respectively.

when wrapped to 40 gives:

# 65 and 72 cols are US typewriter
# standard 12 and 10 pt respectively.

and when rewrapped to 60 gives:

# 65 and 72 cols are US typewriter standard 12 and 10 pt
# respectively.

Indentation of lines wouldn't be affected, so:

# 65 and 72 cols are US typewriter standard 12 and 10 pt 
respectively.


when wrapped to 40 gives:

# 65 and 72 cols are US
# typewriter standard 12 and 10
# pt respectively.

and when rewrapped to 60 gives:

# 65 and 72 cols are US typewriter standard 12 and
# 10 pt respectively.



I assume you are NOT intending to use third party programs to write code 
in but rather to use Python somehow?


I assume you are intending that the editor add the backslash newline at 
 appropriate places without causing a word or code break when needed and 
simply wrapping with indent without breaking the code the rest of the 
time and doing so in such a fashion that ALL general text editors will 
be able to display code properly as well as be usable in modifying code?
Not to mention that the interpreter and/or compiler will still be able 
to use the file.



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


Re: OOP & Abstract Classes

2009-05-11 Thread Nick Craig-Wood
Adam Gaskins  wrote:
>  I am a fairly seasoned PHP developer (don't shoot, I'm changing teams!:) who 
>  is admittedly behind the curve with OOP. Like most who learned PHP, I 
>  started doing web app backend stuff, but I have moved to full blown windows 
>  apps in the last 6 months using Winbinder. As you may know Winbinder is 
>  essentially abandoned, and programming windows apps with Winbinder or even 
>  GTK-PHP is less than ideal. I also deal heavily in serial/rs-232 
>  communications which is a pain in PHP. Long story short, I'm tired of doing 
>  things in such a hackish manner and want to write applications that are 
>  cross platform (I'd like to get our production dept on linux eventually) and 
>  truely object oriented.
> 
>  So I was beginning to learn OOP for PHP, and it seemed to me that abstract 
>  classes were just right for my application. In my application I must 
>  communicate with several peices of test equipment that communicate via 
>  RS-232. Most use SCPI instructions, some do not and require low level 
>  communication.
> 
>  The way I understand abstract classes is that I could have a class that has 
>  all my abstract methods such as 'init', 'getMeasurement', 'setPressure', 
>  etc... then I could use this common interface to to control my different 
>  pieces of hardware (after I write a library for each of them).
> 
>  Is this a valid application for abstract classes? Or am I making life more 
>  complicated than it need be?

This sounds like a fine use for Abstract classes.

Python doesn't have language support for them directly, but they are
usually written like this

class DeviceBase(object):
def __init__(self):
raise NotImplementedError()
def getMeasusrement(self):
raise NotImplementedError()
def setPressure(self, pressure):
raise NotImplementedError()

Then subclass it for the real functionality

class RealDevice(DeviceBase):
def __init__(self):
self.pressure = 0
def getMeasusrement(self):
return 0
def setPressure(self, pressure):
self.pressure = pressure

However, I normally found that there is some functionality that is
common to all subclasses so there may be some real methods in your
DeviceBase class, eg

class DeviceBase(object):
def __init__(self, device):
self.device = device
def getMeasurement(self):
raise NotImplementedError()
def setPressure(self, pressure):
raise NotImplementedError()
def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, self.device)

class RealDevice(DeviceBase):
def __init__(self, device):
DeviceBase.__init__(self, device)
self.pressure = 0
def getMeasurement(self):
return self.pressure
def setPressure(self, pressure):
self.pressure = pressure

Which looks like this when you test it

>>> base = DeviceBase("/dev/ttyS0")
>>> base
DeviceBase('/dev/ttyS0')
>>> base.getMeasurement()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in getMeasurement
NotImplementedError
>>> base.setPressure(14)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 7, in setPressure
NotImplementedError
>>>
>>> real = RealDevice("/dev/ttyS1")
>>> real
RealDevice('/dev/ttyS1')
>>> real.getMeasurement()
0
>>> real.setPressure(14)
>>> real.getMeasurement()
14
>>> 

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I get a value's name

2009-05-11 Thread John O'Hagan
On Mon, 11 May 2009, jalanb3 wrote:

[...]

>
> def replace_line(pattern,replacement):
> errors = '\n' in pattern and [ 'pattern' ] or []
> errors += '\n' in replacement and [ 'replacement' ] or []
> values = [ locals()[e] for e in errors ]
> # etc, etc, and eventually:
> print 'Argument %s is bad : "%s"' % (errors[0],values[0])
>
> And the question arises from that locals() line:
> Given a variable name I can use locals() to get the value
> Is there a way to do it the other way round
> Given the value, can I get the variable name ?
>
> For example, suppose I had started like this (using the variables, not
> strings with their names)
>
> def replace_line(pattern,replacement):
> values = '\n' in pattern and [ pattern ] or []
> values += '\n' in replacement and [ replacement ] or []
>
> Can I later get the name "pattern" via values[0]?
>
[...]

def replace_line(pattern,replacement):
values = '\n' in pattern and [ pattern ] or []
values += '\n' in replacement and [replacement] or []
loc=locals()
print [i for i in loc if loc[i] is pattern if pattern in values]

will print ['pattern'] if the value of pattern is in values (if there's a 
newline in pattern). Is that what you're after?

HTH,

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


creating classes with mix-ins

2009-05-11 Thread samwyse
I'm writing a class that derives it's functionality from mix-ins.
Here's the code:

def boilerplate(what):   # This used to be a decorator, but all of
the
##what = f.__name__  # function bodies turned out to be
'pass'.
'Validate the user, then call the appropriate plug-in.'
def template(self, which, username, password, *args):
if not self.security.isAuthorised(username, password,
which, what):
raise Exception('Unauthorised access')
return getattr(self.blog, what)(which, *args)
template.__name__ = what
template.__doc__ = getattr(self.blog, what).__doc__
return template

class MetaWeblog(object):
def __init__(self,
 securityHandler=SimpleSecurityHandler,
 blogHandler=SimpleBlogHandler):
self.security = securityHandler()
self.blog = blogHandler()
newPost = boilerplate('newPost')
editPost = boilerplate('editPost')
getPost = boilerplate('getPost')
# etc, etc, etc

I'd like to replace the method definitions with a loop:
for what in attr_list:
setattr(klass, what, boilerplate(what))

That begs the question of where I define 'klass' and 'attr_list'.
Should I use a class decorator, or a metaclass?  In favor of
decorators is that I can see how to do it; in favor of a metaclass is
that I get to learn how to use them.  ;-)  What are the other pros and
cons for each choice?
-- 
http://mail.python.org/mailman/listinfo/python-list


sqlite single transaction without foreign key or triggers

2009-05-11 Thread gert
I am trying to do this in a single transaction, the 3 separate
statements work fine, but i am screwed if they are not executed
together.

 ### db.execute('BEGIN') #
 db.execute('UPDATE users SET uid=? WHERE uid=?',(v['uid'],s.UID))
 db.execute('UPDATE sessions SET uid=? WHERE sid=?',(v['uid'],s.SID))
 # only do this if there is no primary key conflict in the above
 if db.ERROR == None: db.execute('UPDATE groups SET uid=? WHERE uid=?',
(v['uid'],s.UID))
 ### db.execute('END') #

My tables are as follows

CREATE TABLE users (
uid VARCHAR(64) PRIMARY KEY,
nameVARCHAR(64) DEFAULT '',
adress  VARCHAR(64) DEFAULT '',
cityVARCHAR(64) DEFAULT '',
country VARCHAR(64) DEFAULT '',
phone   VARCHAR(64) DEFAULT '',
picture BLOB
);

CREATE TABLE groups (
gid VARCHAR(64),
uid VARCHAR(64),
PRIMARY KEY(gid,uid),
FOREIGN KEY(uid) REFERENCES users(uid) ON UPDATE CASCADE ON DELETE
CASCADE
);

CREATE TABLE sessions (
uid VARCHAR(64) UNIQUE,
pwd VARCHAR(64) DEFAULT '',
sid VARCHAR(64) PRIMARY KEY,
exp DATETIME,
FOREIGN KEY(uid) REFERENCES users(uid) ON UPDATE CASCADE ON DELETE
CASCADE
);

What is the python or sql way of doing this kind of things ?


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


Re: Can I get a value's name

2009-05-11 Thread Scott David Daniels

jalanb3 wrote:

... Given a variable name I can use locals() to get the value
Is there a way to do it the other way round
Given the value, can I get the variable name ?


(1) Yes you can in some cases.
(2) You should not, things do not inherently have a name.

With that prelude:
def find_names(value, dictionary):
for name, val in dictionary.items():
if val is value: # note: "is", not "=="
yield name

x = 123456
y = 123456 * 3 // 3
z = 123456.0
q = y
print list(find_names(y, locals()))

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: OOP & Abstract Classes

2009-05-11 Thread Adam Gaskins
Any idea why I didn't see this reply on my ng? I only see the reply from 
Marco. Can't help but wonder if there is more that is not getting through 
here.

Would someone mind forwarding me any other replies?

FWIW I'm using news.east.cox.net.

Thanks,
-Adam

> Mike Driscoll wrote:
>
>> I've never used (or heard of) the Abstract type...and the guy who
>> wrote the FAQ was being a jerk.


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


Re: Decorating methods - where do my arguments go?

2009-05-11 Thread Peter Otten
Mikael Olofsson wrote:

> Duncan Booth wrote:
> 
>> The __get__ method should be returning a new object, NOT modifying the
>> state of the decorator. As written it will break badly and unexpectedly
>> in a variety of situations:
>> 
>> [snip good examples of things going bad]
> 
> Ouch! So, does that mean that George's solution based on a function is
> the way to go, or does that mean that my __call__ should analyze the
> passed callable?

I usually use decorator functions, but I think the following should work, 
too:

class deco(object):
def __init__(self, func):
self._func = func
def __call__(self, *args):
print "Decorator:", args
self._func(*args)
def __get__(self, *args):
return deco(self._func.__get__(*args))

Peter

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


Re: list comprehension question

2009-05-11 Thread J Kenneth King
Steven D'Aprano  writes:

> On Thu, 07 May 2009 13:28:10 -0400, J Kenneth King wrote:
>
>> Steven D'Aprano  writes:
>> 
>>> On Wed, 06 May 2009 09:48:51 -0400, J Kenneth King wrote:
>>>
 Emile van Sebille  writes:
 
> On 5/5/2009 9:15 AM J Kenneth King said...
>
>> List comprehensions can make a reader of your code apprehensive
>> because it can read like a run-on sentence and thus be difficult to
>> parse. The Python documentation discourages their use and I believe
>> for good reason.
>
> Can you provide a link for this?  I'd like to see specifically what's
> being discouraged, as I'd be surprised to find routine usage frowned
> upon.
>
> Emile
 
 http://docs.python.org/tutorial/datastructures.html#nested-list-
>>> comprehensions
 
 
 "If you’ve got the stomach for it, list comprehensions can be nested.
 They are a powerful tool but – like all powerful tools – they need to
 be used carefully, if at all."
>>>
>>> How does this discourage the use of list comprehensions? At most, it
>>> warns that complicated list comps are tricky. Complicated *anything*
>>> are tricky.
>> 
>> They are tricky and need to be used carefully, *if at all*.
>> 
>> IMO this means that if there's a way to do it without a nested list
>> comprehension, then that solution should be preferred.
>
> Earlier, you claimed that list comps in general were discouraged:
>
> "List comprehensions can make a reader of your code apprehensive because 
> it can read like a run-on sentence and thus be difficult to parse. The 
> Python documentation discourages their use and I believe for good reason."

Ooops. Typo. My bad. Had it been quoted earlier it would have saved a
few posts for sure. Such is the Internet. :)

> Emile said "I'd be surprised to find routine usage frowned upon", giving 
> you the opportunity to correct his (mis)understanding. You failed to do 
> so, which I took as meaning that you agreed that routine usage of simple 
> list comps were frowned upon. Now you're talking about *nested* list 
> comps. You started off (apparently) objecting to list comps in general, 
> because they "can" make readers apprehensive. Now you seem to be saying 
> that it's only the complicated, overly-dense ones which rightly make 
> readers apprehensive which you object to.

I was rather confused by that. I use list comps all the time and said
several times that I don't object to list comps, just nested ones.

> I suppose we're making progress if we agree that the Python docs warn 
> against unnecessarily complicated nested list comps. Whether it 
> discourages as well as warns is a matter of interpretation. But there's 
> certainly no sign that list comps as a general technique are discouraged 
> just because overly-complicated list comps are tricky to read. The same 
> can be said about *any* piece of code.

Well I did my best to make my interpretation clear. If the
documentation says that nested list comps are difficult to read and
should be used rarely, if at all, then I generally consider that
"discouraging" their use. Meaning of course that in the right
situation one may be able to justify their own use of a nested comp.
However, for every day problems one wouldn't be encouraged to use them
so liberally as some tend to do.


So.. we have some sort of consensus then? This might be a rare
phenomenon on Usenet... :)

Cheers,

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


Writing text to a Word Document

2009-05-11 Thread gazathome
Hi everyone,

I am trying to write several attributes from a database table and
using the code below I can write the values however it is only
overwriting on the first line.

I am new to the win32com bit and I would like to know what is the
recommended reference to loop down the page and add multiple records
rather than the worddoc.Content.

I have read a little about writing this to an RTF or htmol but I am
getting information overload and going nowhere.  Does anyone have a
nice tutorial out there that simply explains how to do this?

Much appreciated for any thoughts.

Cheers,

Gareth

import win32com.client, arcgisscripting, sys, os
gp = arcgisscripting.create(9.3)

#Create word document component - 
http://www.faqts.com/knowledge_base/view.phtml/aid/37034/fid/244
wordapp = win32com.client.Dispatch("Word.Application") # Create new
Word Object
wordapp.Visible = 1 # Word Application should`t be visible
worddoc = wordapp.Documents.Add() # Create new Document Object
worddoc.Content.Font.Size = 11
worddoc.Content.Paragraphs.TabStops.Add (100)

#Setup of GDB Connection
# Get the Featureclass from the Mobel - Property Box
PropBox = "C:\\Avon Fire Rescue\\data\AvonFire_1.gdb\\PropertyBox"

# Make a search cursor for the Property Box Feature class
PBselCur = gp.searchcursor(PropBox)
PBrow = PBselCur.reset()
PBrow = PBselCur.next()

#Using the search cursor get the Premise ID from a Property box

while PBrow:
PBrowVal = PBrow.getvalue("PremisesID")
#Add data to Word Document
worddoc.Content.Text = (PBrowVal)
PBrow = PBselCur.next()

#worddoc.Close() # Close the Word Document (a save-Dialog pops up)

print "Fin"

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


Re: How to debug this import problem?

2009-05-11 Thread Iwan
Mmm, we solved half of the cause of this one.

Test runs are kicked off via setuptools's test command. But this
happens programmatically, and successively in one process.  But
setuptools's test command clears all modules imported during a test
run from sys.modules - hence it is intended that modules would be re-
imported.

Why certain of our code managed to still get to the classes contained
in prior imports is still a mystery though.

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


Re: Decorating methods - where do my arguments go?

2009-05-11 Thread Mikael Olofsson

Duncan Booth wrote:

The __get__ method should be returning a new object, NOT modifying the 
state of the decorator. As written it will break badly and unexpectedly 
in a variety of situations:


[snip good examples of things going bad]


Ouch! So, does that mean that George's solution based on a function is 
the way to go, or does that mean that my __call__ should analyze the 
passed callable?


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


Re: OOP & Abstract Classes

2009-05-11 Thread Marco Mariani

Mike Driscoll wrote:


I've never used (or heard of) the Abstract type...and the guy who
wrote the FAQ was being a jerk.


Who, Peter Norvig?

(from wikipedia)

Peter Norvig is an American computer scientist. He is currently the 
Director of Research (formerly Director of Search Quality) at Google Inc.


He is a Fellow and Councilor of the American Association for Artificial 
Intelligence and co-author, with Stuart Russell, of Artificial 
Intelligence: A Modern Approach, now the standard college text. He 
previously was head of the Computational Sciences Division (now the 
Intelligent Systems Division) at NASA Ames Research Center, where he 
oversaw a staff of 200 scientists performing NASA's research and 
development in autonomy and robotics, automated software engineering and 
data analysis, neuroengineering, collaborative systems research, and 
simulation-based decision-making. Before that he was Chief Scientist at 
Junglee, where he helped develop one of the first Internet comparison 
shopping services; Chief designer at Harlequin Inc.; and Senior 
Scientist at Sun Microsystems Laboratories.


etc. etc.


Yes, I usually look up in wikipedia before calling anyone a jerk :) :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: mod_python and xml.dom.minidom

2009-05-11 Thread dpapathanasiou
For the record, and in case anyone else runs into this particular
problem, here's how resolved it.

My original xml_utils.py was written this way:

from xml.dom import minidom

def parse_item_attribute (item, attribute_name):
item_doc = minidom.parseString(item)
...

That version worked under the python interpreter, but failed under
both mod_python and mod_wsgi apache modules with an error ("Parent
module 'xml.dom' not loaded").

I found that changing the import statement and the minidom reference
within the function resolved the problem.

I.e., after rewriting xml_utils.py this way, it works under both
apache modules as well as in the python interpreter:

import xml.dom.minidom

def parse_item_attribute (item, attribute_name):
item_doc = xml.dom.minidom.parseString(item)
...

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


Re: OOP & Abstract Classes

2009-05-11 Thread Ulrich Eckhardt
Adam Gaskins wrote:
> Long story short, I'm tired of doing things in such a hackish manner
> and want to write applications that are cross platform (I'd like to
> get our production dept on linux eventually) and truely object
> oriented. 

Adam, there is one notion here that I seriously dislike: you sound as if OOP
was a goal by itself for you. The point is that OOP is a tool, not a goal.
So, if it helps you do the things you really want, go ahead and use it.
Otherwise, just don't.

> The way I understand abstract classes is that I could have a class that
> has all my abstract methods such as 'init', 'getMeasurement',
> 'setPressure', etc... then I could use this common interface to to control
> my different pieces of hardware (after I write a library for each of
> them).
> 
> Is this a valid application for abstract classes? Or am I making life more
> complicated than it need be?

I think that the term is rather "abstract base class" (ABC,
a.k.a. "interface"). Note that in Python, where you don't have to use
prototypes or declaration, you often don't do that. Instead you use "duck
typing", i.e. you simply create different classes for the different
hardware and if all of them support 'init' and 'setPressure' instances are
interchangeable ("Liskov substitution principle", IIRC) without knowing
anything about each other.

> This makes me suspect I am making things more comlicated than they need to
> be. Could someone help me understand the proper way to impliment a set
> classes/methods to deal with several peices of similar and not so similar
> hardware?

Just write a class for each piece and adhere to a common interface and
you're done.

;)

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: OOP & Abstract Classes

2009-05-11 Thread Mike Driscoll
On May 11, 9:53 am, "Adam Gaskins" 
wrote:
> Hi all,
>
> -- Non critical info--
> I am a fairly seasoned PHP developer (don't shoot, I'm changing teams!:) who
> is admittedly behind the curve with OOP. Like most who learned PHP, I
> started doing web app backend stuff, but I have moved to full blown windows
> apps in the last 6 months using Winbinder. As you may know Winbinder is
> essentially abandoned, and programming windows apps with Winbinder or even
> GTK-PHP is less than ideal. I also deal heavily in serial/rs-232
> communications which is a pain in PHP. Long story short, I'm tired of doing
> things in such a hackish manner and want to write applications that are
> cross platform (I'd like to get our production dept on linux eventually) and
> truely object oriented.
> -- END non critical stuff--
>
> So I was beginning to learn OOP for PHP, and it seemed to me that abstract
> classes were just right for my application. In my application I must
> communicate with several peices of test equipment that communicate via
> RS-232. Most use SCPI instructions, some do not and require low level
> communication.
>
> The way I understand abstract classes is that I could have a class that has
> all my abstract methods such as 'init', 'getMeasurement', 'setPressure',
> etc... then I could use this common interface to to control my different
> pieces of hardware (after I write a library for each of them).
>
> Is this a valid application for abstract classes? Or am I making life more
> complicated than it need be?
>
> Now, I have read that Pythons OOP implimentation is so much better and more
> complete then PHP's, but I cant find anything about abstract classes except
> this:http://norvig.com/python-iaq.html
>
> ...which says it doesn't exist in Python and you can only do this hack to
> make it work (and I don't particularly understand how to impliment it from
> this article).
>
> This makes me suspect I am making things more comlicated than they need to
> be. Could someone help me understand the proper way to impliment a set
> classes/methods to deal with several peices of similar and not so similar
> hardware? Not looking for anyone to write code for me, just help
> understanding some of these OOP concepts and how they would apply to my
> situation.
>
> Thanks!
> -Adam

I've never used (or heard of) the Abstract type...and the guy who
wrote the FAQ was being a jerk. It looks like he was just throwing in
an undefined variable name just to make his Python program break while
taking a pot shot at people who use that sort of thing. Whatever.

According to wikipedia, dynamic languages don't implement Abstract as
they can accomplish the same thing via duck typing:
http://en.wikipedia.org/wiki/Abstract_class .  The way it describes
the class, it made me think of decorators as well.

Hopefully someone who has used Abstract classes will jump in here and
give you more information about whether or not they matter in Python.

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


Re: How do I test the integrity of a Python installation in Debian and Ubuntu

2009-05-11 Thread Aahz
In article ,
Geoff Gardiner   wrote:
>Aahz wrote:
>> 
>> What directory are you running this from?  What happens if you switch to
>> running "python Lib/test/regrtest.py"?  Taking a closer look, this looks
>> more like a plain import error.
>
>I couldn't do quite that because there's no Lib, but instead (in Ubuntu
>Hardy, this time):
>
>geg...@gegard:~$ cd /usr/lib/python2.5/
>geg...@gegard:/usr/lib/python2.5$ python test/regrtest.py
>
>9 tests skipped:
>test_builtin test_doctest test_doctest2 test_exceptions
>test_grammar test_opcodes test_operations test_types test_unittest
>Traceback (most recent call last):
>  File "test/regrtest.py", line 1384, in 
>main()
>  File "test/regrtest.py", line 416, in main
>e = _ExpectedSkips()
>  File "test/regrtest.py", line 1321, in __init__
>from test import test_socket_ssl
>ImportError: cannot import name test_socket_ssl
>geg...@gegard:/usr/lib/python2.5$
>
>Also
>geg...@gegard:~$ locate */test_socket_ssl.*
>geg...@gegard:~$ #returns nothing
>
>And
>geg...@gegard:~$ locate /usr/lib/python2.5/test/test_*.*
>/usr/lib/python2.5/test/test_support.py
>/usr/lib/python2.5/test/test_support.pyc
>geg...@gegard:~$

That seems to demonstrate that regrtest.py is indeed a good mechanism for
finding out whether it's a b0rked install!
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the use of the else in try/except/else?

2009-05-11 Thread kj
In  Scott David Daniels 
 writes:

>kj wrote:
>> ...  I can't come with an example in which the same couldn't be
>> accomplished with
>> 
>> try:
>> # do something
>> # do something else
>> except ...:
>> # handle exception
>> 
>> The only significant difference I can come up with is that in the
>> second form, the except clause may be masking some unexpected
>> exceptions from the "do something else" part.  Is this the rationale
>> behind this else clause?  Or is there something more to it?

>Yes, in a way.  The idea of catching particular exceptions is to only
>handle exceptions you expect (let the others go out to more general
>reporters).  So, not only should you choose the tightest exception to
>catch that you can, but you should look for it in a very narrow window:
>exactly where you expect it.

> try:
> v = mumble.field
> except AttributeError:
> pass
> else:
> sys.warning('field was actually there?')

>as opposed to:

> try:
> v = mumble.field
> sys.warning('field was actually there?')
> except AttributeError:
> pass

>The idea is to make it clear what you expect might go
>wrong that you are prepared to handle.

Wow.  As rationales for syntax constructs go, this has got to be
the most subtle one I've ever seen...

Thanks!

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorating methods - where do my arguments go?

2009-05-11 Thread Duncan Booth
Mikael Olofsson  wrote:

> George Sakkis decorator function solution seems to work equally well 
for 
> functions and methods. However, I prefer the cleaner encapsulation 
given 
> by a class. Based on those observations, I think I will use the 
> following approach:
> 
> >>> class test_decorator(object):
> ... _inst = None
> ... def __init__(self,func):
> ... self._func = func
> ... def __call__(self, *args):
> ... print 'Decorator:', args
> ... if self._inst is None:
> ... print 'We seem to be decorating a function.'
> ... self._func(*args)
> ... else:
> ... print 'We seem to be decorating a method.'
> ... self._func(self._inst,*args)
> ... def __get__(self, inst, cls):
> ... self._inst = inst
> ... return self
> ...

The __get__ method should be returning a new object, NOT modifying the 
state of the decorator. As written it will break badly and unexpectedly 
in a variety of situations:

>>> inst1 = cls()
>>> inst2 = cls()
>>> inst1, inst2
(<__main__.cls object at 0x011BC470>, <__main__.cls object at 
0x011BCC90>)
>>> m = inst1.meth
>>> m()
Decorator: ()
We seem to be decorating a method.
Method:<__main__.cls object at 0x011BC470> ()
>>> inst2.meth()
Decorator: ()
We seem to be decorating a method.
Method:<__main__.cls object at 0x011BCC90> ()
>>> m()
Decorator: ()
We seem to be decorating a method.
Method:<__main__.cls object at 0x011BCC90> ()

or even this:

>>> inst1.meth(inst2.meth())
Decorator: ()
We seem to be decorating a method.
Method:<__main__.cls object at 0x011BCC90> ()
Decorator: (None,)
We seem to be decorating a method.
Method:<__main__.cls object at 0x011BCC90> (None,)



-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stand alone exec

2009-05-11 Thread Pascal Chambon

Hello

It sounds indeed like a runtime library problem...

You should run a dependancy finder (like dependency walker - 
http://www.dependencywalker.com/) on your executable, and thus see what 
might be lacking on other systems.
I know that on *nix systems there are tools to see more precisely what's 
missing, but on windows, exept that tool I don't know much.


Regards,
Pascal



prakash jp a écrit :

Hi all,
 
I want to run dos commands through python stand alone execs. The 
created Python stand alone executable (py2exe)  works fine
 
in my machine but on transferring the "dist" folder to other systems 
the executable fails to run.
 
I tried to copy the MSVCP90.dll in the "dist" folder. Also tried to 
exclude the same dll in the options of the setup.py file
 
The error reads as follows :
 
"The application has failed to start because the application 
configuration is incorrect. Reinstalling the application may fix this 
problem".
 
Details of the installed setup files may be useful :
 
1- python-2.6.1.msi

2- py2exe-0.6.9.win32-py2.6.exe
3- pywin32-212.win32-py2.6.exe
 
Thanks in advance
 
Regards

Prakash


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


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


Re: unicode bit me

2009-05-11 Thread norseman

Steven D'Aprano wrote:

On Fri, 08 May 2009 14:22:32 -0400, Terry Reedy wrote:


Scott David Daniels wrote:


It would be a bit easier if people would bother to mention their
Python version, as we regularly get questions from people running 2.3,
2.4, 2.5, 2.6, 2.7a, 3.0, and 3.1b.  They run computers with differing
operating systems and versions such as: Windows 2000, OS/X Leopard,
ubuntu Hardy Heron, SuSE, 

And if they copy and paste the actual error messages instead of saying
'It doesn't work'


"I tried to copy and paste the actual error message, but it doesn't 
work..."



*grin*



==
In Linux get/use gpm and copy paste is simple.
In Microsoft see:  Python-List file dated  May 6, 2009 (05/06/2009) sent 
by norseman.

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


Re: Wrapping comments

2009-05-11 Thread norseman

Tobias Weber wrote:

Hi,
the guideline (PEP 8) is hard wrap to 7x characters. The reason given is 
that soft wrap makes code illegible.


So what if you hard wrap code but let comments and docstrings soft-wrap?

Otherwise it's hugely annoying to edit them. Say you remove the first 
three words of a 150 character sentence. Either keep the ugly or rewrap 
manually.


Or are there editors that can do a "soft hard wrap" while keeping 
indentation and #comment markers intact?




===
Paragraph 1:  65 and 72 cols are US typewriter standard 12 and 10 pt
  respectively. (MSDOS screen, business standard paper, ..)
  And yes, soft wrap does. Check the hardcopy which wraps
  code with lots of long lines.

Paragraph 2:  Comments? I vote no. These are in the code and should
  conform to helping at that location.
  Doc_stuff - I vote yes. For the obvious reason that it
  makes formating the Docs easier AND is to be 'extracted'
  to a separate file for that purpose in the first place.

Paragraph 3:  True

Could you give a short example of what you are referring to in your last 
paragraph?  I showed this to several friends and got several 'views' as 
to what is intended.



I assume you are NOT intending to use third party programs to write code 
in but rather to use Python somehow?


I assume you are intending that the editor add the backslash newline at 
 appropriate places without causing a word or code break when needed 
and simply wrapping with indent without breaking the code the rest of 
the time and doing so in such a fashion that ALL general text editors 
will be able to display code properly as well as be usable in modifying 
code?
Not to mention that the interpreter and/or compiler will still be able 
to use the file.



Steve

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


Re: Complete frustration

2009-05-11 Thread norseman

hellcats wrote:

I have Python2.5 installed on Windows XP. Whenever I double click on a
something.pyw file, IDLE launches and opens something.pyw in the
editor. I would prefer to actually *RUN* the program, not edit it. If
I want to edit it then I'll choose the "Edit with IDLE" context menu.
So I then have to press F5 to get the program to execute. Now I have
my program's windows along with two IDLE windows cluttering my screen
and task bar. WHAT IS GOING ON? I've tried changing the file
association to python.exe, and that works, but just ONCE (even if I
choose "always use the slected program to launch this kind of file").
IDLE may be great and all, but I fricken' don't want to see it every
time I just want to run a python program!
--
http://mail.python.org/mailman/listinfo/python-list



I agree completely.  Check the Python-List archives. Look for a file 
that is dated July 8, 2008 (07/08/2008) that was sent by norseman.


It works for me.


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


Re: [Python-Dev] .pth files are evil

2009-05-11 Thread P.J. Eby

At 04:42 PM 5/9/2009 +0200, Martin v. Löwis wrote:

>> If you always use --single-version-externally-managed with easy_install,
>> it will stop editing .pth files on installation.
>
> It's --multi-version (-m) that does that.
> --single-version-externally-managed is a "setup.py install" option.
>
> Both have the effect of not editing .pth files, but they do so in
> different ways.  The "setup.py install" option causes it to install in a
> distutils-compatible layout, whereas --multi-version simply drops .egg
> files or directories in the target location and leaves it to the user
> (or the generated script wrappers) to add them to sys.path.

Ah, ok. Is there also an easy_install invocation that unpacks the zip
file into some location of sys.path (which then wouldn't require
editing sys.path)?


No; you'd have to use the -e option to easy_install to download and 
extract a source version of the package; then run that package's 
setup.py, e.g.:


   easy_install -eb /some/tmpdir SomeProject
   cd /some/tmpdir/someproject  # subdir is always lowercased/normalized
   setup.py install --single-version-externally-managed --record=...

I suspect that this is basically what pip is doing under the hood, as 
that would explain why it doesn't support .egg files.


I previously posted code to the distutils-sig that was an .egg 
unpacker with appropriate renaming, though.  It was untested, and 
assumes you already checked for collisions in the target directory, 
and that you're handling any uninstall manifest yourself.  It could 
probably be modified to take a filter function, though, something like:


def flatten_egg(egg_filename, extract_dir, filter=lambda s,d: d):
 eggbase = os.path.filename(egg_filename)+'-info'
 def file_filter(src, dst):
 if src.startswith('EGG-INFO/'):
 src = eggbase+s[8:]
 dst = os.path.join(extract_dir, *src.split('/'))
 return filter(src, dst)
 return unpack_archive(egg_filename, extract_dir, file_filter)

Then you could pass in a None-returning filter function to check and 
accumulate collisions and generate a manifest.  A second run with the 
default filter would do the unpacking.


(This function should work with either .egg files or .egg directories 
as input, btw, since unpack_archive treats a directory input as if it 
were an archive.)


Anyway, if you used "easy_install -mxd /some/tmpdir [specs]" to get 
your target eggs found/built, you could then run this flattening 
function (with appropriate filter functions) over the *.egg contents 
of /some/tmpdir to do the actual installation.


(The reason for using -mxd instead of -Zmaxd or -zmaxd is that we 
don't care whether the eggs are zipped or not, and we leave out the 
-a so that dependencies already present on sys.path aren't copied or 
re-downloaded to the target; only dependencies we don't already have 
will get dropped in /some/tmpdir.)


Of course, the devil of this is in the details; to handle conflicts 
and uninstalls properly you would need to know what namespace 
packages were in the eggs you are installing.  But if you don't care 
about blindly overwriting things (as the distutils does not), then 
it's actually pretty easy to make such an unpacker.


I mainly haven't made one myself because I *do* care about things 
being blindly overwritten.


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


Can I get a value's name

2009-05-11 Thread jalanb3
Context for this question arises from some recent code. In particular the 
"replace_line" method, which takes in a regexp to look for, and a replacement 
for when it matches.

It is supposed to work for single lines only (we add ^ and $ to the regexp), so 
arguments which have '\n' in them are not accepted.

So at start of the method we search for such bad chars, and the code ends up 
something like this:

def replace_line(pattern,replacement):
errors = '\n' in pattern and [ 'pattern' ] or []
errors += '\n' in replacement and [ 'replacement' ] or []
values = [ locals()[e] for e in errors ]
# etc, etc, and eventually:
print 'Argument %s is bad : "%s"' % (errors[0],values[0])

And the question arises from that locals() line:
Given a variable name I can use locals() to get the value
Is there a way to do it the other way round
Given the value, can I get the variable name ?

For example, suppose I had started like this (using the variables, not strings 
with their names)

def replace_line(pattern,replacement):
values = '\n' in pattern and [ pattern ] or []
values += '\n' in replacement and [ replacement ] or []

Can I later get the name "pattern" via values[0]?

If this was an array in another language:
Of course not, values[0] is a copy of the value
so the connection to the variable is lost
But, AFAIK, in Python values[0] is "just a rename" of pattern
so there might be a way to get "through to" the original variable

Thank you for reading this far.
If you were now to start writing, I'd be very grateful indeed.

-- 
Alan

P.S. This is just curiosity - replace_lines() works great as is.

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


Re: mod_python and xml.dom.minidom

2009-05-11 Thread dpapathanasiou

> His problem is therefore likely to be something completely different.

You are correct.

As per the earlier advice, I switched from mod_python to mod_wsgi but
I still see the same error:

[Mon May 11 10:30:21 2009] [notice] Apache/2.2.11 (Unix) mod_wsgi/2.4
Python/2.5.2 configured -- resuming normal operations
[Mon May 11 10:30:26 2009] [error] Traceback (most recent call last):
[Mon May 11 10:30:26 2009] [error]   File "../db/items_db.py", line
38, in 
[Mon May 11 10:30:26 2009] [error] db_object.associate(sdb_object,
(lambda primary_key, primary_data:xml_utils.parse_item_attribute
(primary_data, attribute)))
[Mon May 11 10:30:26 2009] [error]   File "../common/xml_utils.py",
line 80, in parse_item_attribute
[Mon May 11 10:30:26 2009] [error] item_doc = minidom.parseString
(item)
[Mon May 11 10:30:26 2009] [error]   File "/usr/lib/python2.5/xml/dom/
minidom.py", line 1924, in parseString
[Mon May 11 10:30:26 2009] [error] from xml.dom import
expatbuilder
[Mon May 11 10:30:26 2009] [error] SystemError: Parent module
'xml.dom' not loaded
[Mon May 11 10:30:26 2009] [error] Traceback (most recent call last):
[Mon May 11 10:30:26 2009] [error]   File "../db/items_db.py", line
38, in 
[Mon May 11 10:30:26 2009] [error] db_object.associate(sdb_object,
(lambda primary_key, primary_data:xml_utils.parse_item_attribute
(primary_data, attribute)))
[Mon May 11 10:30:26 2009] [error]   File "../common/xml_utils.py",
line 80, in parse_item_attribute
[Mon May 11 10:30:26 2009] [error] item_doc = minidom.parseString
(item)
[Mon May 11 10:30:26 2009] [error]   File "/usr/lib/python2.5/xml/dom/
minidom.py", line 1924, in parseString
[Mon May 11 10:30:26 2009] [error] from xml.dom import
expatbuilder
[Mon May 11 10:30:26 2009] [error] SystemError: Parent module
'xml.dom' not loaded

The odd thing is that when xml_utils.py is run outside of either
apache module, xml.dom does load, and the minidom parsing works.

I'm not sure why this is happening, but the next thing I'll do is try
replacing minidom with ElementTree, and see if that has any issues
running under either apache module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32 How to make sure a file is completely written?

2009-05-11 Thread justind
On May 11, 10:03 am, Tim Golden  wrote:
> justind wrote:
> > Hello,
>
> > I'm usinghttp://code.activestate.com/recipes/156178/to watch a
> > folder in windows.
>
> Wow, that takes me back. There's a bit more info (and a different
> technique) here if you're interested:
>
>  http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_chan...
>
> But to come back your question...
>
> > It's working perfectly, but sometimes when I try to
> > open the file immediately after receiving the event, it's not ready to
> > be opened--if I try to open it with PIL I get "IOError: cannot
> > identify image file" and if I try it with a text file, it's empty.
> > This doesn't happen all the time, just occasionally. I think the
> > problem is that the file isn't completely written because if I make
> > the script sleep for a second, it works every time. But that doesn't
> > seem very elegant or robust.
>
> > What's the proper way to make sure the file is ready to be read?
>
> I don't believe there's an easy answer to this question. From the
> filesystem's point of view some process creates a file. So it
> tells you that a file has been created. The filesystem has no
> knowledge of when a file is "complete". It could -- altho' it
> doesn't -- fire an event when a handle on that file is closed,
> but even that wouldn't tell you much: you'd have to be able
> to distinguish between the handle which is behind the data
> you're looking for and a handle from a virus scanner which is
> checking the new file for malware.
>
> To add difficulty, when Windows initiates a file copy (as opposed
> to creating a new file) it immediately creates the file at its
> full size and then copies data in. Which makes some sense as it
> should avoid some element of fragmentation etc. But it removes
> one of your options: noting the size of an original file and
> comparing it with the size of a copy.
>
> So I think you're out of luck and you're going to have to
> put a try-except loop in place.
>
> TJG

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


Re: Decorating methods - where do my arguments go?

2009-05-11 Thread Mikael Olofsson

George Sakkis wrote:

Yes, just return an actual function from the decorator instead of a
callable object:

def test_decorator2(func):
def wrapper(*args):
print 'Decorator2:', args
func(*args)
return wrapper


class cls(object):
@test_decorator
def meth(self,*args):
print 'Method:   ', args

@test_decorator2
def meth2(self,*args):
print 'Method2:   ', args


Thanks! This has the merit over Peter's solution that it seems to work 
for both functions and methods. However, as you can see from my answer 
to Peter, I think I will go for a class based approach anyway. Still, 
your answer helped me grasping the concepts.


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


Re: Decorating methods - where do my arguments go?

2009-05-11 Thread Mikael Olofsson

Peter Otten wrote:
You have to turn your decorator into a descriptor by providing a __get__() 
method. A primitive example:


class test_decorator(object):
def __init__(self,func):
self._func = func
def __call__(self, *args):
print 'Decorator:', args
self._func(self.inst, *args)
def __get__(self, inst, cls):
self.inst = inst
return self


Thanks! Works perfectly for methods, as far as I can see. That's 
perfectly OK, since that is what I was asking for. What I failed to 
include in my original post is that I intend to use the decorator for 
functions as well. The above fails for functions on the second row of 
__call__ with


AttributeError: 'test_decorator' object has no attribute 'inst'

It seems to me like __get__ is not called when decorating a function. I 
guess there's no reasonable value for inst in that case. It might be the 
function itself, but it doesn't make sense to call the function with 
itself as its first argument, when it isn't supposed to be called that way.


George Sakkis decorator function solution seems to work equally well for 
functions and methods. However, I prefer the cleaner encapsulation given 
by a class. Based on those observations, I think I will use the 
following approach:


>>> class test_decorator(object):
... _inst = None
... def __init__(self,func):
... self._func = func
... def __call__(self, *args):
... print 'Decorator:', args
... if self._inst is None:
... print 'We seem to be decorating a function.'
... self._func(*args)
... else:
... print 'We seem to be decorating a method.'
... self._func(self._inst,*args)
... def __get__(self, inst, cls):
... self._inst = inst
... return self
...
>>>
>>> @test_decorator
... def func(*args):
... print 'Function: ', args
...
>>>
>>> func(1,2,3)
Decorator: (1, 2, 3)
We seem to be decorating a function.
Function:  (1, 2, 3)
>>>
>>> class cls(object):
... @test_decorator3
... def meth(self,*args):
... print 'Method:   ', args
...
>>>
>>> cls().meth(1,2,3)
Decorator: (1, 2, 3)
We seem to be decorating a method.
Method:(1, 2, 3)

If there are any drawbacks with this approach that I fail to see, please 
enlighten me.


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


Re: win32 How to make sure a file is completely written?

2009-05-11 Thread Tim Golden

justind wrote:

Hello,

I'm using http://code.activestate.com/recipes/156178/ to watch a
folder in windows. 


Wow, that takes me back. There's a bit more info (and a different
technique) here if you're interested:

 http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html

But to come back your question...


It's working perfectly, but sometimes when I try to
open the file immediately after receiving the event, it's not ready to
be opened--if I try to open it with PIL I get "IOError: cannot
identify image file" and if I try it with a text file, it's empty.
This doesn't happen all the time, just occasionally. I think the
problem is that the file isn't completely written because if I make
the script sleep for a second, it works every time. But that doesn't
seem very elegant or robust.

What's the proper way to make sure the file is ready to be read?


I don't believe there's an easy answer to this question. From the
filesystem's point of view some process creates a file. So it
tells you that a file has been created. The filesystem has no 
knowledge of when a file is "complete". It could -- altho' it

doesn't -- fire an event when a handle on that file is closed,
but even that wouldn't tell you much: you'd have to be able
to distinguish between the handle which is behind the data
you're looking for and a handle from a virus scanner which is
checking the new file for malware.


To add difficulty, when Windows initiates a file copy (as opposed
to creating a new file) it immediately creates the file at its
full size and then copies data in. Which makes some sense as it
should avoid some element of fragmentation etc. But it removes
one of your options: noting the size of an original file and
comparing it with the size of a copy.

So I think you're out of luck and you're going to have to
put a try-except loop in place.

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


Re: win32 How to make sure a file is completely written?

2009-05-11 Thread ma
You have to wait until IO is ready. In Unix, we accomplish this with
fcntl and the default signal SIGIO, I am not sure how you would do
this in Windows.


On Mon, May 11, 2009 at 9:51 AM, justind  wrote:
> Hello,
>
> I'm using http://code.activestate.com/recipes/156178/ to watch a
> folder in windows. It's working perfectly, but sometimes when I try to
> open the file immediately after receiving the event, it's not ready to
> be opened--if I try to open it with PIL I get "IOError: cannot
> identify image file" and if I try it with a text file, it's empty.
> This doesn't happen all the time, just occasionally. I think the
> problem is that the file isn't completely written because if I make
> the script sleep for a second, it works every time. But that doesn't
> seem very elegant or robust.
>
> What's the proper way to make sure the file is ready to be read?
>
> I'm just passing the file names from the above recipe to a function.
> Something like
>
> def handler(files):
>    for file in files:
>        im = Image.open(file)
>
> Thanks
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >