KeyboardInterrupt catch does not shut down the socketserver

2009-05-15 Thread Igor Katson
I have problems in getting a SocketServer to shutdown. Why does this not 
actually stop the application?


from SocketServer import UnixStreamServer, BaseRequestHandler

server = UnixStreamServer('/tmp/ss.sock', BaseRequestHandler)
try:
   server.serve_forever()
except KeyboardInterrupt:
   server.shutdown()


After that the server does not respond any more, but the application hangs.

What's the proper way to shutdown the socketserver and what is my mistake?
--
http://mail.python.org/mailman/listinfo/python-list


Re: x.abc vs x['abc']

2009-05-15 Thread alex23
On May 14, 5:49 am, Gunter Henriksen 
wrote:
> Presuming it is very common to have objects created
> on the fly using some sort of external data
> definitions, is there an obvious common standard
> way to take a dict object and create an object
> whose attribute names are the keys from the dict?

I've always liked this approach, which I first saw in a post by Alex
Martelli:

>>> class Bunch(object):
... def __init__(self, **kwargs):
... self.__dict__.update(kwargs)
...
>>> b = Bunch(a=1,b=2,c=3)
>>> b.a
1
>>> b.b
2
>>> b.d = 22
>>> b.d
22


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


File System Redirection Windows x 64 box.

2009-05-15 Thread Rohit Srivastava
Hi,

In Windows 2003 x64, I want to call iscsicli.exe which is there only
in system32 directory.
Now since in x64 system windows actually redirect the 32 bit
application to sysWOW64 directory, if it is looking for system32. For
more information look for


Now my application is being redirected to this directory and from
python I am always getting an error saying, The program can not find
the file specified.

Any idea, how  can I overcome this, using python? (Condition :: I must
complie for 32 bit system only)
Thanks in Advance

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


Re: (Windows) Finding out which process has locked a file.

2009-05-15 Thread CinnamonDonkey
I have to say, this has got to be one of the least helpful groups I am
subscribed to.

Some interesting links...

   http://support.microsoft.com/kb/218965

   
http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html#the-short-version

   http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html




On 15 May, 03:47, "Gabriel Genellina"  wrote:
> En Thu, 14 May 2009 08:42:07 -0300, Lawrence D'Oliveiro escribió:
>
> > In message <787d6072-3381-40bd-
> > af20-8e1a40405...@h23g2000vbc.googlegroups.com>, CinnamonDonkey wrote:
>
> >> I have a script running which occa[s]ionally fails because it is trying
> >> to delete a file in use by another process. When this happens I want
> >> it to log which process has the lock.
>
> > Maybe there is no such process. Maybe it's just the Dimdows filesystem
> > randomly returning a failure on its own. How would you know?
>
> Oh, c'mon, that's just nonsense and doesn't help anybody.
>
> --
> Gabriel Genellina

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


Re: (Windows) Finding out which process has locked a file.

2009-05-15 Thread Tim Golden

CinnamonDonkey wrote:
> I have to say, this has got to be one of the
> least helpful groups I am subscribed to.

I'm genuinely surprised to hear you say that, especially
about this thread to which you (who appear to be the OP)
have received several replies all pointing you towards
the sysinternals tools which are pretty much the de facto
standard for doing things of this type. They're not
API calls but they're a reasonable compromise between
doing some simple parsing of output and dealing with
some underdocumented and messy low-level NT APIs.

Granted there was one rather silly response but they
really are few and far between on this list I think.
(Or perhaps I just filter them out...)


Some interesting links...

   http://support.microsoft.com/kb/218965

   
http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html#the-short-version

   http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html


Unforunately, you're perhaps adding to the not-helpfulness here
since none of those links (and I'm the author of two of them)
address the question. The original request doesn't want to
know what security is preventing you from accessing the file: it
wants to know who has a *lock* on the file, and as I pointed
out earlier, this is only accessible by some low-level API calls.

If I and others have misunderstood the original question, then
please come back and say so, but your original request seems
fairly clearly to point towards file locking and not to
security & ownership.


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


How to catch str exception?

2009-05-15 Thread anuraguni...@yahoo.com

import sys
try:
raise "xxx"
except str,e:
print "1",e # is not caught here
except:# is caught here
print "2",sys.exc_type,sys.exc_value

In the above code a string exception is raised which though deprecated
but still a 3rd party library I use uses it. So how can I catch such
exception without relying on catch all, which could be bad.

system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3
(Ubuntu 4.2.3-2ubuntu7)] on linux2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: KeyboardInterrupt catch does not shut down the socketserver

2009-05-15 Thread Lawrence D'Oliveiro
In message , Igor Katson 
wrote:

> I have problems in getting a SocketServer to shutdown.

Do you want to do a shutdown or a close?

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


Re: KeyboardInterrupt catch does not shut down the socketserver

2009-05-15 Thread Igor Katson

Lawrence D'Oliveiro wrote:
In message , Igor Katson 
wrote:


  

I have problems in getting a SocketServer to shutdown.



Do you want to do a shutdown or a close?

  
I want the server close the socket, and the program to continue after 
that (in this case, just to terminate).

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


[ANN] BPT (Boxed Package Tool) 0.4a -- now with PIP support

2009-05-15 Thread Giuseppe Ottaviano

Hi all,
I am happy to announce BPT 0.4a

http://pypi.python.org/pypi/bpt

This release is particularly interesting for python users, since it  
includes a modified version of PIP that installs the packages inside  
the box. So, at least for python packages, installation (including  
dependency resolution) is fully automated.


Version 0.4
===

- Included a forked version of `PIP
`_ 0.3.1 that installs packages in
the current box. Installing python packages is now as easy as
``easy_install``

- Implemented the ``autoremove`` command that removes all the disabled
packages (unless they match given patterns)

- Written some new documentation, added a TODO list

What is BPT
===

BPT is a Python library (``bpt``) and a command line application
(``box``) to create and manage isolated enviroments, or *boxes*.

- Boxes are *relocatable*, which means that they can be moved to a
different directory or even distributed to other machines (provided
that the architecture is compatible).

- Packages inside the box can be easily disabled, enabled and removed,
so that different versions of the same software can be installed
simultaneously, allowing to switch between them.

- Boxes can be *nested*, in the sense that it is possible to activate
a box environment while inside another box environment, so that all
the packages installed in both boxes are available, and so on.

BPT is similar in some ways to `virtualenv
`_, but it is not restricted
to Python packages, allowing to install virtually any Unix
software. It also takes some ideas from `jhbuild
`_, but without the dependency
resolution and automatic downloading machinery, and the ``bpt-rules``
format is inspired by `Gentoo `_'s ebuilds.

A fork of PIP_ is included to make installation of python packages
easier, and as an example of use of the BPT API.


Enjoy,
Giuseppe Ottaviano
--
http://mail.python.org/mailman/listinfo/python-list


Re: File System Redirection Windows x 64 box.

2009-05-15 Thread Rohit Srivastava
On May 15, 12:05 pm, Rohit Srivastava 
wrote:
> Hi,
>
> In Windows 2003 x64, I want to call iscsicli.exe which is there only
> in system32 directory.
> Now since in x64 system windows actually redirect the 32 bit
> application to sysWOW64 directory, if it is looking for system32. For
> more information look for
> 
>
> Now my application is being redirected to this directory and from
> python I am always getting an error saying, The program can not find
> the file specified.
>
> Any idea, how  can I overcome this, using python? (Condition :: I must
> complie for 32 bit system only)
> Thanks in Advance
>
> Regards
> Rohit

Apologies for the last statement in the previous post.
Please read it as (I need to comply with 32 bit Windows system also).

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


Re: How to catch str exception?

2009-05-15 Thread Kurt Symanzik
"anuraguni...@yahoo.com"  wrote on 2009-05-15 
4:13:15 PM +0800

import sys
try:
raise "xxx"
except str,e:
print "1",e # is not caught here
except:# is caught here
print "2",sys.exc_type,sys.exc_value

In the above code a string exception is raised which though deprecated
but still a 3rd party library I use uses it. So how can I catch such
exception without relying on catch all, which could be bad.

system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3
(Ubuntu 4.2.3-2ubuntu7)] on linux2


Try this, i.e. catch the exact string:

except "xxx":


Kurt

--
Kurt Symanzik
k...@kbsymanzik.org
Skype id: ksymanzik
http://kbsymanzik.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: introspection question: get return type

2009-05-15 Thread Bruno Desthuilliers

Aahz a écrit :

In article <4a0c6e42$0$12031$426a7...@news.free.fr>,
Bruno Desthuilliers   wrote:

Marco Mariani a écrit :

Bruno Desthuilliers wrote:
Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
sense given Python's dynamic typing.

Unless he's really trying to write in Nohtyp,

You meant "Notype" ?-)


Marco's spelling is correct.  Try "Nohtyp".reverse()


Aazh... I know I'm a bit dumb sometimes, but do you *really* think I had 
failed to spot this ???


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


Re: urllib2 slow for multiple requests

2009-05-15 Thread Tomas Svarovsky
On May 14, 6:33 pm, "Richard Brodie"  wrote:
> "Tomas Svarovsky"  wrote in message
>
> news:747b0d4f-f9fd-4fa6-bb6d-0a4365f32...@b1g2000vbc.googlegroups.com...
>
> > This is a good point, but then it would manifest regardless of the
> > language used AFAIK. And this is not the case, ruby and php
> > implementations are working quite fine.
>
> What I meant was: not reading the data and leaving the connection
> open is going to force the server to handle all 100 requests concurrently.
> I'm guessing that's not what your other implementations do.
> What happens to the timing if you call response.read(), response.close() ?

Now I get it, but nevertheless, even when I explicitely read from the
socket and then close it properly, the timing still doesn't change.

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


Re: How to catch str exception?

2009-05-15 Thread anuraguni...@yahoo.com
but the whole point of catching such exception is that i can print its
value
there are many such exceptions and hence it is not feasible to catch
them all or know them all unless i go thru src code.

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


test 23213213

2009-05-15 Thread Zainescu Traian

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


Re: (Windows) Finding out which process has locked a file.

2009-05-15 Thread CinnamonDonkey
Thanx for the response Tim! :-) Great site!

 > I'm genuinely surprised to hear you say that...

Early morning frustration... I appologise to all... you are totally
right. Thank you to all for the responses.

The sysinternal "Handle" tool that you made reference to earlier is
definately a working solution with minimal effort and I could indeed
use this to solve the problem.

I'd very much like to understand how such a problem could be solved
programatically though even if it means using some "underdocumented
and messy low-level NT APIs". Whilst taking the simplest approach is
the quickest to an end solution... it's also the least educational.
I'm as interested in how file locking works as I am in solving the
problem.

 > "you're perhaps adding to the not-helpfulness here..."

Again, a valid point and a lesson to be learned... I should actually
read the links I post before posting them! (I actually posted them so
that I could later read them at work).

Yes, this thread is specifically about who has the *lock* on a file.

Thanx TJG for the reality check ;-)

Shaun



On 15 May, 08:50, Tim Golden  wrote:
> CinnamonDonkey wrote:
>
>  > I have to say, this has got to be one of the
>  > least helpful groups I am subscribed to.
>
> I'm genuinely surprised to hear you say that, especially
> about this thread to which you (who appear to be the OP)
> have received several replies all pointing you towards
> the sysinternals tools which are pretty much the de facto
> standard for doing things of this type. They're not
> API calls but they're a reasonable compromise between
> doing some simple parsing of output and dealing with
> some underdocumented and messy low-level NT APIs.
>
> Granted there was one rather silly response but they
> really are few and far between on this list I think.
> (Or perhaps I just filter them out...)
>
> > Some interesting links...
>
> >    http://support.microsoft.com/kb/218965
>
> >    http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.h...
>
> >    http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file
>
> Unforunately, you're perhaps adding to the not-helpfulness here
> since none of those links (and I'm the author of two of them)
> address the question. The original request doesn't want to
> know what security is preventing you from accessing the file: it
> wants to know who has a *lock* on the file, and as I pointed
> out earlier, this is only accessible by some low-level API calls.
>
> If I and others have misunderstood the original question, then
> please come back and say so, but your original request seems
> fairly clearly to point towards file locking and not to
> security & ownership.
>
> TJG

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


Re: How to catch str exception?

2009-05-15 Thread Peter Otten
anuraguni...@yahoo.com wrote:

> but the whole point of catching such exception is that i can print its
> value
> there are many such exceptions and hence it is not feasible to catch
> them all or know them all unless i go thru src code.

Catch them all with a bare except and then reraise non-string exceptions:

try:
raise "abc"
except:
e, t, tb = sys.exc_info()
if not isinstance(e, str):
raise
print "caught", e



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


Re: How to catch str exception?

2009-05-15 Thread anuraguni...@yahoo.com

> try:
>     raise "abc"
> except:
>     e, t, tb = sys.exc_info()
>     if not isinstance(e, str):
>         raise
>     print "caught", e

This seems to be the solution, thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: KeyboardInterrupt catch does not shut down the socketserver

2009-05-15 Thread Lawrence D'Oliveiro
In message , Igor Katson 
wrote:

> Lawrence D'Oliveiro wrote:
>
>> In message , Igor
>> Katson wrote:
>>   
>>> I have problems in getting a SocketServer to shutdown.
>>
>> Do you want to do a shutdown or a close?
>>   
> I want the server close the socket ...

You want to do a close, do a close, not a shutdown 
.


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


Just wondering

2009-05-15 Thread Gediminas Kregzde
Hello,

I'm Vilnius college II degree student and last semester our teacher
introduced us to python
I've used to program with Delphi, so I very fast adopted to python

Now I'm developing cross platform program and use huge amounts of
data. Program is needed to run as fast as it coud. I've read all tips
about geting performance, but got 1 bug: map function is slower than
for loop for about 5 times, when using huge amounts of data.
It is needed to perform some operations, not to return data.

I'm adding sample code:
from time import time

def doit(i):
   pass

def main():
   a = [0] * 1000
   t = time()
   map(doit, a)
   print "map time: " + str(time() - t)

def main2():
   t = time()
   a = [0] * 1000
   for i in a:
   pass
   print "loop time: " + str(time() - t)

main()  # takes approximately 5x times longer than main2()
main2()

I'm wondering were is catch?

I'm using python 2.6 on windows xp sp2 machine

P.S. Sorry for my broken English
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: KeyboardInterrupt catch does not shut down the socketserver

2009-05-15 Thread Igor Katson

Lawrence D'Oliveiro wrote:
In message , Igor Katson 
wrote:


  

Lawrence D'Oliveiro wrote:



In message , Igor
Katson wrote:
  
  

I have problems in getting a SocketServer to shutdown.


Do you want to do a shutdown or a close?
  
  

I want the server close the socket ...



You want to do a close, do a close, not a shutdown 
.



  

Shutdown implies closing the listening socket, doesn't it?
--
http://mail.python.org/mailman/listinfo/python-list


Re: itertools question

2009-05-15 Thread pataphor

Neal Becker wrote:

Is there any canned iterator adaptor that will 


transform:
in = [1,2,3]

into:
out = [(1,2,3,4), (5,6,7,8),...]

That is, each time next() is called, a tuple of the next N items is 
returned.


Here's one that abuses a for loop:

from itertools import islice

def grouper(seq,n):
it = iter(seq)
for x in it:
yield (x,) + tuple(islice(it,n-1))

def test():
L = range(11)
n = 3
for x in grouper(L,n):
print x

if __name__ == '__main__':
test()

BTW what's up with the followup to gmane?

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


Re: Just wondering

2009-05-15 Thread bearophileHUGS
Gediminas Kregzde:
> map function is slower than
> for loop for about 5 times, when using huge amounts of data.
> It is needed to perform some operations, not to return data.

Then you are using map() for the wrong purpose. map() purpose is to
build a list of things. Use a for loop.

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


Re: Just wondering

2009-05-15 Thread Stef Mientki
and this, while it's realy doing something is even 4 times faster than 
main2 ;-)

And if you only need integers, it can be even faster.

def main3():
  from numpy import zeros
  t = time()
  a = zeros ( 1000 )
  b = a + 3.14
  print "loop time: " + str(time() - t)

cheers,
Stef

Gediminas Kregzde wrote:

Hello,

I'm Vilnius college II degree student and last semester our teacher
introduced us to python
I've used to program with Delphi, so I very fast adopted to python

Now I'm developing cross platform program and use huge amounts of
data. Program is needed to run as fast as it coud. I've read all tips
about geting performance, but got 1 bug: map function is slower than
for loop for about 5 times, when using huge amounts of data.
It is needed to perform some operations, not to return data.

I'm adding sample code:
from time import time

def doit(i):
   pass

def main():
   a = [0] * 1000
   t = time()
   map(doit, a)
   print "map time: " + str(time() - t)

def main2():
   t = time()
   a = [0] * 1000
   for i in a:
   pass
   print "loop time: " + str(time() - t)

main()  # takes approximately 5x times longer than main2()
main2()

I'm wondering were is catch?

I'm using python 2.6 on windows xp sp2 machine

P.S. Sorry for my broken English
  


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


Re: Just wondering

2009-05-15 Thread Marco Mariani

Gediminas Kregzde wrote:



def doit(i):
   pass

def main():
   a = [0] * 1000
   t = time()
   map(doit, a)
   print "map time: " + str(time() - t)


Here you are calling a function ten million times, build a list with of 
ten million None results, then throw it away.




def main2():
   t = time()
   a = [0] * 1000
   for i in a:
   pass
   print "loop time: " + str(time() - t)


Here you do nothing but iterating 'i' over the 'a' list.



main()  # takes approximately 5x times longer than main2()
main2()

I'm wondering were is catch?


Function calls are not free in python. They cost a lot more than they do 
in C, Delphi or other languages.


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


Re: capture stdout and stderror from within a Windows Service?

2009-05-15 Thread Chris Curvey
On May 14, 11:57 am, Chris Curvey  wrote:
> I'm trying to get this invocation right, and it is escaping me.  How
> can I capture the stdout and stderr if I launch a subprocess using 
> subprocess.check_call()?  The twist here is that the call is running
> from within a Windows service.
>
> I've tried:
>
> check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
> "An integer is required"]
>
> check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
> [raises an exception "An integer is required"]

Ahhh, Blake put me on the right track.  If you want any of the
streams, you have to supply values for all of them, like so:

p = subprocess.Popen(step, shell=True
  stdout=subprocess.PIPE,
  stdin=subprocess.PIPE,
  stderr=subprocess.PIPE)

(stdout, stderr) = p.communicate()

and, incidentally, it appears that you have to use UNC paths in your
Popen call -- drive letters won't work.

so "dir \\foobar\myshare\mydir" will work, but "dir j:\mydir" will
not.

Many thanks for all your assistance.


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


Re: Just wondering

2009-05-15 Thread Jaime Fernandez del Rio
map is creating a new list of 10,000,000 items, not modifying the
values inside list a. That's probably where your time difference comes
from...

Jaime

On Fri, May 15, 2009 at 1:56 PM, Gediminas Kregzde
 wrote:
> Hello,
>
> I'm Vilnius college II degree student and last semester our teacher
> introduced us to python
> I've used to program with Delphi, so I very fast adopted to python
>
> Now I'm developing cross platform program and use huge amounts of
> data. Program is needed to run as fast as it coud. I've read all tips
> about geting performance, but got 1 bug: map function is slower than
> for loop for about 5 times, when using huge amounts of data.
> It is needed to perform some operations, not to return data.
>
> I'm adding sample code:
> from time import time
>
> def doit(i):
>   pass
>
> def main():
>   a = [0] * 1000
>   t = time()
>   map(doit, a)
>   print "map time: " + str(time() - t)
>
> def main2():
>   t = time()
>   a = [0] * 1000
>   for i in a:
>       pass
>   print "loop time: " + str(time() - t)
>
> main()  # takes approximately 5x times longer than main2()
> main2()
>
> I'm wondering were is catch?
>
> I'm using python 2.6 on windows xp sp2 machine
>
> P.S. Sorry for my broken English
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
planes de dominación mundial.
-- 
http://mail.python.org/mailman/listinfo/python-list


Configure options for minimal Python 2.6

2009-05-15 Thread Andrew Malcolmson
I want to compile a minimal Python 2.6 for Debian Etch without support
for optional features such as tk and sphinx.  The configure script's
help says that features can be disabled with an '--without-PACKAGE', so
I guess disabling tk is '--without-tk', but where is there a list of the
feature/package names of the other optional components?
---
Andrew Malcolmson

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


Re: Just wondering

2009-05-15 Thread Peter Otten
Gediminas Kregzde wrote:

> Now I'm developing cross platform program and use huge amounts of
> data. Program is needed to run as fast as it coud. I've read all tips
> about geting performance, but got 1 bug: map function is slower than
> for loop for about 5 times, when using huge amounts of data.
> It is needed to perform some operations, not to return data.
> 
> I'm adding sample code:
> from time import time
> 
> def doit(i):
>pass
> 
> def main():
>a = [0] * 1000
>t = time()
>map(doit, a)
>print "map time: " + str(time() - t)
> 
> def main2():
>t = time()
>a = [0] * 1000
>for i in a:
>pass
>print "loop time: " + str(time() - t)
> 
> main()  # takes approximately 5x times longer than main2()
> main2()
> 
> I'm wondering were is catch?
> 
> I'm using python 2.6 on windows xp sp2 machine

Two factors: 

(1) building another throwaway list and
(2) function call overhead for calling doit()

You can avoid (1) by using filter() instead of map() and verify (2) by 
changing the loop to

for i in a:
doit(i)

Peter

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


Re: creating python code with dynamic file name

2009-05-15 Thread Dave Angel

bijoy franco wrote:

hi,


How can i create python code, for which filename can be defined on the
fly..?

for example, in a blog, when each article selected, respective python code
with headline of the article as filename should be called.

thanks

bijoy

  

You could have been much clearer in your requirements.  I have to guess:

Perhaps you're writing a CGI script to run on Linux, with Python 2.3.  
You need to be able to import a different python file, depending on some 
data calculation.  You have three different such python files, whose 
names are known ahead of time.

if   data == "English":
 import   english
elif   data == "Spanish":
 import  spanish
else:
 import nativeamerican

Or is it:
You're writing a script on Windows Server 2003, that's going to generate 
python 3.0 source code, and html, and the code and the html it generates 
is dependent on some data retrieved from Yahoo stock quotes.  The python 
all has to be version 3.1



Supply your environment, your requirements, some example data, and some 
test code that doesn't quite work.  Then someone will probably be able 
to point out the problem.



I could suggest you play with __import__()   But of course that's not 
available everywhere.



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


Re: Just wondering

2009-05-15 Thread Jaime Fernandez del Rio
> (1) building another throwaway list and
> (2) function call overhead for calling doit()
>
> You can avoid (1) by using filter() instead of map()

Are you sure of this? My python returns, when asked for help(filter) :

Help on built-in function filter in module __builtin__:

filter(...)
filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a tuple
or string, return the same type, else return a list.

I'm afraid there is no builtin function to do an inplace modification
of a sequence...


-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
planes de dominación mundial.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just wondering

2009-05-15 Thread Bruno Desthuilliers

Gediminas Kregzde a écrit :

Hello,

I'm Vilnius college II degree student and last semester our teacher
introduced us to python
I've used to program with Delphi, so I very fast adopted to python

Now I'm developing cross platform program and use huge amounts of
data. Program is needed to run as fast as it coud. I've read all tips
about geting performance, but got 1 bug: map function is slower than
for loop 


Why should it be a bug ?


for about 5 times,


read below for comments on your benchmark.


when using huge amounts of data.
It is needed to perform some operations, not to return data.


Then don't use map. You're uselessly building a new list (which takes 
time *and* eats RAM - so on 'huge' dataset, this might even make your 
system start swapping).





I'm adding sample code:
from time import time


The correct way to time code is to use the timeit module.


def doit(i):
   pass

def main():
   a = [0] * 1000
   t = time()
   map(doit, a)
   print "map time: " + str(time() - t)

def main2():
   t = time()
   a = [0] * 1000
   for i in a:
   pass


Your benchmark is screwed. In the first case, you call doit() X times 
(with X = len(a)), while in the second case you don't call it at all.


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


Re: File System Redirection Windows x 64 box.

2009-05-15 Thread Dave Angel

Rohit Srivastava wrote:

Hi,

In Windows 2003 x64, I want to call iscsicli.exe which is there only
in system32 directory.
Now since in x64 system windows actually redirect the 32 bit
application to sysWOW64 directory, if it is looking for system32. For
more information look for


Now my application is being redirected to this directory and from
python I am always getting an error saying, The program can not find
the file specified.

Any idea, how  can I overcome this, using python? (Condition :: I must
complie for 32 bit system only)
Thanks in Advance

Regards
Rohit

  
My experience with Microsoft's 64 bit systems is limited to the Itanium 
system (while it was still called Merced), prerelease.



Shadowing directories has to be a big mistake.  And especially if the 
directory is called "system32."   Seems logical that there could be 
another one called "system64".  And that 64 bit applications would have 
to have their sources tweaked while being ported from a different OS.


I remember FILEPATH and DATAPATH, in DOS days.  It tried to 
automatically alias directory locations on a file open, similar to what 
PATH does for program launches.  But many applications, when trying to 
update their files, put the update back in the user-supplied directory, 
so you ended up with two copies, one out of date.   Big mess.



I presume the reason that  iscsicli.exe is located there is that it's a 
64 bit executable?


Why not follow some of the advice in the page you quoted?   You probably 
can't use SysNative, since it was introduced with Vista.  But what's 
wrong with Wow64DisableWow64FsRedirection() ??

see  http://msdn.microsoft.com/en-us/library/aa365743(VS.85).aspx


The page says it's available on Server 2003, as of SP1.  If you can't be 
sure SP1 is installed, I'm not sure what to suggest.  A batch or CMD 
file?   Or are those restricted as well?


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


Re: Just wondering

2009-05-15 Thread Peter Otten
Jaime Fernandez del Rio wrote:

>> (1) building another throwaway list and
>> (2) function call overhead for calling doit()
>>
>> You can avoid (1) by using filter() instead of map()
> 
> Are you sure of this? 

> I'm afraid there is no builtin function to do an inplace modification
> of a sequence...
 
You are right. 

But the OP invokes map() for the side effect of calling doit(item) for every 
item in the (huge) list and then gets another list of the same length 
containing only None values. by using filter() instead of map() with doit 
always returning None he gets an empty result list which means less wasted 
effort:

>>> items = range(10)
>>> map(doit, items)
[None, None, None, None, None, None, None, None, None, None]
>>> filter(doit, items)
[]

Peter

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


Re: capture stdout and stderror from within a Windows Service?

2009-05-15 Thread Tim Golden

Chris Curvey wrote:

Ahhh, Blake put me on the right track.  If you want any of the
streams, you have to supply values for all of them, like so:

p = subprocess.Popen(step, shell=True
  stdout=subprocess.PIPE,
  stdin=subprocess.PIPE,
  stderr=subprocess.PIPE)

(stdout, stderr) = p.communicate()

and, incidentally, it appears that you have to use UNC paths in your
Popen call -- drive letters won't work.



This is because you're running in a service. Drive letters
aren't system wide: they're per-user. The service won't
know about any drive letters you or anyone else happens
to have mapped.

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


Re: Your Favorite Python Book

2009-05-15 Thread Evan Kroske

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?


-sam


Programming Python is good, but its examples follow a function-based
(not functional) style that I don't like. Most of the applications are a
mix of function libraries and scripts, and there's almost no
object-oriented best-practices content.

I don't have a recommendation; that's the only Python book I own.

--
Evan Kroske
Welcome2Obscurity.Blogspot.com 
Glory is fleeting, but obscurity is forever. — some French guy

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


Re: Representing a Tree in Python

2009-05-15 Thread Jaime Fernandez del Rio
If you run Dijkstra without a third argument, i.e. without an end
node, the it will compute the shortest paths from your start node to
all nodes in the tree. So by doing something like:

start_node = 1
end_nodes = [2,3,5]

D, P = Dijkstra(G, start_node)

You will then have in D a dictionary with distances to all nodes, and
in P a dictionary of preceding nodes along the shortest path for each
node. You could tweak the Dijkstra function so that it stops when the
minimum distances to all elements of end_nodes have been calculated,
without having to solve for the whole graph...

Apart from that, how you want to store the shortest path information
is up to you, but if you stick to the "graph as a dictionary of
dictionaries" you can construct the subgraph that contains only the
nodes in the shortest paths between the start and the end nodes with
code like this one:

shortest_tree = {}
current_layer = end_nodes
while current_layer != [start_node] :
new_layer = set()
for node in current_layer :
new_node = P[node]
if new_node in shortest_tree :
if node not in shortest_tree[new_node] :
shortest_tree[new_node][node] = G[new_node][node]
else :
shodtest_tree[new_node] = {}
shortest_tree[new_node][node] = G[new_node][node]
new_layer.add(new_node)
current_layer = [j for j in new_layer]

I haven't tested the code, and there may be more efficient ways of
achieving the same, though...

Jaime

On Wed, May 13, 2009 at 10:49 AM, godshorse  wrote:
> On May 13, 3:19 pm, Jaime Fernandez del Rio 
> wrote:
>> Dijkstra's algorithm computes shortest paths between a node and _ALL_
>> other nodes in the graph. It is usually stopped once computing the
>> shortest path to the target node is done, but that's simply for
>> efficiency, not a limitation of the algorithm. So you should be able
>> to tweak the code you are using so that it provides you with all you
>> are looking for. I'd be surprised if graphine (which, by the way,
>> looks great, CTO) or any other graph package didn't implement it, so
>> switching to that may be the most efficient thing to do.
>>
>> On the other hand, if you want to post your code and links to the
>> Dijkstra code you are using it may be possible to help you with the
>> tweaking...
>>
>> Jaime
>>
>>
>>
>> On Wed, May 13, 2009 at 8:31 AM, godshorse  wrote:
>> > On May 13, 11:54 am, CTO  wrote:
>> >> On May 13, 12:10 am, godshorse  wrote:
>>
>> >> > Hello,
>>
>> >> > I want to find out the shortest path tree from a root to several nodes
>> >> > in a graph data structure. I found a Dijkstra code from internet that
>> >> > finds shortest path between only two nodes. How can i extend it to a
>> >> > tree?. And what is the best way to represent a tree in Python?.
>>
>> >> > Thank you,
>>
>> >> Well, I'm biased, but I like http://graphine.org>.
>> >> As an example, to build a five node tree:
>>
>> >> >>> from graph.base import Graph
>> >> >>> g = Graph()
>> >> >>> for i in range(5):
>>
>> >> ...     g.add_node(i)
>> >> ...
>>
>> >> >>> g.add_edge(0, 1)
>> >> >>> g.add_edge(0, 2)
>> >> >>> g.add_edge(1, 3)
>> >> >>> g.add_edge(1, 4)
>>
>> >> And to find the shortest path between, say, node 0 and node 4:
>>
>> >> >>> start = g[0]
>> >> >>> end = g[4]
>> >> >>> distance, edges = g.get_shortest_paths(start)[end]
>> >> >>> distance
>> >> 2
>> >> >>> edges
>>
>> >> [Edge(name=(0,1)), Edge(name=(1,4))]
>>
>> >> Let me know what you think if you decide to use it- I'm looking for
>> >> feedback.
>>
>> >> Geremy Condra
>>
>> > Thanks very much for your reply Geremy. That site was interesting.
>>
>> > Actually the Graph building part is already completed now. I used a
>> > dictionary for that and it works fine. for Dijkstra shortest path
>> > problem your suggestion can be used.
>>
>> > But let me clear the my problem again. I have a graph. and I want to
>> > find 'shortest path tree' from a root node to several nodes. as a
>> > example if we have a graph of 5 nodes from 1 to 5, I need to build the
>> > shortest path tree from node 1 to nodes 2,3,5. So my question is
>> > instead of keeping separate lists for each destination node's shortest
>> > path. How can I represent and store them in a tree structure using
>> > python. Then I can easily find out what are the common nodes in the
>> > path to each destination.
>>
>> > Thanks once again.
>> > --
>> >http://mail.python.org/mailman/listinfo/python-list
>>
>> --
>> (\__/)
>> ( O.o)
>> ( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
>> planes de dominación mundial.
>
> Hello Jaime,
>
> Thanks for the reply.
>
> This is the link to the code that I am using. 
> http://code.activestate.com/recipes/119466/
> What I do in my code is just looping through the destination nodes and
> find the shortest path to each node.
>
> Thanks
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale e

Re: How to catch str exception?

2009-05-15 Thread Dave Angel

anuraguni...@yahoo.com wrote:

import sys
try:
raise "xxx"
except str,e:
print "1",e # is not caught here
except:# is caught here
print "2",sys.exc_type,sys.exc_value

In the above code a string exception is raised which though deprecated
but still a 3rd party library I use uses it. So how can I catch such
exception without relying on catch all, which could be bad.

system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3
(Ubuntu 4.2.3-2ubuntu7)] on linux2

  

Just fix the except type to be the exception caused by the illegal "raise"

except TypeError,e:
   print "1",e # is caught here


1 exceptions must be classes or instances, not str

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


Re: New to python, can i ask for a little help? (Andrew Chung)

2009-05-15 Thread Gabor Urban
I gues, it was rather simple...

Begin with simple tasks, figure out how to do them. If you are
proceding well, then increase difficulty/complexity.

Gabor
-- 
Linux: Choice of a GNU Generation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DOM implementation

2009-05-15 Thread Emanuele D'Arrigo
Hey Paul,

would you mind continuing this thread on Python + DOM? I'm trying to
implement a DOM Events-like set of classes and I could use another
brain that has some familiarity with the DOM to bounce ideas with. If
you are too busy never mind. Also, I thought of keeping the discussion
here rather than via email, for the benefit of current and future
readers.

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


Re: mod_python and xml.dom.minidom

2009-05-15 Thread dpapathanasiou

> Were you getting this issue with xml.dom showing on first request all
> the time, or only occasionally occurring? If the latter, were you
> running things in a multithreaded configuration and was the server
> being loaded with lots of concurrent requests?

It was the former.

> For your particular Python installation, does the '_xmlplus' module
> exist? Ie., can you import it as '_xmlplus' or 'xml.doc._xmlplus'?

No, it appears I don't have _xmlplus; neither 'import _xmlplus' nor
'import xml.doc._xmlplus' works.

My python installation is the default which came with debian 5.0
(i.e., I didn't build it from source with unorthodox configuration
options, or use apt).

As a final note, I wound up switching to cElementTree for parsing the
xml (not only for performance but also because the code is much more
concise), and I found that I don't need a full package path with that
module.

I.e, the import statement is:

from cElementTree import ElementTree, Element, SubElement, iterparse,
tostring, fromstring

and within each function I can simply refer to Element, SubElement,
etc. w/o the full path prefix.
-- 
http://mail.python.org/mailman/listinfo/python-list


python

2009-05-15 Thread anica_1069
hello, I´m a student of linguistic an I need do this exercises. Can
anybody help me,please?
Thanks


◑ Read in some text from a corpus, tokenize it, and print the list of
all wh-word types that occur. (wh-words in English are used in
questions, relative clauses and exclamations: who, which, what, and so
on.) Print them in order. Are any words duplicated in this list,
because of the presence of case distinctions or punctuation?

◑ Create a file consisting of words and (made up) frequencies, where
each line consists of a word, the space character, and a positive
integer, e.g. fuzzy 53. Read the file into a Python list using open
(filename).readlines(). Next, break each line into its two fields
using split(), and convert the number into an integer using int(). The
result should be a list of the form: [['fuzzy', 53], ...].
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Your Favorite Python Book

2009-05-15 Thread Sam Tregar
Thanks for the suggestions everyone!  I've got a copy of Core Python 2nd
Edition on the way.

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


Re: How to catch str exception?

2009-05-15 Thread anuraguni...@yahoo.com

> except TypeError,e:
>     print "1",e # is caught here
>
> 1 exceptions must be classes or instances, not str

doesn't happen so in 2.5.2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python

2009-05-15 Thread Andre Engels
We may be willing to help you with your homework, but we will not be
doing it for you. Please tell us what you have got (whether it be a
non-working a program, a partial program or just some ideas about what
you might need to do) and what you think is stopping you from getting
further.

2009/5/15  :
> hello, I´m a student of linguistic an I need do this exercises. Can
> anybody help me,please?
> Thanks
>
>
> ◑ Read in some text from a corpus, tokenize it, and print the list of
> all wh-word types that occur. (wh-words in English are used in
> questions, relative clauses and exclamations: who, which, what, and so
> on.) Print them in order. Are any words duplicated in this list,
> because of the presence of case distinctions or punctuation?
>
> ◑ Create a file consisting of words and (made up) frequencies, where
> each line consists of a word, the space character, and a positive
> integer, e.g. fuzzy 53. Read the file into a Python list using open
> (filename).readlines(). Next, break each line into its two fields
> using split(), and convert the number into an integer using int(). The
> result should be a list of the form: [['fuzzy', 53], ...].
> --
> http://mail.python.org/mailman/listinfo/python-list
>





-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch str exception?

2009-05-15 Thread MRAB

anuraguni...@yahoo.com wrote:

but the whole point of catching such exception is that i can print its
value
there are many such exceptions and hence it is not feasible to catch
them all or know them all unless i go thru src code.


If string exceptions are so difficult to use, don't use them! :-)

It would be better to write your own exception class:

class MyException(Exception):
pass

try:
raise MyException("Something bad happened!")
except MyException, e:
print "ERROR: %s" % e
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch str exception?

2009-05-15 Thread anuraguni...@yahoo.com

> It would be better to write your own exception class:
>
> class MyException(Exception):
>      pass


and how would i automatically inject this into 3rd part library
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't run PyQt apps with MacPython

2009-05-15 Thread Morad
On May 13, 7:29 pm, David Boddie  wrote:
> On Wednesday 13 May 2009 17:53, Morad wrote:
>
> > I recently got a new MacBook Pro with Leopard, and would like to
> > develop using Python and PyQt. I installed the latest Qt SDK, updated
> > MacPython to V 2.5.4 and then proceeded to install SIP and PyQt as
> > described in Mark Summerfield's book on PyQt Programming. Everything
> > went fine and none of the scripts complained. However when I want to
> > run a demo app, I get the error message "Fatal Python error:
> > Interpreter not initialized (version mismatch?) / Abort Trap". Anybody
> > can help?
>
> This page suggests a possible conflict between installed Python
> interpreters:
>
> http://aralbalkan.com/1675/comment-page-1
>
> A post to the PyQt mailing list talks about the correct way to build from
> source, but it may not be relevant in this case:
>
> http://www.riverbankcomputing.com/pipermail/pyqt/2006-July/013766.html
>
> It may just be worth checking that SIP and PyQt were built and installed
> for the interpreter you expected. Failing that, you might want to ask this
> again on the PyQt mailing list:
>
> http://www.riverbankcomputing.com/pipermail/pyqt/
>
> David

Thanks David. What I managed to do as an interim solution is simply to
remove MacPython and reinstall SIP and PyQt using the default version
of Python that comes with Apple, and then everything works. Next I
will retry how to use a more uptodate version, maybe I compiled SIP
etc. with the wrong version. If I have more questions I will use the
PyQt mailing list, thanks for the tip!

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


Re: python

2009-05-15 Thread Mike Driscoll
On May 15, 8:58 am, anica_1...@hotmail.com wrote:
> hello, I´m a student of linguistic an I need do this exercises. Can
> anybody help me,please?
> Thanks
>
> ◑ Read in some text from a corpus, tokenize it, and print the list of
> all wh-word types that occur. (wh-words in English are used in
> questions, relative clauses and exclamations: who, which, what, and so
> on.) Print them in order. Are any words duplicated in this list,
> because of the presence of case distinctions or punctuation?


This requires learning file I/O and some string manipulation
techniques. I would probably read each line, split on spaces and then
loop over each word and check for "wh" and add them to a new list.
After reading the file, you'd then use a sort to get them in the right
order.

>
> ◑ Create a file consisting of words and (made up) frequencies, where
> each line consists of a word, the space character, and a positive
> integer, e.g. fuzzy 53. Read the file into a Python list using open
> (filename).readlines(). Next, break each line into its two fields
> using split(), and convert the number into an integer using int(). The
> result should be a list of the form: [['fuzzy', 53], ...].

I recommend reading the Python Tutorial: http://python.org/doc/

If you're using Python 2.x, then check out http://www.diveintopython.org/

If you're using 3.0, your primary options are the online docs and
"Programming in Python 3" by Summerfield.

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


Re: How to catch str exception?

2009-05-15 Thread MRAB

anuraguni...@yahoo.com wrote:

It would be better to write your own exception class:

class MyException(Exception):
 pass



and how would i automatically inject this into 3rd part library


Ah, I wasn't reading carefully enough! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can't run PyQt apps with MacPython

2009-05-15 Thread Morad
On May 15, 10:34 am, Morad  wrote:
> On May 13, 7:29 pm, David Boddie  wrote:
>
>
>
> > On Wednesday 13 May 2009 17:53, Morad wrote:
>
> > > I recently got a new MacBook Pro with Leopard, and would like to
> > > develop using Python and PyQt. I installed the latest Qt SDK, updated
> > > MacPython to V 2.5.4 and then proceeded to install SIP and PyQt as
> > > described in Mark Summerfield's book on PyQt Programming. Everything
> > > went fine and none of the scripts complained. However when I want to
> > > run a demo app, I get the error message "Fatal Python error:
> > > Interpreter not initialized (version mismatch?) / Abort Trap". Anybody
> > > can help?
>
> > This page suggests a possible conflict between installed Python
> > interpreters:
>
> >http://aralbalkan.com/1675/comment-page-1
>
> > A post to the PyQt mailing list talks about the correct way to build from
> > source, but it may not be relevant in this case:
>
> >http://www.riverbankcomputing.com/pipermail/pyqt/2006-July/013766.html
>
> > It may just be worth checking that SIP and PyQt were built and installed
> > for the interpreter you expected. Failing that, you might want to ask this
> > again on the PyQt mailing list:
>
> >http://www.riverbankcomputing.com/pipermail/pyqt/
>
> > David
>
> Thanks David. What I managed to do as an interim solution is simply to
> remove MacPython and reinstall SIP and PyQt using the default version
> of Python that comes with Apple, and then everything works. Next I
> will retry how to use a more uptodate version, maybe I compiled SIP
> etc. with the wrong version. If I have more questions I will use the
> PyQt mailing list, thanks for the tip!
>
> Morad

Quick update: I now also managed to get things working with a newer
version of MacPython (2.5.4) and everything looks fine. The trick
seems to be that if a terminal window is open prior to the MacPython
install, it will NOT use the new version of python. So one has to
close it and open a new terminal window, and only then should one
compile SIP and PyQt.

Anyway, thanks again for the help.
Morad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DOM implementation

2009-05-15 Thread Paul Boddie
On 15 Mai, 15:23, "Emanuele D'Arrigo"  wrote:
> Hey Paul,
>
> would you mind continuing this thread on Python + DOM? I'm trying to
> implement a DOM Events-like set of classes and I could use another
> brain that has some familiarity with the DOM to bounce ideas with. If
> you are too busy never mind. Also, I thought of keeping the discussion
> here rather than via email, for the benefit of current and future
> readers.

Sure! Just keep your observations coming! I've made a very lazy
attempt at DOM Events support in libxml2dom, since it looked as if it
might be necessary when providing elementary SVG Tiny support (which
also isn't finished), although I find these things quite hard to
figure out with the usual vagueness of the specifications on certain
crucial implementation-related details (and that there's a mountain of
specifications that one has to navigate).

One of my tests tries to exercise the code, but I might be doing it
all completely wrong:

https://hg.boddie.org.uk/libxml2dom/file/91c0764ac7c6/tests/svg_events.py

It occurs to me that various PyQt- and PyKDE-related bindings might
also provide some exposure to DOM Events, although I had heard that
WebKit, which should have support for lots of DOM features, exposes
some pretty useless interfaces to languages like Python, currently.
The situation with Mozilla and PyXPCOM may well be similar.

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


Import w/ '.' syntax

2009-05-15 Thread mrstevegross
Remind me: is it possible to craft an import statement like this:
  import foo.bar

If so, what's going on here exactly? Is Python looking for a module
called 'bar', in a directory called 'foo', in a search path somewhere?
Or am I totally misunderstanding the import semantics.

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


Re: Your Favorite Python Book

2009-05-15 Thread Jeff McNeil
On May 11, 5:45 pm, Chris Rebert  wrote:
> 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

I second this. I've got a small stack of reference books on Python and
this is the most ripped up, coffee-stained, ragged piece of junk I
own. It's even more beat up than my K&R book which I've probably had
four times as long.  Everyone knows that's how you rate your techie
books... the more beat up they are, the higher the quality.

The book is laid out wonderfully.  You've got an tutorial that's
geared towards programmers, language reference, some advanced topics,
and then module reference.

Also, have a look at www.pylonsbook.com once you get the language
down. I've come to like this one as well because you'll also learn a
lot about Python development in general from it. A lot of the
knowledge transfers out of the web development arena into other areas
of programming.



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


using urlretrive/urlopen

2009-05-15 Thread Rustom Mody
I am trying to talk to a server that runs on localhost
The server runs on http://localhost:7000/ and that opens alright in  a
web browser.

However if I use urlopen or urlretrieve what I get is this 'file' --
obviously not the one that the browser gets:


Query 'http://localhost:7000/' not implemented

Any tips/clues?

This is python2.6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import w/ '.' syntax

2009-05-15 Thread Jeff McNeil
On May 15, 10:50 am, mrstevegross  wrote:
> Remind me: is it possible to craft an import statement like this:
>   import foo.bar
>
> If so, what's going on here exactly? Is Python looking for a module
> called 'bar', in a directory called 'foo', in a search path somewhere?
> Or am I totally misunderstanding the import semantics.
>
> Thanks,
> --Steve

In that specific case, you're looking for a module 'bar' in the 'foo'
package, which should be located somewhere on sys.path.

http://docs.python.org/tutorial/modules.html

That covers it pretty well.

Thanks,

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


Re: Import w/ '.' syntax

2009-05-15 Thread mrstevegross
> In that specific case, you're looking for a module 'bar' in the 'foo'
> package, which should be located somewhere on sys.path.
>
> http://docs.python.org/tutorial/modules.html
>
> That covers it pretty well.

Aha! 'packages'! That makes sense.

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


Case insensitive version of string.Template?

2009-05-15 Thread python
Using Python 2.6 or higher: Is there a way to configure
string.Template() to ignore the case of matched identifiers?
In other words, given the following Template string and
dictionary where all keys are lowercase, is there a way to have
my identifiers expanded based on their lowercase values?
import string
values = dict( name='John Doe', phone='999-555-1212' )
output = string.Template( 'My name is $NAME and my phone is
$Phone.' ).safe_substitute( values )
Thank you,
Malcolm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Your Favorite Python Book

2009-05-15 Thread Mike Driscoll
On May 11, 4:45 pm, Chris Rebert  wrote:
> 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

I use Hetland's "Beginning Python" and Chun's "Core Python
Programming" the most, although I haven't used them in a while. I also
use Martelli's "Python Cookbook" from time-to-time. Hopefully he will
put out a 3.0 version too.

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


Re: How to catch str exception?

2009-05-15 Thread Dave Angel



anuraguni...@yahoo.com wrote:

except TypeError,e:
print "1",e # is caught here

1 exceptions must be classes or instances, not str



doesn't happen so in 2.5.2

  

I tested it in 2.6.2

Perhaps you could try something like:

try:
   raise "xxx"
except Exception, e:
   print "1",e # is caught here
   ...and then test e.message and reraise if necessary


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


Re: (Windows) Finding out which process has locked a file.

2009-05-15 Thread Tim Golden

CinnamonDonkey wrote:

Thanx for the response Tim! :-) Great site!

 > I'm genuinely surprised to hear you say that...

Early morning frustration... I appologise to all... you are totally
right. Thank you to all for the responses.


Well it's big of you to apologise. In return, I've managed to knock
up an example of determining locked file owners. But it is a tad
messy. I'll try to work it up into an annotated example, but for
now it's on pastebin:

 http://python.pastebin.com/m7b4e420a

It manages to mix pywin32, ctypes and wmi over COM via my WMI module.
I may have missed some useful shortcuts but I think it does enough
to illustrate what's going on. It's mostly a translation of a
posting which I'll try to link to when I can find it again, to
give credit where it's due.



Thanx TJG for the reality check ;-)


Well I hope the above is helpful.

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


Re: Your Favorite Python Book

2009-05-15 Thread Lou Pecora
In article 
,
 Mike Driscoll  wrote:

> On May 11, 4:45 pm, Chris Rebert  wrote:

> >
> > 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

"Python in a Nutshell" -- Absolutely!  Covers a lot in an easily 
accessible way.  The first book I reach for.  I hope Martelli updates it 
to 3.0.

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


Parsing Strings in Enclosed in Curly Braces

2009-05-15 Thread xamalek
How do you parse a string enclosed in Curly Braces?

For instance:

x = "{ABC EFG IJK LMN OPQ}"

I want to do x.split('{} ') and it does not work. Why does it not work
and what are EXCEPTIONS to using the split method?

That I want to split based on '{', '}' and WHITESPACE.

Please advise.

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


Re: Parsing Strings in Enclosed in Curly Braces

2009-05-15 Thread Chris Rebert
On Fri, May 15, 2009 at 9:12 AM,   wrote:
> How do you parse a string enclosed in Curly Braces?
>
> For instance:
>
> x = "{ABC EFG IJK LMN OPQ}"
>
> I want to do x.split('{} ') and it does not work. Why does it not work
> and what are EXCEPTIONS to using the split method?

.split() takes a *substring* to split on, *not* a set of individual
characters to split on. Read the Fine Docs.

> That I want to split based on '{', '}' and WHITESPACE.

Well, you could use a regex, or you could just .find() where the
braces are, slice them off the ends of the string, and then split the
result on space.

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


Printing a hex character and prefixing it correctly

2009-05-15 Thread xamalek
If I have an integer k, for instance;

k = 32 // BASE 10

How do I get print to print it out in HEX and PREFIXED with 0x? What
is the PROPER WAY?

This does not work:

  print "This is hex 32: ", int(k, 16)

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


Re: Parsing Strings in Enclosed in Curly Braces

2009-05-15 Thread Mike Driscoll
On May 15, 11:12 am, xama...@yahoo.com wrote:
> How do you parse a string enclosed in Curly Braces?
>
> For instance:
>
> x = "{ABC EFG IJK LMN OPQ}"
>
> I want to do x.split('{} ') and it does not work. Why does it not work
> and what are EXCEPTIONS to using the split method?
>
> That I want to split based on '{', '}' and WHITESPACE.
>
> Please advise.
>
> Regards,
> Xav

The reason it doesn't work is that you don't have a string with "{}".
Instead, you have one of each. If your string was like this, then it
would split:

x = "{} ABC EFG"

In the mean time, you can just use some string slicing like this:

y = x[1:-1]

That will remove the braces and allow you to manipulate the text
therein.

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


Re: DOM implementation

2009-05-15 Thread Emanuele D'Arrigo
Hi Paul, thank you for your swift reply!

On May 15, 3:42 pm, Paul Boddie  wrote:
> Sure! Just keep your observations coming! I've made a very lazy
> attempt at DOM Events support in libxml2dom,

I just had a look at libxml2dom, in particular its events.py file.
Given that we are working from a standard your implementation is
exceedingly similar to mine and had I know before I started writing my
own classes I would have started from it instead! =)
Browsing through the code, the EventTarget class docstring reads:

The listeners for a node are accessed through the global object.
This common
collection is consequently accessed by all nodes in a document,
meaning that
distinct objects representing the same node can still obtain the
set of
listeners registered for that node. In contrast, any attempt to
directly
store listeners on particular objects would result in the specific
object
which registered the listeners holding the record of such objects,
whereas
other objects obtained independently for the same node would hold
no such
record.

Naively, I implemented my EventTarget class storing its own listeners
rather than global ones. Nevertheless, I'm not quite understanding
this issue. Why shouldn't the listeners be stored directly on the
EventTarget? I have a glimpse of understanding that if the
DOMImplementation keeps EventTarget and Nodes (or Elements? which
entity is supposed to support Events?) separate this might be
necessary. But beside the fact that it's just a fuzzy and potentially
incorrect intuition, I seem to think that the appropriate way to
proceed would be for the DOMImplementation to provide a Node class
that also inherits from EventTarget. In so doing the listeners would
be immediately accessible as soon as one has a handle to a Node.

Furthermore, your code finds the bubbling route with the line:

bubble_route = target.xpath("ancestor::*")

That xpath method is a libxml method right?

> (...) although I find these things quite hard to
> figure out with the usual vagueness of the specifications on certain
> crucial implementation-related details (and that there's a mountain of
> specifications that one has to navigate).

Indeed there is some vagueness in the W3C recommendations and the
various documents offer very little redundancy with each other but
require you to be knowledgeable about them all! I'm managing to piece
together the pieces of the puzzle only after a couple of day having an
in-depth read-through of DOM, DOM Events and a little bit of XML
events to see how it all works in practice. XML events is also what's
prompting me to think that Node/Elements classes of the implementation
should also inherit from EventTarget as they can all be event
targets.

> One of my tests tries to exercise the code, but I might be doing it
> all completely wrong:
>
> https://hg.boddie.org.uk/libxml2dom/file/91c0764ac7c6/tests/svg_event...

Before I can comment I'd like to better understand what you are aiming
for with libxml2dom. It seems to be providing some kind of conversion
services from the xml structure generated by libxml to a dom-like
structure (implemented by pxdom?).
Is that correct?

> It occurs to me that various PyQt- and PyKDE-related bindings might
> also provide some exposure to DOM Events, although I had heard that
> WebKit, which should have support for lots of DOM features, exposes
> some pretty useless interfaces to languages like Python, currently.
> The situation with Mozilla and PyXPCOM may well be similar.

PyKDE is off-limits because it's unix only while I'm trying to be
cross-platform. PyQT is interesting. Very. Further investigation is
required. =)

Manu

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


Re: Printing a hex character and prefixing it correctly

2009-05-15 Thread Chris Rebert
On Fri, May 15, 2009 at 9:15 AM,   wrote:
> If I have an integer k, for instance;
>
> k = 32 // BASE 10
>
> How do I get print to print it out in HEX and PREFIXED with 0x? What
> is the PROPER WAY?
>
> This does not work:
>
>  print "This is hex 32: ", int(k, 16)

print "This is hex 32:", hex(k)

print int("0xA", 16) #==> 10

I would recommend you read the tutorial and/or library reference if
you haven't already.

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


Autosizing column widths in Excel using win32com.client ?

2009-05-15 Thread nonsense
Is there a way to autosize the widths of the excel columns as when you
double click them manually?
-- 
http://mail.python.org/mailman/listinfo/python-list


Finding location of an executable in a windows machine?

2009-05-15 Thread nonsense
My python script calls another windows program file. I have the path
to that program hardcoded in it. Is there a way for python to
automatically find the path to this program?

testapp_path = "C:\\Program Files\\testapp\\version\\61\\"

Or do i have to do a brute force approach to searching all drives/
folders till it finds a path matching my program name?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a dictionary

2009-05-15 Thread Tobiah
On Tue, 12 May 2009 14:17:54 +0200, Jaime Fernandez del Rio wrote:

> This one I think I know... Try with:
> 
> for k in sorted(word_count) :
> print k,"=",word_count[k]
> 
> You need to do the sorting before iterating over the keys...

Isn't that what's happening here?  I read this as the
'sorted' function iterating over the keys in word_count,
then passing that sorted list to the 'for' loop, for a
second iteration over the sorted pairs.

No?

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


Re: Printing a hex character and prefixing it correctly

2009-05-15 Thread BgEddy
xama...@yahoo.com wrote:

> If I have an integer k, for instance;
> 
> k = 32 // BASE 10
> 
> How do I get print to print it out in HEX and PREFIXED with 0x? What
> is the PROPER WAY?
> 
> This does not work:
> 
>   print "This is hex 32: ", int(k, 16)
> 
> Xav

How about this :

k=32
print "This is hex 32: 0x%02X" % k

Kind Regards,
BgEddy

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


RE: Printing a hex character and prefixing it correctly

2009-05-15 Thread Andreas Tawn
> If I have an integer k, for instance;
> 
> k = 32 // BASE 10
> 
> How do I get print to print it out in HEX and PREFIXED with 0x? What
> is the PROPER WAY?
> 
> This does not work:
> 
>   print "This is hex 32: ", int(k, 16)
> 
> Xav

k = 32

print "This is hex 32: ", hex(k)

Cheers,

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


Re: Sorting a dictionary

2009-05-15 Thread J. Cliff Dyer
On Fri, 2009-05-15 at 09:57 -0700, Tobiah wrote:
> On Tue, 12 May 2009 14:17:54 +0200, Jaime Fernandez del Rio wrote:
> 
> > This one I think I know... Try with:
> > 
> > for k in sorted(word_count) :
> > print k,"=",word_count[k]
> > 
> > You need to do the sorting before iterating over the keys...
> 
> Isn't that what's happening here?  I read this as the
> 'sorted' function iterating over the keys in word_count,
> then passing that sorted list to the 'for' loop, for a
> second iteration over the sorted pairs.
> 
> No?
> 
> Tobiah

The code and the description you are responding to are by the same
poster.  The OP posted something quite different.

@Ronn:

The for statement, which is the line ending with ":" has all the control
over what order elements get processed in.  Compare the following cases:

>>> for x in ['hat', 'socks', 'shirt', 'pants']:
... print sorted(x)
aht
ckoss
hirst
anpst

In this case, each element of the list gets sorted.  That is, the
letters of each string are put in alphabetical order.  But they are
processed in the order they appeared in the list.  If you want to
process the elements of the list in alphabetical order, you have to sort
the list itself:

>>> for x in sorted(['hat', 'socks', 'shirt', 'pants']):
... print x
hat
pants
shirt
socks

Cheers,
Cliff



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


Re: Parsing Strings in Enclosed in Curly Braces

2009-05-15 Thread MRAB

Chris Rebert wrote:

On Fri, May 15, 2009 at 9:12 AM,   wrote:

How do you parse a string enclosed in Curly Braces?

For instance:

x = "{ABC EFG IJK LMN OPQ}"

I want to do x.split('{} ') and it does not work. Why does it not work
and what are EXCEPTIONS to using the split method?


.split() takes a *substring* to split on, *not* a set of individual
characters to split on. Read the Fine Docs.


That I want to split based on '{', '}' and WHITESPACE.


Well, you could use a regex, or you could just .find() where the
braces are, slice them off the ends of the string, and then split the
result on space.


Here's a function which splits on multiple characters:

def split_many(string, delimiters):
parts = [string]
for d in delimiters:
parts = sum((p.split(d) for p in parts), [])
return parts
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding location of an executable in a windows machine?

2009-05-15 Thread MRAB

nonse...@mynonsense.net wrote:

My python script calls another windows program file. I have the path
to that program hardcoded in it. Is there a way for python to
automatically find the path to this program?

testapp_path = "C:\\Program Files\\testapp\\version\\61\\"

Or do i have to do a brute force approach to searching all drives/
folders till it finds a path matching my program name?


The path to the Python script is given by __file__. If your other
program is in the same folder then you can use:

other_app_path = os.path.join(os.path.dirname(__file__), 
other_app_name)

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


Re: introspection question: get return type

2009-05-15 Thread Aahz
In article <4a0d2e07$0$9422$426a7...@news.free.fr>,
Bruno Desthuilliers   wrote:
>Aahz a écrit :
>> In article <4a0c6e42$0$12031$426a7...@news.free.fr>,
>> Bruno Desthuilliers   wrote:
>>> Marco Mariani a écrit :
 Bruno Desthuilliers wrote:
> Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
> sense given Python's dynamic typing.
 Unless he's really trying to write in Nohtyp,
>>> You meant "Notype" ?-)
>> 
>> Marco's spelling is correct.  Try "Nohtyp".reverse()
>
>Aazh... I know I'm a bit dumb sometimes, but do you *really* think I had 
>failed to spot this ???

  IIRC, English isn't your first language, so I figured better
safe than sorry; humor often mistranslates.  My apologies for casting
aspersions on your linguistic skills.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"In 1968 it took the computing power of 2 C-64's to fly a rocket to the moon.
Now, in 1998 it takes the Power of a Pentium 200 to run Microsoft Windows 98.
Something must have gone wrong."  --/bin/fortune
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing a hex character and prefixing it correctly

2009-05-15 Thread Dave Angel

xama...@yahoo.com wrote:

If I have an integer k, for instance;

k = 32 // BASE 10

How do I get print to print it out in HEX and PREFIXED with 0x? What
is the PROPER WAY?

This does not work:

  print "This is hex 32: ", int(k, 16)

Xav

  

How about
   print "This is hex 32: ", hex(k)


(This works in Python 2.6.2)

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


Re: Finding location of an executable in a windows machine?

2009-05-15 Thread Dave Angel

nonse...@mynonsense.net wrote:

My python script calls another windows program file. I have the path
to that program hardcoded in it. Is there a way for python to
automatically find the path to this program?

testapp_path = "C:\\Program Files\\testapp\\version\\61\\"

Or do i have to do a brute force approach to searching all drives/
folders till it finds a path matching my program name?


  
Do you actually need the path, or do you just want the program to run as 
though you had entered it at a command prompt?  Many of the APIs for 
launching other programs will do a path search, similar to what the DOS 
box in Windows does.  Try just leaving off the path entirely.


Or you can get the PATH environment variable, parse it, and search for 
those locations yourself.  But realize that the shell also looks in a 
few places not on the path, including at least  current directory and 
windows directory (eg.  c:\windows\system32 ).  And you very likely want 
to look a few other places, such as in Program Files.


But searching the drives raw is rarely a good idea, as it's quite likely 
there's a duplicate filename out there somewhere, and you want a 
deterministic algorithm for which one will run.


Depending on how fancy your program is, you may want to do the searching 
at install time, and store the result in an xxx.ini file or equivalent.  
That file would probably go somewhere in "Documents and Settings" 
directory structure, perhaps based on the current user.  That way you 
can document how the user will customize it.


If you need help on a specific python command, you'd also need to tell 
us what version of Python you're using.

print sys.version

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


Re: DOM implementation

2009-05-15 Thread Paul Boddie
On 15 Mai, 18:27, "Emanuele D'Arrigo"  wrote:
>
> I just had a look at libxml2dom, in particular its events.py file.
> Given that we are working from a standard your implementation is
> exceedingly similar to mine and had I know before I started writing my
> own classes I would have started from it instead! =)

Another implementation is probably a good thing, though, since I don't
trust my own interpretation of the specifications. ;-)

> Browsing through the code, the EventTarget class docstring reads:

[Long docstring cut]

> Naively, I implemented my EventTarget class storing its own listeners
> rather than global ones. Nevertheless, I'm not quite understanding
> this issue. Why shouldn't the listeners be stored directly on the
> EventTarget?

One reason for this might well be due to the behaviour of libxml2 and
libxml2dom: if I visit the same node in a document twice, obtaining a
node instance each time, these two instances will be different;
therefore, storing listeners on such instances is not very helpful
because the expectation that you will automatically see previously
added listeners on a node will not generally be fulfilled. With pxdom,
it may be a different situation, but libxml2dom is constrained by the
behaviour of libxml2: I don't attempt to check node equivalence and
then expose the structures representing a single node using a single
object; I generally try and instantiate as few Python objects,
wrapping libxml2 structures, as I can.

> I have a glimpse of understanding that if the
> DOMImplementation keeps EventTarget and Nodes (or Elements? which
> entity is supposed to support Events?) separate this might be
> necessary. But beside the fact that it's just a fuzzy and potentially
> incorrect intuition, I seem to think that the appropriate way to
> proceed would be for the DOMImplementation to provide a Node class
> that also inherits from EventTarget. In so doing the listeners would
> be immediately accessible as soon as one has a handle to a Node.

The libxml2dom.svg module has classes which inherit from EventTarget.
What I've tried to do is to make submodules to address particular
formats and document models.

> Furthermore, your code finds the bubbling route with the line:
>
> bubble_route = target.xpath("ancestor::*")
>
> That xpath method is a libxml method right?

I use libxml2's XPath support exposed via libxml2dom.Node.

> Indeed there is some vagueness in the W3C recommendations and the
> various documents offer very little redundancy with each other but
> require you to be knowledgeable about them all! I'm managing to piece
> together the pieces of the puzzle only after a couple of day having an
> in-depth read-through of DOM, DOM Events and a little bit of XML
> events to see how it all works in practice. XML events is also what's
> prompting me to think that Node/Elements classes of the implementation
> should also inherit from EventTarget as they can all be event
> targets.

I think that if I were to expose an event-capable DOM, other than that
provided for SVG, I would just have a specific submodule for that
purpose.

> > One of my tests tries to exercise the code, but I might be doing it
> > all completely wrong:
>
> >https://hg.boddie.org.uk/libxml2dom/file/91c0764ac7c6/tests/svg_event...
>
> Before I can comment I'd like to better understand what you are aiming
> for with libxml2dom. It seems to be providing some kind of conversion
> services from the xml structure generated by libxml to a dom-like
> structure (implemented by pxdom?).
> Is that correct?

Yes. The aim is to provide a PyXML DOM API on top of libxml2
documents.

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


Appending traceback from exception in child thread

2009-05-15 Thread Edd
Hi folks,

I have a some threadpool code that works like this :

tp = ThreadPool(number_of_threads)
futures = [tp.future(t) for t in tasks] # each task is callable
for f in futures:
print f.value() # <-- may propagate an exception

The idea being that a Future object represents a value that may or may
not have been computed yet and the .value() method will block until
that value is ready.

As the comment on the last line indicates, looking at the .value() of
a Future may give the return value of the associated task, or it may
also propagate an exception that was raised in a child thread.

Inside the implementation I store caught exceptions with code that
looks something like:

try:
self.return_value = self.task()
except:
self.exception = sys.exc_info()[1]

The problem I have is that when an exception is propagated in to the
parent thread by re-raising it, the part of the traceback from the
child thread is lost. So if the program dies due to such an exception,
I can't see what caused it by examining the printed traceback.

To solve this problem, I could of course grab the traceback in the
child thread and create some kind of custom exception that stashes the
trace inside. This could then be caught on the fringes of my code in
order to combine the tracebacks of parent and child together before
printing it. But I was wondering if there might be a nicer way that
keeps the original exception object. Perhaps something akin to gluing
the tracebacks together at the point where the exception is re-raised?

Kind regards,

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


Re: Can I get a value's name

2009-05-15 Thread Ken Seehart

jalanb3 wrote:

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
  
No, values[0] gives a reference to the value stored at index 0 of the 
values array, which does not contain the name.
In particular, the name and all other information about the expression 
itself is lost.  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).


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

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.  Chances are that if you want to do 
this, you need to rethink the problem instead.


# horribly bad, but sort of working, code follows:

foo = 'find me!'

def find_var(x):
   '''returns the name associated with a value'''
   for k,v in globals().items():
   if v == x:
   return k

print find_var(foo)

Note that a value can have several different names (and unnamed 
references) pointing at it, so the above code is not very general, but 
it may illustrate some interesting points.


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

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

  


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


ConfigParser and newlines

2009-05-15 Thread Minesh Patel
I am using ConfigParser to parse a config file and I want to maintain
the newlines, how is it possible. Example given below. BTW, is there
an alternative to configParser, should I use 'exec' instead. Is there
any support for yaml built-in or possibly in the future?

test.cfg

[Foo_Section]

BODY = Line of text 1

   Continuing Line of text 1


Executing the code
===
Python 2.5.1 Stackless 3.1b3 060516 (release25-maint, Mar  6 2009, 14:12:34)
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ConfigParser import RawConfigParser
>>> config = RawConfigParser()
>>> config.read('test.cfg')
['test.cfg']
>>> config.get('Foo_Section', 'BODY')
'Line of text 1\nContinuing Line of text 1'
>>>
===

I was expecting 'Line of text 1\n\nContinuing Line of text 1'
   
with 2 newlines, how can I achieve that with ConfigParser.



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


Re: ConfigParser and newlines

2009-05-15 Thread Mike Driscoll
On May 15, 1:09 pm, Minesh Patel  wrote:
> I am using ConfigParser to parse a config file and I want to maintain
> the newlines, how is it possible. Example given below. BTW, is there
> an alternative to configParser, should I use 'exec' instead. Is there
> any support for yaml built-in or possibly in the future?
>

The primary alternative to ConfigParser is Michael Foord's ConfigObj:

http://www.voidspace.org.uk/python/configobj.html

I don't know if it has yaml support or not though.

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


Re: ConfigParser and newlines

2009-05-15 Thread Tim Chase

test.cfg

[Foo_Section]

BODY = Line of text 1

   Continuing Line of text 1


Executing the code
===
Python 2.5.1 Stackless 3.1b3 060516 (release25-maint, Mar  6 2009, 14:12:34)
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

from ConfigParser import RawConfigParser
config = RawConfigParser()
config.read('test.cfg')

['test.cfg']

config.get('Foo_Section', 'BODY')

'Line of text 1\nContinuing Line of text 1'
===

I was expecting 'Line of text 1\n\nContinuing Line of text 1'
   
with 2 newlines, how can I achieve that with ConfigParser.


Not as best I can tell.  From my 
/usr/lib/python2.5/ConfigParser.py file, around line 441:


  if line[0].isspace() and cursect is not None and optname:
value = line.strip()
if value:
  cursect[optname] = "%s\n%s" % (cursect[optname], value)

That "value = line.strip()" is what's throwing away your extra 
newline.  Then the "if value" refuses to add the extra newline 
because it was a blank line.  It looks like this behavior was 
intentional?


-tkc






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


Re: Appending traceback from exception in child thread

2009-05-15 Thread Chris Mellon
On Fri, May 15, 2009 at 1:09 PM, Edd  wrote:
> Hi folks,
>
> I have a some threadpool code that works like this :
>
>    tp = ThreadPool(number_of_threads)
>    futures = [tp.future(t) for t in tasks] # each task is callable
>    for f in futures:
>        print f.value() # <-- may propagate an exception
>
> The idea being that a Future object represents a value that may or may
> not have been computed yet and the .value() method will block until
> that value is ready.
>
> As the comment on the last line indicates, looking at the .value() of
> a Future may give the return value of the associated task, or it may
> also propagate an exception that was raised in a child thread.
>
> Inside the implementation I store caught exceptions with code that
> looks something like:
>
>    try:
>        self.return_value = self.task()
>    except:
>        self.exception = sys.exc_info()[1]
>
> The problem I have is that when an exception is propagated in to the
> parent thread by re-raising it, the part of the traceback from the
> child thread is lost. So if the program dies due to such an exception,
> I can't see what caused it by examining the printed traceback.
>
> To solve this problem, I could of course grab the traceback in the
> child thread and create some kind of custom exception that stashes the
> trace inside. This could then be caught on the fringes of my code in
> order to combine the tracebacks of parent and child together before
> printing it. But I was wondering if there might be a nicer way that
> keeps the original exception object. Perhaps something akin to gluing
> the tracebacks together at the point where the exception is re-raised?
>
> Kind regards,
>
> Edd
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Take a look at the Deferred and Failure objects from Twisted. Deferred
is a deferred result with callback (basically a Future without the
blocking interface), and Failure is an asynchronous exception object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing Strings in Enclosed in Curly Braces

2009-05-15 Thread kay
On 15 Mai, 18:12, xama...@yahoo.com wrote:
> How do you parse a string enclosed in Curly Braces?
>
> For instance:
>
> x = "{ABC EFG IJK LMN OPQ}"
>
> I want to do x.split('{} ') and it does not work. Why does it not work
> and what are EXCEPTIONS to using the split method?
>
> That I want to split based on '{', '}' and WHITESPACE.
>
> Please advise.
>
> Regards,
> Xav

import string
ttable   = string.maketrans("{} ", "\1\1\1")
print x.translate(ttable).split("\1")   # -> ['', 'ABC', 'EFG', 'IJK',
'LMN', 'OPQ', '']

The validity of the translation+split depends on the presence of \1 in
the original string of course.

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


Re: SOAPpy(10060, 'Operation timed out')

2009-05-15 Thread Piet van Oostrum
> "Zhang, Ning"  (ZN) wrote:

>ZN> Hi all
>ZN> I am working for a energy company, we currently want to use api to load
>ZN> data into the database.

>ZN> I am new for soappy package. I have done a bit research on 
>ZN> http://www.ibm.com/developerworks/webse ... #resources
>ZN> ces> 
>ZN> and
>ZN> http://www.diveintopython.org/soap_web_ ... gging.html
>ZN>  

>ZN> I can make none of the examples from tutorial correct.  

These examples often use short-lived services. When the tutorials are a
couple of years old, the sites disappear and the examples don't work. I
have given a course on distributed object systems the last years and
every few years I have to change the examples because they stop working.

>ZN> I have also tried the the example from Endolith posted last year.

>ZN> viewtopic.php?f=19&t=10038&p=45872&hilit=soap#p45872
>ZN> ZN> 872&hilit=soap#p45872> 

>ZN> Code: Select all
>ZN>   

>ZN> from SOAPpy import WSDL

>ZN> wsdl_file = 'http://xurrency.com/api.wsdl'
>ZN> server = WSDL.Proxy(wsdl_file)
>ZN> values = server.getValuesInverse('usd')

>ZN> However, I got the error message below:  

>ZN> error: (10060, 'Operation timed out')

This works for me. Could it be that the xurrency.com site was
temporarily down? Or that your company's firewall blocks SOAP calls?
maybe you should ask your network manager.

I used this example in my last lectures and it worked also today:

from SOAPpy import SOAPProxy
url = "http://xurrency.com/servidor_soap.php";
namespace = "http://xurrency.com/api.wsdl";
server = SOAPProxy(url, namespace)
server.config.dumpSOAPOut = True
server.config.dumpSOAPIn = True
print server.getValue(100,"eur","usd")

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch str exception?

2009-05-15 Thread Terry Reedy

anuraguni...@yahoo.com wrote:

but the whole point of catching such exception is that i can print its
value
there are many such exceptions and hence it is not feasible to catch
them all or know them all unless i go thru src code.


I think you have discovered why they are gone in Py3 ;-).


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


Tkinter Window On Top

2009-05-15 Thread Trevor
Can a Tkinter application create a COM object and keep its own window
on top of it?

excel = win32com.client.Dispatch('Excel.Application')

I would like the user to be able to see and interact with the Excel
application but keep the Tkinter application on top.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding location of an executable in a windows machine?

2009-05-15 Thread Terry Reedy

nonse...@mynonsense.net wrote:

My python script calls another windows program file. I have the path
to that program hardcoded in it. Is there a way for python to
automatically find the path to this program?

testapp_path = "C:\\Program Files\\testapp\\version\\61\\"

Or do i have to do a brute force approach to searching all drives/
folders till it finds a path matching my program name?


Program Files directories are usually not part of the PATH environment 
variable.  A main program in Program Files is generally started by 
clicking on: an icon that points to it, an entry in Start Menu, its 
directory listing in Explorer, or a file whose extension is associated 
with it.  A subsidiary program is started by a main program that knows 
where is it in relation to the main program.


If a program is registered when installed, then there will be a registry 
key that is the same for all installations that points to its 
installation-specific location.  Python on Windows comes with a winreg 
module for accessing the registry.  You just need to find the key, 
possibly using the regedit utility and its search function.


Terry Jan Reedy

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


Re: Parsing Strings in Enclosed in Curly Braces

2009-05-15 Thread Peter Otten
k...@fiber-space.de wrote:

> ttable   = string.maketrans("{} ", "\1\1\1")
> print x.translate(ttable).split("\1")   # -> ['', 'ABC', 'EFG', 'IJK',
> 'LMN', 'OPQ', '']
> 
> The validity of the translation+split depends on the presence of \1 in
> the original string of course.

Keep one of the splitting characters to avoid that (theoretical) risk:

ttable = string.maketrans("{} ", "{{{")

Peter

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


Re: How to catch str exception?

2009-05-15 Thread Paul Rubin
"anuraguni...@yahoo.com"  writes:
> there are many such exceptions and hence it is not feasible to catch
> them all or know them all unless i go thru src code.

But that is true of all exceptions.  The alternative seems to be a
"checked exception" scheme like Java's, which in practice imposes a
huge pain on programmers, who have to modify type signatures all up
and down the call hierarchy every time they raise another exception at
the bottom level.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch str exception?

2009-05-15 Thread MRAB

Paul Rubin wrote:

"anuraguni...@yahoo.com"  writes:

there are many such exceptions and hence it is not feasible to catch
them all or know them all unless i go thru src code.


But that is true of all exceptions.  The alternative seems to be a
"checked exception" scheme like Java's, which in practice imposes a
huge pain on programmers, who have to modify type signatures all up
and down the call hierarchy every time they raise another exception at
the bottom level.


I would've thought that a modern IDE would do a lot of the work for you.
--
http://mail.python.org/mailman/listinfo/python-list


How do i generate a tuple from a generator ?

2009-05-15 Thread eye zak
Hi,

I have a situation where i want a tuple from a generator/sequence
comprehension.
I am wondering, is this possible ? or is this just a bad idea all together?

class iterator(object):
__slots__ = ('__iters',)

def __init__(self,*args):
assert len(args) != 0
self.__iters = tuple( __builtins__.iter(arg) for arg in args )

def __iter__(self,*args):
return self

def next(self):
return [ i.next() for i in self.__iters ]# HERE I WANT A TUPLE

This can also be accomplished with a generator function, but requires
while True loop. is that better ?

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


Re: How do i generate a tuple from a generator ?

2009-05-15 Thread Emile van Sebille

On 5/15/2009 1:58 PM eye zak said...

Hi,

I have a situation where i want a tuple from a generator/sequence
comprehension.
I am wondering, is this possible ? or is this just a bad idea all together?

class iterator(object):
__slots__ = ('__iters',)

def __init__(self,*args):
assert len(args) != 0
self.__iters = tuple( __builtins__.iter(arg) for arg in args )

def __iter__(self,*args):
return self

def next(self):
return [ i.next() for i in self.__iters ]# HERE I WANT A TUPLE

  return tuple(...)
Emile



This can also be accomplished with a generator function, but requires
while True loop. is that better ?

Isaac


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


Re: Just wondering

2009-05-15 Thread norseman

Gediminas Kregzde wrote:

Hello,

I'm Vilnius college II degree student and last semester our teacher
introduced us to python
I've used to program with Delphi, so I very fast adopted to python

Now I'm developing cross platform program and use huge amounts of
data. Program is needed to run as fast as it coud. I've read all tips
about geting performance, but got 1 bug: map function is slower than
for loop for about 5 times, when using huge amounts of data.
It is needed to perform some operations, not to return data.

I'm adding sample code:
from time import time

def doit(i):
   pass

def main():
   a = [0] * 1000
   t = time()
   map(doit, a)
   print "map time: " + str(time() - t)

def main2():
   t = time()
   a = [0] * 1000
   for i in a:
   pass
   print "loop time: " + str(time() - t)

main()  # takes approximately 5x times longer than main2()
main2()

I'm wondering were is catch?

I'm using python 2.6 on windows xp sp2 machine

P.S. Sorry for my broken English

===

cut n paste done


Using Laptop at 2.4 GHz
map time:  4.9281001091   map/loop = 5.7554...
loop time: 0.856245994568

Using Desktop at 3.1 GHz
map time: 3.4673515   map/loop = 7.6556...
loop time: 0.45368665


Yep - map is way slower

Your English is good enough for me to understand. What more is needed?
:)

Someone writing Python can probably say why.

Steve

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


Re: Just wondering

2009-05-15 Thread norseman

Marco Mariani wrote:

Gediminas Kregzde wrote:



def doit(i):
   pass

def main():
   a = [0] * 1000
   t = time()
   map(doit, a)
   print "map time: " + str(time() - t)


Here you are calling a function ten million times, build a list with of 
ten million None results, then throw it away.




def main2():
   t = time()
   a = [0] * 1000
   for i in a:
   pass
   print "loop time: " + str(time() - t)


Here you do nothing but iterating 'i' over the 'a' list.



main()  # takes approximately 5x times longer than main2()
main2()

I'm wondering were is catch?


Function calls are not free in python. They cost a lot more than they do 
in C, Delphi or other languages.




Gediminas - You did a good job of testing the overhead.  All good 
programmers do that!


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


Re: ConfigParser and newlines

2009-05-15 Thread Minesh Patel
> Not as best I can tell.  From my /usr/lib/python2.5/ConfigParser.py file,
> around line 441:
>
>  if line[0].isspace() and cursect is not None and optname:
>    value = line.strip()
>    if value:
>      cursect[optname] = "%s\n%s" % (cursect[optname], value)
>
> That "value = line.strip()" is what's throwing away your extra newline.
>  Then the "if value" refuses to add the extra newline because it was a blank
> line.  It looks like this behavior was intentional?
>

Is that a bug? What would be the use cases for stripping newlines
unnecessarily. Seems like the configParser is trying to be too clever.

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


ConfigParser examples?

2009-05-15 Thread Esmail

Hi all,

Can anyone point to on the web, or possibly share a simple example
of the use of the ConfigParser module?

I have a program that has a lot of flags in various places (yes,
ugly I know), so I am trying to consolidate this information in
a configuration file so that the program can pull the necessary
information from this place without the need to edit the program
and its flags.

Some sample code for using ConfigParser would be helpful - haven't
been able to find any on-line so far beyond the standard documentation.

Thanks,
Esmail

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


  1   2   >