XML Parsing

2007-03-27 Thread [EMAIL PROTECTED]
I want to parse this XML file:






filename

Hello




filename2

Hello2





This XML will be in a file called filecreate.xml

As you might have guessed, I want to create files from this XML file
contents, so how can I do this?
What modules should I use? What options do I have? Where can I find
tutorials? Will I be able to put
this on the internet (on a googlepages server)?

Thanks in advance to everyone who helps me.
And yes I have used Google but I am unsure what to use.

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


Re: Python automatic testing: mocking an imported module?

2007-03-27 Thread Peter Otten
Silfheed wrote:

> So we have the following situation: we have a testee.py that we want
> to automatically test out and verifiy that it is worthy of being
> deployed.  We want our tester.py to test the code for testee.py
> without changing the code for testee.py.  testee.py has a module in it
> that we want to mock in some tests and in others use the real module.
> 
> /foo.py:  (real module)
> class bar:
>def __init__(self):
> "I am real"
> 
> /foo_fake/foo.py: (fake module)
> class bar:
>def ___init__(self):
> "I am a banana"
> 
> /testee.py:
> import foo
> foo.bar()
> 
> /tester.py:
> from foo_fake import foo
>foo.bar()# prints I am a banana
>testee.py  # also prints I am a banana
> import foo
>foo.bar()   # prints I am real
>testee.py # also prints I am real
> 
> 
> This isnt working as we would like, does anyone have any tips  on how
> to get something like this working?

You can put foo_fake.foo into sys.modules as foo:

import sys
from foo_fake import foo

assert "foo" not in sys.modules
sys.modules["foo"] = foo

foo.bar()# prints I am a banana
import foo
foo.bar()# prints I am a banana

Peter

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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Alex Gibson

"Beliavsky" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Mar 26, 10:16 am, [EMAIL PROTECTED] (Cameron Laird) wrote:
>> In article 
>> <[EMAIL PROTECTED]>,[EMAIL PROTECTED] 
>> <[EMAIL PROTECTED]> wrote:
>
>> >Is there a mac version??
>> >Thanks
>> >Chris
>>
>> Yes.
>>
>> Several, in fact--all available at no charge.  The Python
>> world is different from what experience with Fortran might
>> lead you to expect.
>
> Your experience with Fortran is dated -- see below.
>
>>
>> I'll be more clear:  Fortran itself is a distinguished
>> language with many meritorious implementations.  It can be
>> costly, though, finding the implementation you want/need
>> for any specific environment.
>
> Gfortran, which supports Fortran 95 and a little of Fortran 2003, is
> part of GCC and is thus widely available. Binaries for g95, also based
> on GCC, are available for more than a dozen platforms, including
> Windows, Mac OS X, and Linux. I use both and consider only g95 mature,
> but gfortran does produce faster programs. Intel's Fortran compilers
> cost about $500 on Windows and Mac OS and $700 on Linux. It's not
> free, but I would not call it costly for professional developers.
>
> Speaking of money, gfortran and g95 have free manuals, the latter
> available in six languages
> http://ftp.g95.org/ . Final drafts of Fortran standards, identical to
> the official ISO standards, are freely available. The manual for Numpy
> costs $40 per copy.

Sun also provides its sun studio ide and compilers(c , c++ and fortran) free 
of charge on x86 linux
just have to register for free.
http://developers.sun.com/sunstudio/downloads/

Alex 


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


Re: wxPython, Syntax highlighting

2007-03-27 Thread Justin Ezequiel
On Mar 28, 2:56 pm, "Eric von Horst" <[EMAIL PROTECTED]> wrote:

> I am looking for wx widget that has the ability to show text, edit the
> text (like a TextCtrl) but also does syntax highlighting (if the text
> is e.g. XML or HTML).
> I have been looking in the latest wxPython version but I could not
> really find anything.

see
.\wxPython2.6 Docs and Demos\samples\ide\ActiveGridIDE.py

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


Re: PyDoc -g call to Alt-Installed Python

2007-03-27 Thread Peter Otten
D.Hering wrote:

> I have both python2.4 and 2.5 installed on a (k)ubuntu linux box. I'm
> trying to get the call to pydoc -g (pydoc server called from the
> system console) to recognize python2.5 rather than the system's
> default 2.4 release.
> 
> I've tried several different things so far, to no avail. My console
> scripting knowledge, so far, is minimal. Any help here is appreciated.

Copy Tools/scripts/pydoc from the Python2.5 source distribution into ~/bin.
Then change its first line from 

#!/usr/bin/env python 

to

#!/usr/bin/env python2.5

Peter

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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Tim Roberts
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

>On Mon, 26 Mar 2007 06:40:49 -0700, kyosohma wrote:
>
>> Fortran also appears to be a compiled language, whereas Python is an
>> interpreted language.
>
>Sheesh. Do Java developers go around telling everybody that Java is an
>interpreted language? I don't think so.
>
>What do you think the "c" in ".pyc" files stands for? "Cheese"?

Well, I'm being a bit argumentative here, but it's hard to deny that the
use of "compiled" in the context of .pyc (or .javac) is very different from
the use of "compiled" in the context of running gcc.  Once upon a time,
Basic enthusiasts would have used the word "tokenized" to describe .pyc
files.

A .pyc file is, in fact, interpreted by an intermediate language
interpreter.  I don't understand why anyone would be embarrassed by that.
Is it fast enough?  It certainly is for MY needs.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython, Syntax highlighting

2007-03-27 Thread Eric von Horst
Hi,

I am looking for wx widget that has the ability to show text, edit the
text (like a TextCtrl) but also does syntax highlighting (if the text
is e.g. XML or HTML).
I have been looking in the latest wxPython version but I could not
really find anything.

Any suggestions?

(I need this because my collegue who is very Java-minded can
apparently do that without any problems)

Kd

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


Re: Mastering Python

2007-03-27 Thread Hendrik van Rooyen
 "Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote:


>Dennis Lee Bieber a écrit :
>> On Wed, 21 Mar 2007 21:40:51 +0100, Bruno Desthuilliers
>> <[EMAIL PROTECTED]> declaimed the following in
>> comp.lang.python:
>>>
>> For future reference, and I hope you don't mind the lesson,

>I don't.

>> the past
>> tense of "bind" is "bound"

>err... I knew that, of course.

If one were to apply Dennis' ..ind to ..ound rule in reverse,
then the present tense of the verb "hound"
will be "hind" - bound to be..

English is such a a marvellously logical, consistent language.

For instance, there is a disease of the lungs called phthisis,
which is pronounced something like: "tie-sis"...

Pretty obvious of course, as is the pronounciation of the
name:  "Cholmondely"

- Hendrik


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


Re: with timeout(...):

2007-03-27 Thread Hendrik van Rooyen
 "Nick Craig-Wood" <[EMAIL PROTECTED]> wrote:


> Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:

> 
> >  But would be useful to be able to do without messing with
> >  threads and GUI and imports. 
> >  Could be hard to implement as the interpreter would have 
> >  to be assured of getting control back periodically, so a 
> >  ticker interrupt routine is called for - begins to sound more 
> >  like a kernel function to me.  
> >  Isn't there something available that could be got at via ctypes?
> 
> I think if we aren't executing python bytecodes (ie are blocked in the
> kernel or running in some C extension) then we shouldn't try to
> interrupt.  It may be possible - under unix you'd send a signal -
> which python would act upon next time it got control back to the
> interpreter, but I don't think it would buy us anything except a whole
> host of problems!

Don't the bytecodes call underlying OS functions? - so is there not a case
where a particular bytecode could block, or all they all protected by
time outs?
Embedded code would handle this sort of thing by interrupting anyway
and trying to clear the mess up afterward - if the limit switch does not
appear after some elapsed time, while you are moving the 100 ton mass,
you should abort and alarm, regardless of anything else...
And if the limit switch sits on a LAN device, the OS timeouts could be
wholly inappropriate...

- Hendrik

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


Re: Can't use class variable with private nested class

2007-03-27 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:
   ...
> class Outer:
>   class Inner:
>   printOnce = True
> 
>   def __init__(self):
>   if Outer.Inner.printOnce:
>   print 'Printing once.'
>   Outer.Inner.printOnce = False
> 
>   def __init__(self):
>   first = Outer.Inner()
>   second = Outer.Inner()
> 
> outer = Outer()
> 
> 
> However the following code, which has a private nested class, does not
> work:
> class Public:
>   class __Private:
>   printOnce = True
> 
>   def __init__(self):
>   print 'Creating a __Private instance'
>   if Public.__Private.printOnce:

When, anywhere "immediately inside" a class named X, you use a name
__foo starting with two underscores, that name is mangled to _X__foo.
Here, you're inside class __Private, so the mangling of __Private is to
_Private__Private (I'd actually have expected more stray underscores
hither and thither, but that's the gist of it).

>   print 'Printing once.'
>   Public.__Private.printOnce = False
> 
>   def __init__(self):
>   print 'Creating a Public instance'
>   first = Public.__Private()
>   second = Public.__Private()
> 
> public = Public()
> 
> Attempting to run the code will produce this error:
> AttributeError: class Public has no attribute '_Private__Private'
> 
> What can be done so that this private nested class can have the same
> functionality as the public nested class?

Forget all the naming silliness and use self.__class__.printOnce
instead.


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


Can't use class variable with private nested class

2007-03-27 Thread tron . thomas
The following code will print a message only once:
class PrintOnce:
printOnce = True

def __init__(self):
if PrintOnce.printOnce:
print 'Printing once.'
PrintOnce.printOnce = False

first = PrintOnce()
second = PrintOnce()

The following code will do the same thing for a nested class:
class Outer:
class Inner:
printOnce = True

def __init__(self):
if Outer.Inner.printOnce:
print 'Printing once.'
Outer.Inner.printOnce = False

def __init__(self):
first = Outer.Inner()
second = Outer.Inner()

outer = Outer()


However the following code, which has a private nested class, does not
work:
class Public:
class __Private:
printOnce = True

def __init__(self):
print 'Creating a __Private instance'
if Public.__Private.printOnce:
print 'Printing once.'
Public.__Private.printOnce = False

def __init__(self):
print 'Creating a Public instance'
first = Public.__Private()
second = Public.__Private()

public = Public()

Attempting to run the code will produce this error:
AttributeError: class Public has no attribute '_Private__Private'

What can be done so that this private nested class can have the same
functionality as the public nested class?

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


Re: with timeout(...):

2007-03-27 Thread Klaas
On Mar 27, 3:28 pm, Paul Rubin  wrote:
> Nick Craig-Wood <[EMAIL PROTECTED]> writes:
> > It could be made to work I'm sure by getting the interpreter to check
> > for timeouts every few hundred bytecodes (like it does for thread
> > switching).
>
> Is there some reason not to use sigalarm for this?

 * doesn't work with threads
 * requires global state/handler
 * cross-platform?

-Mike

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


Re: __init__.py

2007-03-27 Thread Tina I
Jorgen Grahn wrote:
> On Mon, 26 Mar 2007 08:27:19 +0200, Tina I <[EMAIL PROTECTED]> wrote:
>> Tina I wrote:
>>> When looking at other peoples code (to learn from it) I keep seeing an 
>>> empty file named "__init__.py". What's the purpose of this?
>>>
>>> Thanks
>>> Tina
>> Duh! Never mind... found it.
>> Kinda neat actually :)
> 
> /What/ was neat? It's polite in cases like this to explain what the
> answer or solution was.
> 
> I have never seen an empty __init__.py, and I'd like to know what its
> purpose could be.
> 
> BR,
> /Jorgen
> 
Sorry, it was just that it was so easy to find right there in the 
documentation. I had just missed it the first time around. So I kinda 
assumed that since it was spelled out so well in the doc I was asking a 
very stupid question.
But anyway, it can be found here: 
http://www.python.org/doc/2.1.3/tut/node8.html#SECTION00840

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


ANN: Gracie v0.2 -- a local-account OpenID provider

2007-03-27 Thread Ben Finney
Howdy all,

I'm pleased to announce the creation of the Gracie project.

What is Gracie?
===

Gracie is an OpenID server (a "provider" in OpenID terminology) that 
serves OpenID identities for the local system PAM accounts. It 
authenticates users with a username/password challenge.

The OpenID protocol is documented at http://openid.net/>.

Gracie is intended for use within trusted environments that have an 
existing authentication system available via PAM (e.g. most GNU/Linux 
environments), that would like to provide OpenIDs for all local users 
instead of maintaining disparate web-based accounts for local 
services.

What can Gracie do now?
===

Gracie 0.2 is still alpha-development software, not intended for use 
in production environments. That said, this version does satisfy some 
basic requirements.

Currently Gracie can serve OpenID 1.1 authentication for local PAM 
users. It will authenticate the user with a web form, using the PAM 
system where the Gracie server is running. It assumes that any 
consumer request for identity is authorised to be given the user's 
identity.

What improvements are needed?
=

The current state of Gracie is functional but still needs much 
improvement. Please check the TODO.txt file in the source package for 
a list of improvements that need to be made.


As of this announcement, Gracie version 0.2 is available.

The project's home page is http://trac.whitetree.org/gracie/>.

-- 
 \ "When I turned two I was really anxious, because I'd doubled my |
  `\   age in a year. I thought, if this keeps up, by the time I'm six |
_o__)   I'll be ninety."  -- Steven Wright |
Ben Finney <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python automatic testing: mocking an imported module?

2007-03-27 Thread Ben Finney
"Silfheed" <[EMAIL PROTECTED]> writes:

> So we have the following situation: we have a testee.py that we want
> to automatically test out and verifiy that it is worthy of being
> deployed.

This is sometimes called the "module under test". I wish there was a
more succinct name in common usage.

> We want our tester.py to test the code for testee.py
> without changing the code for testee.py.

This is called a "unit test" for the module.

> testee.py has a module in it

Looking at your example, testee.py *imports* a module; it doesn't
contain another one.

> that we want to mock in some tests and in othemodule.

Excellent idea.


= foo.py =
class Bar(object):
def __init__(self):
self.name = "bar"
=

= dostuff.py =
import foo

def get_bar():
return foo.Bar()
=

= test_dostuff.py =
import dostuff

class Mock_foo_module(object):
""" Mock object for foo module """

class Bar(object):
def __init__(self):
self.name = "banana"

def test_dostuff_get_bar_should_create_bar():
""" The dostuff.get_bar function should create a new Bar """
dostuff.foo = Mock_foo_module()
test_bar = dostuff.get_bar()
if not test_bar.name == "banana":
raise AssertionError("test_bar.name should be banana")
=

This is simply using an instance of a class (Mock_foo_module) to be a
mock 'module' object. That mock module has the required 'Bar'
attribute, bound to a class; so the 'dostuff' module's 'foo' attribute
can be replaced with our mock module object for the purpose of the
test.

The mock module's Bar class behaves in an idiomatic way (setting the
'name' attribute of its instance to a known value) that we use to
check whether the 'dostuff' module actually used our mock module.

This can be extended to mock any module interface you like, and then
confirm that the module under test has actually used the module as
expected.

-- 
 \ "A politician is an animal which can sit on a fence and yet |
  `\   keep both ears to the ground."  -- Henry L. Mencken |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyPy 1.0: JIT compilers for free and more

2007-03-27 Thread Ben Finney
Carl Friedrich Bolz <[EMAIL PROTECTED]> writes:

> ==
> PyPy 1.0: JIT compilers for free and more
> ==
>
> Welcome to the PyPy 1.0 release - a milestone integrating the
> results of four years of research, engineering, management and
> sprinting efforts, concluding the 28 months phase of EU co-funding!

Fabulous! Congratulations to all who contributed to getting PyPy to
this significant milestone.

Here's to all the cool new things people will be doing with PyPy!

-- 
 \  "If nothing changes, everything will remain the same."  -- |
  `\   Barne's Law |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib timeout issues

2007-03-27 Thread Nick Vatamaniuc
On Mar 27, 4:41 pm, "supercooper" <[EMAIL PROTECTED]> wrote:
> On Mar 27, 3:13 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > En Tue, 27 Mar 2007 16:21:55 -0300, supercooper <[EMAIL PROTECTED]>
> > escribió:
>
> > > I am downloading images using the script below. Sometimes it will go
> > > for 10 mins, sometimes 2 hours before timing out with the following
> > > error:
>
> > > urllib.urlretrieve(fullurl, localfile)
> > > IOError: [Errno socket error] (10060, 'Operation timed out')
>
> > > I have searched this forum extensively and tried to avoid timing out,
> > > but to no avail. Anyone have any ideas as to why I keep getting a
> > > timeout? I thought setting the socket timeout did it, but it didnt.
>
> > You should do the opposite: timing out *early* -not waiting 2 hours- and
> > handling the error (maybe using a queue to hold pending requests)
>
> > --
> > Gabriel Genellina
>
> Gabriel, thanks for the input. So are you saying there is no way to
> realistically *prevent* the timeout from occurring in the first
> place?  And by timing out early, do you mean to set the timeout for x
> seconds and if and when the timeout occurs, handle the error and start
> the process again somehow on the pending requests?  Thanks.
>
> chad

Chad,

Just run the retrieval in a Thread. If the thread is not done after x
seconds, then handle it as a timeout and then retry, ignore, quit or
anything else you want.

Even better, what I did for my program is first gather all the URLs (I
assume you can do that), then group by servers, i.e. n # of images
from foo.com, m # from bar.org  Then start a thread for each
server (with some possible maximum number of threads), each one of
those threads will be responsible for retrieving images from only one
server (this is to prevent a DoS pattern). Let each of the server
threads start a 'small' retriever thread for each image (this is to
handle the timeout you mention).

So you have two different threads -- one per server to parallelize
downloading, which in turn will spawn and one per download to handle
timeout. This way you will (ideally) saturate your bandwidth but you
only get one image per server at a time so you still 'play nice' with
each of the servers.  If you want to have a max # of server threads
running (in case you have way to many servers to deal with) then run
batches of server threads.

Hope this helps,
Nick Vatamaniuc

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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Steven D'Aprano
On Tue, 27 Mar 2007 12:11:01 -0600, Erik Johnson wrote:

> But seriously... I'm not a language or architecture guru.  Is there any
> real difference between a JVM and an interpreter? I mean, I have some
> general feel that bytecode is a lower-level, more direct and more efficient
> thing to be interpreting that Java or Python source, but at the bottom
> level, you are still running an interpreter which is going to be
> (significantly?) more inefficient than executing native machine instructions
> directly on the CPU, right?

Thirty (or more?) years ago, the differences between compilers and
interpreters was fairly large. Interpreters would scan the source code of
each and every line. If you had a loop, each line in the loop would be
parsed each time around the loop. Despite 30+ years of progress, that's
still the model that many (most?) people have in their head when they
think of "interpreted language". That's why "interpreted" is the Kiss of
Death to anyone interested in speed -- whether true or not.

def if_(): # interpreted function
exec 'x = 0'
exec """for i in range(100):
exec 'x += i'"""
return x

def cf(): # compiled function
x = 0
for i in range(100):
x += i
return x

>>> timeit.Timer('cf()', 'from __main__ import cf').repeat(3, 1000)
[0.054703950881958008, 0.038740158081054688, 0.041306018829345703]
>>> timeit.Timer('if_()', 'from __main__ import if_').repeat(3, 1000)
[16.228797912597656, 16.261317014694214, 15.885524034500122]


But these days, and probably for the last decade at least, the nice neat
lines between "compiled" and "interpreted" is much fuzzier. So-called
interpreted languages don't parse the source code every time it is run.
They compile to byte-code, which is interpreted in a virtual machine in
the same way that compiled code is interpreted in a real machine.

Even that distinction isn't necessarily cut and dried. On modern CPUs,
machine code itself can be implemented in a mini-language, which naturally
is interpreted by an interpreter built into the CPU. The "real" machine on
the CPU is likely to itself include "virtual" machines, up to and
including entire emulators of other CPUs.

(Note: for each and every generalization I have made, there are almost
certainly exceptions. I think that just supports my contention that the
generalizations about "compiled" and "interpreted" languages are more
misleading than useful.)


> Why is Python able to automatically compile source into bytecode on the
> fly (when needed) but Java still forces you to do so explicitly?

That probably has more to do with different programming models than
different technologies. I'm sure somebody could build an interactive
complier/interpreter for Java like Python's. If nobody has, it is probably
more to do with nobody seeing the need of such than because it can't be
done.

I suspect that the advantages of an interactive system are much less for
languages like Java that have static type declarations.


> I don't mean to bash Java - I think it has it's place as well, but I
> mean to note that Java is very carefully marketed whereas Python's image is
> not managed by a major, international corporation.

Exactly. And that's why I think it does Python no favours at all to
keep emphasising the interpreter over the compiler. It gives too many
people the wrong idea.



-- 
Steven D'Aprano 

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


Re: looking for RSS generator

2007-03-27 Thread alex23
> I'm looking for sample code to generate an RSS feed.

For this, I highly recommend PyRSS2Gen: 
http://www.dalkescientific.com/Python/PyRSS2Gen.html

Very straightforward.

> I can annotate
> my html code with comments/tags to mark the articles, all I need is an
> "engine" to process the pages and generate the rss file.

If you're wanting to convert HTML to RSS, I'd recommend using
BeautifulSoup for parsing the HTML: 
http://www.crummy.com/software/BeautifulSoup/

Hope this helps.

-alex23


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


Re: socket read timeout

2007-03-27 Thread hg
Facundo Batista wrote:

> hg wrote:
> 
>> Do you mean use select ?
> 
> No, socket's timeout:
> 
 import socket
 s = socket.socket()
 s.settimeout(5)
 ...
> 
> Regards,
> 
> --
> .   Facundo
> .
> Blog: http://www.taniquetil.com.ar/plog/
> PyAr: http://www.python.org/ar/


My issue with that is the effect on write: I only want a timeout on read ...
but anyway ...

Thanks,

hg


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


PyDoc -g call to Alt-Installed Python

2007-03-27 Thread D.Hering
I have both python2.4 and 2.5 installed on a (k)ubuntu linux box. I'm
trying to get the call to pydoc -g (pydoc server called from the
system console) to recognize python2.5 rather than the system's
default 2.4 release.

I've tried several different things so far, to no avail. My console
scripting knowledge, so far, is minimal. Any help here is appreciated.

Thanks,
-Dieter

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


Re: Python automatic testing: mocking an imported module?

2007-03-27 Thread Chris Lasher
On Mar 27, 6:18 pm, "Silfheed" <[EMAIL PROTECTED]> wrote:
> Heyas
>
> So we have the following situation: we have a testee.py that we want
> to automatically test out and verifiy that it is worthy of being
> deployed.  We want our tester.py to test the code for testee.py
> without changing the code for testee.py.  testee.py has a module in it
> that we want to mock in some tests and in others use the real module.

I think you mean "testee.py *imports* a module", rather than "has a
module in it". Semantics but I was thrown off by this at first.

Why not write tests for the module that testee.py imports (here called
"foo.py")? If you write out the tests and foo.py passes to spec, then
you should feel confident it will work correctly with testee.py. Never
trust it; always play paranoid coder, but feel comfortable enough
using it.

After all, why should you feel comfortable using modules in the
standard library? Nobody guarantees bugs don't still lurk in there
(heck, c.l.p just found one in pdb today), however, they have unit
tests out the wazzoo that demonstrate, to the best of our knowledge,
the module works to spec. If that approach is good enough for the
standard library, wouldn't it be good enough for you?

Chris

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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Beliavsky
On Mar 27, 6:32 am, [EMAIL PROTECTED] (Cameron Laird) wrote:
> In article <[EMAIL PROTECTED]>,Beliavsky <[EMAIL PROTECTED]> wrote:
>
> .
> .
> .
>
>
>
> >Your experience with Fortran is dated -- see below.
>
> >> I'll be more clear:  Fortran itself is a distinguished
> >> language with many meritorious implementations.  It can be
> >> costly, though, finding the implementation you want/need
> >> for any specific environment.
>
> >Gfortran, which supports Fortran 95 and a little of Fortran 2003, is
> >part of GCC and is thus widely available. Binaries for g95, also based
> >on GCC, are available for more than a dozen platforms, including
> >Windows, Mac OS X, and Linux. I use both and consider only g95 mature,
> >but gfortran does produce faster programs. Intel's Fortran compilers
> >cost about $500 on Windows and Mac OS and $700 on Linux. It's not
> >free, but I would not call it costly for professional developers.
>
> >Speaking of money, gfortran and g95 have free manuals, the latter
> >available in six languages
> >http://ftp.g95.org/. Final drafts of Fortran standards, identical to
> >the official ISO standards, are freely available. The manual for Numpy
> >costs $40 per copy.
>
> My experience with Fortran is indeed dated.  However,
> I still work with university groups that balk at $500
> for valuable software--sometimes because of admini-
> strative conflicts with licensing (example:  the group
> needs an educational license that fits its team
> perfectly, but educational license have to be approved
> by a campus-wide office that involves the group in
> expenses uncovered by its grants, and ... complications
> ensue).  Intel's compiler, for example, is a great deal,
> and recognized as a trivial expense sometimes--but
> judged utterly impossible by a research group down a
> different corridor.
>
> My summary:  practical success depends on specific
> details, and specific details in the Fortran and Python
> worlds differ.
>
> Also, Beliavsky, thanks for your report on the pertinent
> Fortran compilers.  There *are* other proprietary Fortan
> compilers extant; do you expect them to fade away,
> leaving only g* and Intel, or are you simply remarking
> on those two as the (intellectual) market leaders?

My point was that a few years ago an advantage of Python+Numeric or
Octave or R over Fortran is that the former let one work at a much
higher level, if one restricted oneself to using only free tools. The
creation of g95 and gfortran has changed that somewhat, and the
existence of commercial compilers is a plus, since they can surpass
the free compilers in performance (Intel), functionality (creating
Windows GUI programs entirely in Fortran, for example) or diagnosing
errors (NAG, Lahey/Fujitsu and Salford/Silverfrost). A research group
could purchase a single license of a commercial compiler to use in
nightly builds but use the free compilers for development.

Which commercial compilers will fade away? Decent free compilers will
hurt the market for mediocre commercial ones, which may explain the
demise of the compiler from NA Software. The Fortran 2003 standard
adds many new features to Fortran 95, thus making big demands on
vendors, and I have heard that Lahey and Salford will not be upgrading
their compilers to the new standard. The active vendors appear to be
Absoft, IBM, Intel, Pathscale, Portland, and Sun.

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


looking for RSS generator

2007-03-27 Thread jd
I'm looking for sample code to generate an RSS feed.  I can annotate
my html code with comments/tags to mark the articles, all I need is an
"engine" to process the pages and generate the rss file.  If I was a
python wiz I'm sure I could do this quickly but as a newbie, an assist
here would certainly make this task go faster.  Thanks...

-- jeff

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


Re: PyPy 1.0: JIT compilers for free and more

2007-03-27 Thread Luis M. González

Carl Friedrich Bolz wrote:
> ==
> PyPy 1.0: JIT compilers for free and more
> ==
>
> Welcome to the PyPy 1.0 release - a milestone integrating the results
> of four years of research, engineering, management and sprinting
> efforts, concluding the 28 months phase of EU co-funding!
>
> Although still not mature enough for general use, PyPy 1.0 materializes
> for the first time the full extent of our original vision:
>
> - A flexible Python interpreter, written in "RPython":
>
>- Mostly unaware of threading, memory and lower-level target platform
>  aspects.
>- Showcasing advanced interpreter features and prototypes.
>- Passing core CPython regression tests, translatable to C, LLVM and
> .NET.
>
> - An advanced framework to translate such interpreters and programs:
>
>- That performs whole type-inference on RPython programs.
>- Can weave in threading, memory and target platform aspects.
>- Has low level (C, LLVM) and high level (CLI, Java, JavaScript)
> backends.
>
> - A **Just-In-Time Compiler generator** able to **automatically**
>enhance the low level versions of our Python interpreter, leading to
>run-time machine code that runs algorithmic examples at speeds typical
>of JITs!
>
> Previous releases, particularly the 0.99.0 release from February,
> already highlighted features of our Python implementation and the
> abilities of our translation approach but the **new JIT generator**
> clearly marks a major research result and gives weight to our vision
> that one can generate efficient interpreter implementations, starting
> from a description in a high level language.
>
> We have prepared several entry points to help you get started:
>
> * The main entry point for JIT documentation and status:
>
> http://codespeak.net/pypy/dist/pypy/doc/jit.html
>
> * The main documentation and getting-started PyPy entry point:
>
> http://codespeak.net/pypy/dist/pypy/doc/index.html
>
> * Our online "play1" demos showcasing various Python interpreters,
>features (and a new way to program AJAX applications):
>
> http://play1.codespeak.net/
>
> * Our detailed and in-depth Reports about various aspects of the
>project:
>
> http://codespeak.net/pypy/dist/pypy/doc/index-report.html
>
> In the next few months we are going to discuss the goals and form of
> the next stage of development - now more than ever depending on your
> feedback and contributions - and we hope you appreciate PyPy 1.0 as an
> interesting basis for greater things to come, as much as we do
> ourselves!
>
> have fun,
>
>  the PyPy release team,
>  Samuele Pedroni, Armin Rigo, Holger Krekel, Michael Hudson,
>  Carl Friedrich Bolz, Antonio Cuni, Anders Chrigstroem, Guido Wesdorp
>  Maciej Fijalkowski, Alexandre Fayolle
>
>  and many others:
>  http://codespeak.net/pypy/dist/pypy/doc/contributor.html
>
>
> What is PyPy?
> 
>
> Technically, PyPy is both a Python interpreter implementation and an
> advanced compiler, or more precisely a framework for implementing dynamic
> languages and generating virtual machines for them.
>
> The framework allows for alternative frontends and for alternative
> backends, currently C, LLVM and .NET.  For our main target "C", we can
> can "mix in" different garbage collectors and threading models,
> including micro-threads aka "Stackless".  The inherent complexity that
> arises from this ambitious approach is mostly kept away from the Python
> interpreter implementation, our main frontend.
>
> PyPy is now also a Just-In-Time compiler generator.  The translation
> framework contains the now-integrated JIT generation technology.  This
> depends only on a few hints added to the interpreter source and should
> be able to cope with the changes to the interpreter and be generally
> applicable to other interpreters written using the framework.
>
> Socially, PyPy is a collaborative effort of many individuals working
> together in a distributed and sprint-driven way since 2003.  PyPy would
> not have gotten as far as it has without the coding, feedback and
> general support from numerous people.
>
> Formally, many of the current developers were involved in executing an
> EU contract with the goal of exploring and researching new approaches
> to language and compiler development and software engineering.  This
> contract's duration is about to end this month (March 2007) and we are
> working and preparing the according final review which is scheduled
> for May 2007.
>
> For the future, we are in the process of setting up structures to help
> maintain conceptual integrity of the project and to discuss and deal
> with funding opportunities related to further PyPy sprinting and
> developments. See here for results of the discussion so far:
>
>  http://codespeak.net/pipermail/pypy-dev/2007q1/003577.html
>
>
> 1.0.0 Feature highlights
> =

Re: reusing generators

2007-03-27 Thread Paul Rubin
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> Hello, I have a two large files that I need to read in records from
> and compare in a pairwise fashion: Memory is an issue, so I want to
> use a generator to get each record one at a time. However, doing the
> comparisons with nested for loops, the inner generator will run out of
> items. How can I restart the generator from the beginning of the file
> each time through the outer loop? Thanks!

If the files are that large, maybe you want to rethink that quadratic
algorithm.  But if you really want to restart the generator, the
simplest way is just close and re-open the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Auto execute python in USB flash disk

2007-03-27 Thread Ben Finney
"Ene" <[EMAIL PROTECTED]> writes:

> Install the free PortablePython from http://www.portablepython.com/
> on your USB flash drive, and go from there.

To be clear: In addition to being a zero-cost download, Portable
Python is free software:

Python® distribution included in Portable Python is licensed under
PSF License, SciTE is licensed under SciTE license and Portable
Python scripts are licensed under GPL license.

http://www.portablepython.com/site/download/>

-- 
 \ "I know when I'm going to die, because my birth certificate has |
  `\an expiration date."  -- Steven Wright |
_o__)  |
Ben Finney

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

reusing generators

2007-03-27 Thread [EMAIL PROTECTED]
Hello, I have a two large files that I need to read in records from
and compare in a pairwise fashion: Memory is an issue, so I want to
use a generator to get each record one at a time. However, doing the
comparisons with nested for loops, the inner generator will run out of
items. How can I restart the generator from the beginning of the file
each time through the outer loop? Thanks!

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


Re: PyPy 1.0: JIT compilers for free and more

2007-03-27 Thread skip

Carl> Welcome to the PyPy 1.0 release...
...
Carl> - A **Just-In-Time Compiler generator** able to **automatically**
Carl>   enhance the low level versions of our Python interpreter,
Carl>   leading to run-time machine code that runs algorithmic examples
Carl>   at speeds typical of JITs!

Woo hoo!  Congratulations to all the PyPynistas!

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


Re: with timeout(...):

2007-03-27 Thread Paul Rubin
Nick Craig-Wood <[EMAIL PROTECTED]> writes:
> It could be made to work I'm sure by getting the interpreter to check
> for timeouts every few hundred bytecodes (like it does for thread
> switching).

Is there some reason not to use sigalarm for this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket read timeout

2007-03-27 Thread Facundo Batista
hg wrote:

> Do you mean use select ?

No, socket's timeout:

>>> import socket
>>> s = socket.socket()
>>> s.settimeout(5)
>>> ...

Regards, 

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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


Python automatic testing: mocking an imported module?

2007-03-27 Thread Silfheed
Heyas

So we have the following situation: we have a testee.py that we want
to automatically test out and verifiy that it is worthy of being
deployed.  We want our tester.py to test the code for testee.py
without changing the code for testee.py.  testee.py has a module in it
that we want to mock in some tests and in others use the real module.

/foo.py:  (real module)
class bar:
   def __init__(self):
"I am real"

/foo_fake/foo.py: (fake module)
class bar:
   def ___init__(self):
"I am a banana"

/testee.py:
import foo
foo.bar()

/tester.py:
from foo_fake import foo
   foo.bar()# prints I am a banana
   testee.py  # also prints I am a banana
import foo
   foo.bar()   # prints I am real
   testee.py # also prints I am real


This isnt working as we would like, does anyone have any tips  on how
to get something like this working?

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


Re: pattern search

2007-03-27 Thread Gabriel Genellina
En Tue, 27 Mar 2007 18:42:15 -0300, Diez B. Roggisch <[EMAIL PROTECTED]>  
escribió:

> Paul McGuire schrieb:
>> On Mar 27, 10:18 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>>> Fabian Braennstroem wrote:
 while iter:
 value = model.get_value(iter, 1)
 if value.endswith("."+ pattern): [...]

 Now, I would like to improve it by searching for different 'real'
 patterns just like using 'ls' in bash. E.g. the entry
 'car*.pdf' should select all pdf files with a beginning 'car'.
 Does anyone have an idea, how to do it?

>>> Use regular expressions. They are part of the module "re". And if you  
>>> use them, ditch your code above, and make it just search for a pattern  
>>> all the time. Because the above is just the case of
>>> *.ext

>> The glob module is a more direct tool based on the OP's example.  The
>> example he gives works directly with glob.  To use re, you'd have to
>> convert to something like "car.*\.pdf", yes?

> I'm aware of the glob-module. But it only works on files. I was under
> the impression that he already has a list of files he wants to filter
> instead of getting it fresh from the filesystem.

In that case the best way would be to use the fnmatch module - it already  
knows how to translate from car*.pdf into the right regexp. (The glob  
module is like a combo os.listdir+fnmatch.filter)

-- 
Gabriel Genellina

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


Re: urllib timeout issues

2007-03-27 Thread Gabriel Genellina
En Tue, 27 Mar 2007 17:41:44 -0300, supercooper <[EMAIL PROTECTED]>  
escribió:

> On Mar 27, 3:13 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
>> En Tue, 27 Mar 2007 16:21:55 -0300, supercooper <[EMAIL PROTECTED]>
>> escribió:
>>
>> > I am downloading images using the script below. Sometimes it will go
>> > for 10 mins, sometimes 2 hours before timing out with the following
>> > error:
>>
>> > urllib.urlretrieve(fullurl, localfile)
>> > IOError: [Errno socket error] (10060, 'Operation timed out')
>>
>> > I have searched this forum extensively and tried to avoid timing out,
>> > but to no avail. Anyone have any ideas as to why I keep getting a
>> > timeout? I thought setting the socket timeout did it, but it didnt.
>>
>> You should do the opposite: timing out *early* -not waiting 2 hours- and
>> handling the error (maybe using a queue to hold pending requests)
>>
>> --
>> Gabriel Genellina
>
> Gabriel, thanks for the input. So are you saying there is no way to
> realistically *prevent* the timeout from occurring in the first

Exactly. The error is out of your control: maybe the server is down,  
irresponsive, overloaded, a proxy has any problems, any network problem,  
etc.

> place?  And by timing out early, do you mean to set the timeout for x
> seconds and if and when the timeout occurs, handle the error and start
> the process again somehow on the pending requests?  Thanks.

Exactly!
Another option: Python is cool, but there is no need to reinvent the  
wheel. Use wget instead :)

-- 
Gabriel Genellina

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


Re: Please help!! SAXParseException: not well-formed (invalid token)

2007-03-27 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> I checked the file format (of the file containing the n-tilde - ñ) and
> it is indeed UTF-8! I'm baffled! Any ideas?

Without you showing us your actual code and data - no. Because it works 
for me and a lot of other people.


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


PyPy 1.0: JIT compilers for free and more

2007-03-27 Thread Carl Friedrich Bolz
==
PyPy 1.0: JIT compilers for free and more
==

Welcome to the PyPy 1.0 release - a milestone integrating the results
of four years of research, engineering, management and sprinting
efforts, concluding the 28 months phase of EU co-funding!

Although still not mature enough for general use, PyPy 1.0 materializes
for the first time the full extent of our original vision:

- A flexible Python interpreter, written in "RPython":

   - Mostly unaware of threading, memory and lower-level target platform
 aspects.
   - Showcasing advanced interpreter features and prototypes.
   - Passing core CPython regression tests, translatable to C, LLVM and 
.NET.

- An advanced framework to translate such interpreters and programs:

   - That performs whole type-inference on RPython programs.
   - Can weave in threading, memory and target platform aspects.
   - Has low level (C, LLVM) and high level (CLI, Java, JavaScript) 
backends.

- A **Just-In-Time Compiler generator** able to **automatically**
   enhance the low level versions of our Python interpreter, leading to
   run-time machine code that runs algorithmic examples at speeds typical
   of JITs!

Previous releases, particularly the 0.99.0 release from February,
already highlighted features of our Python implementation and the
abilities of our translation approach but the **new JIT generator**
clearly marks a major research result and gives weight to our vision
that one can generate efficient interpreter implementations, starting
from a description in a high level language.

We have prepared several entry points to help you get started:

* The main entry point for JIT documentation and status:

http://codespeak.net/pypy/dist/pypy/doc/jit.html

* The main documentation and getting-started PyPy entry point:

http://codespeak.net/pypy/dist/pypy/doc/index.html

* Our online "play1" demos showcasing various Python interpreters,
   features (and a new way to program AJAX applications):

http://play1.codespeak.net/

* Our detailed and in-depth Reports about various aspects of the
   project:

http://codespeak.net/pypy/dist/pypy/doc/index-report.html

In the next few months we are going to discuss the goals and form of
the next stage of development - now more than ever depending on your
feedback and contributions - and we hope you appreciate PyPy 1.0 as an
interesting basis for greater things to come, as much as we do
ourselves!

have fun,

 the PyPy release team,
 Samuele Pedroni, Armin Rigo, Holger Krekel, Michael Hudson,
 Carl Friedrich Bolz, Antonio Cuni, Anders Chrigstroem, Guido Wesdorp
 Maciej Fijalkowski, Alexandre Fayolle

 and many others:
 http://codespeak.net/pypy/dist/pypy/doc/contributor.html


What is PyPy?


Technically, PyPy is both a Python interpreter implementation and an
advanced compiler, or more precisely a framework for implementing dynamic
languages and generating virtual machines for them.

The framework allows for alternative frontends and for alternative
backends, currently C, LLVM and .NET.  For our main target "C", we can
can "mix in" different garbage collectors and threading models,
including micro-threads aka "Stackless".  The inherent complexity that
arises from this ambitious approach is mostly kept away from the Python
interpreter implementation, our main frontend.

PyPy is now also a Just-In-Time compiler generator.  The translation
framework contains the now-integrated JIT generation technology.  This
depends only on a few hints added to the interpreter source and should
be able to cope with the changes to the interpreter and be generally
applicable to other interpreters written using the framework.

Socially, PyPy is a collaborative effort of many individuals working
together in a distributed and sprint-driven way since 2003.  PyPy would
not have gotten as far as it has without the coding, feedback and
general support from numerous people.

Formally, many of the current developers were involved in executing an
EU contract with the goal of exploring and researching new approaches
to language and compiler development and software engineering.  This
contract's duration is about to end this month (March 2007) and we are
working and preparing the according final review which is scheduled
for May 2007.

For the future, we are in the process of setting up structures to help
maintain conceptual integrity of the project and to discuss and deal
with funding opportunities related to further PyPy sprinting and
developments. See here for results of the discussion so far:

 http://codespeak.net/pipermail/pypy-dev/2007q1/003577.html


1.0.0 Feature highlights
==


Here is a summary list of key features included in PyPy 1.0:

- The Just-In-Time compiler generator, now capable of generating the
   first JIT compiler versions of our Python interpreter:

http://cod

Re: socket read timeout

2007-03-27 Thread hg
Steve Holden wrote:

> Jarek Zgoda wrote:
>> hg napisa?(a):
>> 
>>> I am looking for the most efficient / cleanest way to implement a socket
>>> read with timeout (Windows mainly but would be great if the same code
>>> worked under *nix)
>> 
>> Did you see http://www.timo-tasi.org/python/timeoutsocket.py ?
>> 
> Note that since 2.4, I believe, sockets in the standard library allow
> you to specify a timeout parameter.
> 
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb http://del.icio.us/steve.holden
> Recent Ramblings   http://holdenweb.blogspot.com

Hi and thanks to all.

Do you mean use select ?

Thanks,

hg

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


Re: pattern search

2007-03-27 Thread Diez B. Roggisch
Paul McGuire schrieb:
> On Mar 27, 10:18 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> Fabian Braennstroem wrote:
>>> Hi,
>>> I wrote a small gtk file manager, which works pretty well. Until
>>> now, I am able to select different file (treeview entries) just by
>>> extension (done with 'endswith'). See the little part below:
>>> self.pathlist1=[ ]
>>> self.patternlist=[ ]
>>> while iter:
>>> #print iter
>>> value = model.get_value(iter, 1)
>>> #if value is what I'm looking for:
>>> if value.endswith("."+ pattern):
>>> selection.select_iter(iter)
>>> selection.select_path(n)
>>> self.pathlist1.append(n)
>>> self.patternlist.append(value)
>>> iter = model.iter_next(iter)
>>> #print value
>>> n=n+1
>>> Now, I would like to improve it by searching for different 'real'
>>> patterns just like using 'ls' in bash. E.g. the entry
>>> 'car*.pdf' should select all pdf files with a beginning 'car'.
>>> Does anyone have an idea, how to do it?
>> Use regular expressions. They are part of the module "re". And if you use
>> them, ditch your code above, and make it just search for a pattern all the
>> time. Because the above is just the case of
>>
>> *.ext
>>
>> Diez- Hide quoted text -
>>
>> - Show quoted text -
> 
> The glob module is a more direct tool based on the OP's example.  The
> example he gives works directly with glob.  To use re, you'd have to
> convert to something like "car.*\.pdf", yes?
> 
> (Of course, re offers much more power than simple globbing.  Not clear
> how much more the OP was looking for.)

I'm aware of the glob-module. But it only works on files. I was under 
the impression that he already has a list of files he wants to filter 
instead of getting it fresh from the filesystem.

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


Re: plot dendrogram with python

2007-03-27 Thread Jon
> does anyone know if there is a way to plot a dendrogram with python.
> Pylab or matplotlib do not provide such a function.

This makes a datafile for gnuplot using output from pycluster. I'd be
interested to see something like this added to pylab/matplotlib,
although I don't have time myself. Not very elegant, but someone can
probably transform it to the three line recursion which escapes me.

Best,

Jon


import Numeric
from Pycluster import treecluster
dist = Numeric.zeros((10,10),Numeric.Float)
for i in range(dist.shape[0]):
   dist[i:,i:]=i

tree , dist = treecluster(distancematrix=dist,method='a')


tree=tree.tolist()
base = []
line = []
names = range(dist.shape[0]+1)

def f(i,tree,names,spos):
   height=dist[spos]
   if i>=0:
  try:
 base.append(names[i])
  except:
 print i
  x=len(base)
  line.append((x,0))
  line.append((x,height))
  line.append(("#","#"))
   else:
  cluster = tree[-i-1]
  h1,x1=f(cluster[0],tree,names,-i-1)
  h2,x2=f(cluster[1],tree,names,-i-1)
  x=(x1+x2)/2.0
  if h1==h2:
 # tie
 line.append((x1,h1))
 line.append((x2,h2))
 line.append(("#","#"))
 line.append((x,height))
 line.append((x,h1))
 line.append(("#","#"))
  else:
 raise Exception("Whoops")
  tree[-i-1].append((x,h1))
   return height,x


h1,x1 = f(tree[-1][0],tree,names,len(tree)-1)
h2,x2 = f(tree[-1][1],tree,names,len(tree)-1)
x=(x1+x2)/2.0
height = dist[-1]
tree[-1].append((x,h1))
if h1==h2:
 # tie
 line.append((x1,h1))
 line.append((x2,h2))
 line.append(("#","#"))
 line.append((x,height))
 line.append((x,h1))
 line.append(("#","#"))
else:
 raise Exception("Whoops")

# print base

d=open("dend.dat","w")
# make a tree diagram
for point in line:
   if point[0]!="#":
  print >> d, point[0],point[1]
   else:
  print >> d
  print >> d

d.close()

#
# os.system("gnuplot")
# """plot "dend.dat" u 1:2 w l"""


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


Re: Auto execute python in USB flash disk

2007-03-27 Thread José Antonio Salazar Montenegro




I suspect he wants to do this just for the kicks.

Just for completion, Truecrypt
does precisely what you need. It has to be installed, but you could
carry the installer unencrypted in the same USB drive.


Larry Bates wrote:

  Brian Erhard wrote:
  
  
I am still fairly new to python and wanted to attempt a home made
password protection program.  There are files that I carry on a USB
flash drive that I would like to password protect.  Essentially, I
would like to password protect an entire directory of files.  Is there
a way to auto execute a python script after a user double clicks to
open a folder on the USB drive? How can you capture that double click
event on a specific folder?

Thanks.


  
  Unless you are just doing this to learn, I would suggest you purchase
USB key with encryption included.  They are REALLY cheap.

http://www.kingston.com/flash/DataTravelers_enterprise.asp

-Larry
  



NOTA: La informacion de este correo es de propiedad exclusiva y confidencial. Este mensaje es solo para el destinatario indicado, si usted no lo es, destruyalo de inmediato. Ninguna informacion aqui contenida debe ser entendida como dada o avalada por MADISA, sus subsidiarias o sus empleados, salvo cuando ello expresamente se indique. Es responsabilidad de quien recibe este correo de asegurarse que este libre de virus, por lo tanto ni MADISA, sus subsidiarias ni sus empleados aceptan responsabilidad alguna.
NOTE: The information in this email is proprietary and confidential. This message is for the designated recipient only, if you are not the intended recipient, you should destroy it immediately. Any information in this message shall not be understood as given or endorsed by MADISA, its subsidiaries or their employees, unless expressly so stated. It is the responsibility of the recipient to ensure that this email is virus free, therefore neither MADISA, its subsidiaries nor their employees accept any responsibility.
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Auto execute python in USB flash disk

2007-03-27 Thread Larry Bates
Brian Erhard wrote:
> I am still fairly new to python and wanted to attempt a home made
> password protection program.  There are files that I carry on a USB
> flash drive that I would like to password protect.  Essentially, I
> would like to password protect an entire directory of files.  Is there
> a way to auto execute a python script after a user double clicks to
> open a folder on the USB drive? How can you capture that double click
> event on a specific folder?
> 
> Thanks.
> 
Unless you are just doing this to learn, I would suggest you purchase
USB key with encryption included.  They are REALLY cheap.

http://www.kingston.com/flash/DataTravelers_enterprise.asp

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


plotting R graphics with rpy: figure crashes

2007-03-27 Thread Frank
Hi,

I use rpy to plot functions and have the following problem. When I
execute the following code line by line (start python and then execute
line by line) the resulting figure looks as it should. However, when I
put these lines in a script and execute the script the figure appears
for half a second but then crashes. Using pylab.show() at the end of
the script prevents the crash but now the window is no longer
refreshed (e.g., changing the size of the window makes the contents
disappear).

import pylab
import rpy

x = range(0, 10)
y = [ 2*i for i in x ]
rpy.r.plot(x,y)

I compared already with sys.version if the python version is the same
in both cases (it is).  Hence, the problem might be caused by rpy.

Has anyone an idea how to figure that out?

Thanks!

Frank

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


Re: Auto execute python in USB flash disk

2007-03-27 Thread Shane Geiger



Is there
a way to auto execute a python script after a user double clicks to
open a folder on the USB drive? How can you capture that double click
event on a specific folder?



That would depend on what desktop / Operating System you're
using. If it's Windows, you need a shell extension (which
is non-trivial to understand and write). If it's one of the
Linux desktops, someone else had better chip in!
  


http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_15.shtml#e390


--


There is a new version of `Movable Python
`_
available.

This is available for **Movable Python** for Python 2.2.3, 2.3.5, 2.4.3
and 2.5rc2 from :

   `The Movable Python Groups Page
`_



What is Movable Python
==

Movable Python is a portable distribution of Python for windows,
designed to be run off a USB stick or computers that don't have Python
installed. It features an IDE (Pythonwin and IDLE are included - but
you can also use SPE), and a GUI launcher.

It can be configured to use multiple interpreters from a single
interface, including acting as a GUI for any executable.

It has a host of other features (like logging all output from files,
enabling psyco for all scripts, etc).

See the following link for a list of all the new features in Movable
Python 2.0.0 :


http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_15.shtml#e390

For an overview of the most important features (with screenshots) see :


http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_22.shtml#e396

Other uses for Movable Python include testing programs with different
versions of Python, and providing clean install 'sandboxes' for testing
programs. It is also an ideal launcher for IronPython.




--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: How can I catch all exception in python?

2007-03-27 Thread Jeff McNeil

You could also use sys.excepthook if you're trying to handle uncaught
exceptions.



On 27 Mar 2007 11:45:54 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


On Mar 27, 9:15 pm, [EMAIL PROTECTED] wrote:
> Technically speaking, you can catch all errors as follows:
>
> try:
># do something
> except Exception, e:
>print e

That won't catch exceptions/errors that don't derive from
Exception class. For example a string won't be caught:

try:
   raise "foo"
except Exception, e:
   print e

But this will catch all exceptions:

try:
   raise "foo"
except:
   print sys.exc_info()

(there may be other ways I don't know of)

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

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

Re: urllib timeout issues

2007-03-27 Thread supercooper
On Mar 27, 3:13 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Tue, 27 Mar 2007 16:21:55 -0300, supercooper <[EMAIL PROTECTED]>
> escribió:
>
> > I am downloading images using the script below. Sometimes it will go
> > for 10 mins, sometimes 2 hours before timing out with the following
> > error:
>
> > urllib.urlretrieve(fullurl, localfile)
> > IOError: [Errno socket error] (10060, 'Operation timed out')
>
> > I have searched this forum extensively and tried to avoid timing out,
> > but to no avail. Anyone have any ideas as to why I keep getting a
> > timeout? I thought setting the socket timeout did it, but it didnt.
>
> You should do the opposite: timing out *early* -not waiting 2 hours- and
> handling the error (maybe using a queue to hold pending requests)
>
> --
> Gabriel Genellina

Gabriel, thanks for the input. So are you saying there is no way to
realistically *prevent* the timeout from occurring in the first
place?  And by timing out early, do you mean to set the timeout for x
seconds and if and when the timeout occurs, handle the error and start
the process again somehow on the pending requests?  Thanks.

chad

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


Re: Extending a class on runtime

2007-03-27 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Hi,
> 
> Let's say you have a bunch of instatiated objects of the same class on
> your hands and you want to had some functionality to them.

Then I'd just do it.

> I'm facing this situation while working with PyGTK and libglade to
> create a GUI. Libglade creates a whole object tree representing the
> GUI out of an XML file, and a bunch of GtkComboBox objects are
> instantiated. I don't like the way GtkComboBox objects works, so I'd
> like them to have some extra methods. Inheriting and extending
> GtkComboBox is pointless because I'm not the one instantiating the
> class. I only came up with three possibilities:
> 
> A) Adding my methods to the objects in a for-loop
> 
> B) Adding my methods to the GtkComboBox class (I tried this and it
> seems to work)

I don't have much experience with PyGTK, but unless GtkComboBox is a 
very special class object, it should JustWork(tm).

> C) Create a GtkComboBoxExtended class inheriting from GtkComboBox
> and change the instances' class in a for-loop.

That's another possible solution, but it requires more work.

> I'm kind of inclined to C. B sounds dangerous

Why ? Eventually confusing if not well documented, but mostly harmless 
IMHO. Python is dynamic by nature, and there's no reason to not take 
advantage of this fact.

> and A is plain ugly.

It's also the more complicated and less efficient solution IMHO (unless 
you want different implementations of the same method on a per-instance 
basis...).

> I'm very new to this and I'm sure there is a well-established pythonic
> way to solve this problem, so I'm appealing for  your vast collective
> wisdom to point me in the path of righteousness.

As far as I'm concerned, and if it's just a matter of adding a couple of 
methods, I'd go for B, which is the SimplestThingToDo(tm).

Now if it's a big complicated project with a rather unstable team, C is 
perhaps a bit more explicit since it makes obvious that this not a 
pristine GtkComboBox no more. But even then, it's always possible to 
monkeypatch a class in a more or less documented way (explict mentions 
of the patch in added/replaced/extended methods and in __repr__()).

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib timeout issues

2007-03-27 Thread Gabriel Genellina
En Tue, 27 Mar 2007 16:21:55 -0300, supercooper <[EMAIL PROTECTED]>  
escribió:

> I am downloading images using the script below. Sometimes it will go
> for 10 mins, sometimes 2 hours before timing out with the following
> error:
>
> urllib.urlretrieve(fullurl, localfile)
> IOError: [Errno socket error] (10060, 'Operation timed out')
>
> I have searched this forum extensively and tried to avoid timing out,
> but to no avail. Anyone have any ideas as to why I keep getting a
> timeout? I thought setting the socket timeout did it, but it didnt.

You should do the opposite: timing out *early* -not waiting 2 hours- and  
handling the error (maybe using a queue to hold pending requests)

-- 
Gabriel Genellina

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


rpy: parsing arrays from python to R

2007-03-27 Thread Frank

Hi,

I use rpy on linux to call R functions. Works fine up to the following
problem: How to parse arrays (no vectors, that means 2-dimensional) to
R without much effort?

The following code solves the problem (in two different ways).
However, it seems to me that there might be a way to do it more
efficiently.

rpy.r.assign("N", N)
rpy.r("A2 <- array(1:N^2, dim=c(N,N))")
rpy.r("A3 <- array(1:N^2, dim=c(N,N))")


for i in range(N):   # two alternative ways to parse
arrays
rpy.r.assign("Wi", W[i])
rpy.r.assign("i", i+1)
rpy.r("""for( j in 1:N ){
A2[i,j] <- Wi[j]}""")
for k in range(N):
rpy.r.assign("k", k+1)
rpy.r("A3[i,k] <- Wi[k]")


print rpy.r("A3")
print rpy.r("A2")


As I see it, the problem is, that the 'assign' command works only
either for scalars or vectors (one-dimensional arrays but not more-
dimensional arrays). I tried it for 2-dimensional arrays and the
result is a list whose components are vectors. Again, this is easy to
convert to a two-dimensional array but the point here is that one has
to do it.

Maybe there are people using R with python who have some more
experience. I would be interested how they solved this problem.

Thanks!

Frank

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


Re: PDB does not allow jumping to first statement?

2007-03-27 Thread Chris Lasher
On Mar 27, 5:59 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> I tried on GNU/Linux and Python versions 2.4 and 2.5 and get the same
> behavior. Best as I can tell, it looks like a bug in Python. pdb,
> pydb, rpdb2 all handle the "jump" command by changing the frame
> f_lineno value. When the corresponding code pointer has offset 0 (or
> equivalently and more simlply as you put it, is the first statement)
> this doesn't seem to work properly. But this also implies that all you
> need to do is add something as the first statement. A docstring
> comment, e.g.
> "this is what my program does..."
> comes to mind :-)

I started implementing this, but it's a hack. Looks like it's time for
me to file a bug report!

> Lastly, I'll mention that I what most folks want to do is not jump to
> the beginning of the program but rather *restart* it. The difference
> here as applied to your example is seen in the way variables (e.g. a,
> b, and c) are handled. In a "restart", those names would go back to
> being undefined and referring to them before assigning to them would
> cause a NameError exception. With "jump", they retain their existing
> values.

In the case I was working with, I really did want to "jump" and retain
the values, rather than restart and clear those values.

Just as an aside, Rocky, I really like your ShowMeDo on pydb. Thanks
for making that. (For those who haven't seen it, check out the
"Introducing the pydb Debugger" at )

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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Mark Morss
wrote:

> Well, the discussion was about Python vs. Fortran, and Pyrex, as I
> understand it, is a tool for linking C to Python.

I think it's more than that.  It's more a subset of Python with a little
static typing.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


urllib timeout issues

2007-03-27 Thread supercooper
I am downloading images using the script below. Sometimes it will go
for 10 mins, sometimes 2 hours before timing out with the following
error:

Traceback (most recent call last):
  File "ftp_20070326_Downloads_cooperc_FetchLibreMapProjectDRGs.py",
line 108, i
n ?
urllib.urlretrieve(fullurl, localfile)
  File "C:\Python24\lib\urllib.py", line 89, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
  File "C:\Python24\lib\urllib.py", line 222, in retrieve
fp = self.open(url, data)
  File "C:\Python24\lib\urllib.py", line 190, in open
return getattr(self, name)(url)
  File "C:\Python24\lib\urllib.py", line 322, in open_http
return self.http_error(url, fp, errcode, errmsg, headers)
  File "C:\Python24\lib\urllib.py", line 335, in http_error
result = method(url, fp, errcode, errmsg, headers)
  File "C:\Python24\lib\urllib.py", line 593, in http_error_302
data)
  File "C:\Python24\lib\urllib.py", line 608, in redirect_internal
return self.open(newurl)
  File "C:\Python24\lib\urllib.py", line 190, in open
return getattr(self, name)(url)
  File "C:\Python24\lib\urllib.py", line 313, in open_http
h.endheaders()
  File "C:\Python24\lib\httplib.py", line 798, in endheaders
self._send_output()
  File "C:\Python24\lib\httplib.py", line 679, in _send_output
self.send(msg)
  File "C:\Python24\lib\httplib.py", line 646, in send
self.connect()
  File "C:\Python24\lib\httplib.py", line 630, in connect
raise socket.error, msg
IOError: [Errno socket error] (10060, 'Operation timed out')


I have searched this forum extensively and tried to avoid timing out,
but to no avail. Anyone have any ideas as to why I keep getting a
timeout? I thought setting the socket timeout did it, but it didnt.

Thanks.

<--- CODE --->

images = [['34095e3','Clayton'],
['35096d2','Clearview'],
['34095d1','Clebit'],
['34095c3','Cloudy'],
['34096e2','Coalgate'],
['34096e1','Coalgate SE'],
['35095g7','Concharty Mountain'],
['34096d6','Connerville'],
['34096d5','Connerville NE'],
['34096c5','Connerville SE'],
['35094f8','Cookson'],
['35095e6','Council Hill'],
['34095f5','Counts'],
['35095h6','Coweta'],
['35097h2','Coyle'],
['35096c4','Cromwell'],
['35095a6','Crowder'],
['35096h7','Cushing']]

exts = ['tif', 'tfw']
envir = 'DEV'
# URL of our image(s) to grab
url = 'http://www.archive.org/download/'
logRoot = '//fayfiler/seecoapps/Geology/GEOREFRENCED IMAGES/TOPO/
Oklahoma UTMz14meters NAD27/'
logFile = os.path.join(logRoot, 'FetchLibreDRGs_' + strftime('%m_%d_%Y_
%H_%M_%S', localtime()) + '_' + envir + '.log')

# Local dir to store files in
fetchdir = logRoot
# Entire process start time
start = time.clock()

msg = envir + ' - ' + "Script: " + os.path.join(sys.path[0],
sys.argv[0]) + ' - Start time: ' + strftime('%m/%d/%Y %I:%M:%S %p',
localtime()) + \
 
'\n--
\n\n'
AddPrintMessage(msg)
StartFinishMessage('Start')

# Loop thru image list, grab each tif and tfw
for image in images:
# Try and set socket timeout default to none
# Create a new socket connection for every time through list loop
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('archive.org', 80))
s.settimeout(None)

s2 = time.clock()
msg = '\nProcessing ' + image[0] + ' --> ' + image[1]
AddPrintMessage(msg)
print msg
for ext in exts:
fullurl = url + 'usgs_drg_ok_' + image[0][:5] + '_' + image[0]
[5:] + '/o' + image[0] + '.' + ext
localfile = fetchdir + image[0] + '_' +
string.replace(image[1], ' ', '_') + '.' + ext
urllib.urlretrieve(fullurl, localfile)
e2 = time.clock()
msg = '\nDone processing ' + image[0] + ' --> ' + image[1] +
'\nProcess took ' + Timer(s2, e2)
AddPrintMessage(msg)
print msg
# Close socket connection, only to reopen with next run thru loop
s.close()

end = time.clock()
StartFinishMessage('Finish')
msg = '\n\nDone! Process completed in ' + Timer(start, end)
AddPrintMessage(msg)

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


Re: 16bit RGB with Image module

2007-03-27 Thread Will McGugan
Jason B wrote:
> Well I kept screwing around and funny thing, this works:
> 
> import sys, Image
> 
> if len(sys.argv) ==  2:
>   print "\nReading: "+sys.argv[1]
>   image_file = open(sys.argv[1], "rb")
>   pixel_data = image_file.read()
> 
> im = Image.fromstring("RGB", (326, 325), pixel_data, "raw", "BGR;16")
> im.show()
> 
> Although I have no idea *why* it works, other than the fact that I'm now 
> using the correct number of bits per pixel.  :)
> 
> Anyone have thoughts on this?

Well RGB will will use 24 bits per pixel, not 16, so the first error you 
got makes sense. I guess using the raw decoder with "BGR;16" makes it 
use 16 bit. Although, I couldn't find any reference in the docs!

I'm sure Fredrik Lundh could shed some light on this...

Will McGugan
--
blog: http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pattern search

2007-03-27 Thread Paul McGuire
On Mar 27, 3:13 pm, Fabian Braennstroem <[EMAIL PROTECTED]> wrote:
> Hi to all,
>
> Wojciech Mu?a schrieb am 03/27/2007 03:34 PM:
>
> > Fabian Braennstroem wrote:
> >> Now, I would like to improve it by searching for different 'real'
> >> patterns just like using 'ls' in bash. E.g. the entry
> >> 'car*.pdf' should select all pdf files with a beginning 'car'.
> >> Does anyone have an idea, how to do it?
>
> > Use module glob.
>
> Thanks for your help! glob works pretty good, except that I just
> deleted all my lastet pdf files :-(
>
> Greetings!
> Fabian

Then I shudder to think what might have happened if you had used
re's! :)

-- Paul

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


Re: pattern search

2007-03-27 Thread Paul McGuire
On Mar 27, 10:18 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Fabian Braennstroem wrote:
> > Hi,
>
> > I wrote a small gtk file manager, which works pretty well. Until
> > now, I am able to select different file (treeview entries) just by
> > extension (done with 'endswith'). See the little part below:
>
> > self.pathlist1=[ ]
> > self.patternlist=[ ]
> > while iter:
> > #print iter
> > value = model.get_value(iter, 1)
> > #if value is what I'm looking for:
> > if value.endswith("."+ pattern):
> > selection.select_iter(iter)
> > selection.select_path(n)
> > self.pathlist1.append(n)
> > self.patternlist.append(value)
> > iter = model.iter_next(iter)
> > #print value
> > n=n+1
>
> > Now, I would like to improve it by searching for different 'real'
> > patterns just like using 'ls' in bash. E.g. the entry
> > 'car*.pdf' should select all pdf files with a beginning 'car'.
> > Does anyone have an idea, how to do it?
>
> Use regular expressions. They are part of the module "re". And if you use
> them, ditch your code above, and make it just search for a pattern all the
> time. Because the above is just the case of
>
> *.ext
>
> Diez- Hide quoted text -
>
> - Show quoted text -

The glob module is a more direct tool based on the OP's example.  The
example he gives works directly with glob.  To use re, you'd have to
convert to something like "car.*\.pdf", yes?

(Of course, re offers much more power than simple globbing.  Not clear
how much more the OP was looking for.)

-- Paul

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


Extending a class on runtime

2007-03-27 Thread rdaunoravicius
Hi,

Let's say you have a bunch of instatiated objects of the same class on
your hands and you want to had some functionality to them.

I'm facing this situation while working with PyGTK and libglade to
create a GUI. Libglade creates a whole object tree representing the
GUI out of an XML file, and a bunch of GtkComboBox objects are
instantiated. I don't like the way GtkComboBox objects works, so I'd
like them to have some extra methods. Inheriting and extending
GtkComboBox is pointless because I'm not the one instantiating the
class. I only came up with three possibilities:

A) Adding my methods to the objects in a for-loop

B) Adding my methods to the GtkComboBox class (I tried this and it
seems to work)

C) Create a GtkComboBoxExtended class inheriting from GtkComboBox
and change the instances' class in a for-loop.

I'm kind of inclined to C. B sounds dangerous and A is plain ugly.
I'm very new to this and I'm sure there is a well-established pythonic
way to solve this problem, so I'm appealing for  your vast collective
wisdom to point me in the path of righteousness.

Thanks,
Rodrigo

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


Re: Numeric Soup

2007-03-27 Thread Erik Johnson

"Robert Kern" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> http://www.scipy.org/History_of_SciPy
>
> numpy is the current array package and supercedes Numeric and numarray.
scipy
> provides a bunch of computational routines (linear algebra, optimization,
> statistics, signal processing, etc.) built on top of numpy.

Thank you.


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


Re: How can I catch all exception in python?

2007-03-27 Thread irstas
On Mar 27, 9:15 pm, [EMAIL PROTECTED] wrote:
> Technically speaking, you can catch all errors as follows:
>
> try:
># do something
> except Exception, e:
>print e

That won't catch exceptions/errors that don't derive from
Exception class. For example a string won't be caught:

try:
   raise "foo"
except Exception, e:
   print e

But this will catch all exceptions:

try:
   raise "foo"
except:
   print sys.exc_info()

(there may be other ways I don't know of)

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


Re: Help in Placing Object in Memory

2007-03-27 Thread Harry George
"Clement" <[EMAIL PROTECTED]> writes:

> I am newbie to Python.. i want to know something..
> 
> can i place an object in disk instead of placing in Main Memory...?
> 
> If possible, can you please explain with some scripts...?
> 
> can two python script share a common object?
> 

For the CPU to use the object, it needs to be in RAM.  But it is
possible to save the RAM image onto disk, and then bring it back
later.  The common approach is called "pickling", though there are
several variants on this:

 http://docs.python.org/lib/persistence.html


-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 16bit RGB with Image module

2007-03-27 Thread Jason B
Well I kept screwing around and funny thing, this works:

import sys, Image

if len(sys.argv) ==  2:
  print "\nReading: "+sys.argv[1]
  image_file = open(sys.argv[1], "rb")
  pixel_data = image_file.read()

im = Image.fromstring("RGB", (326, 325), pixel_data, "raw", "BGR;16")
im.show()

Although I have no idea *why* it works, other than the fact that I'm now 
using the correct number of bits per pixel.  :)

Anyone have thoughts on this?

Thanks!
J


"Jason B" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi all,
>
> I'm still new to all of this, but I'm trying to do something here that 
> *seems* like it should be pretty simple.  All I want to do is take an 
> array of pixel data from a file (no header data or anything, just pixel 
> data) in RGB565 format and save it off to a bitmap file - or display it, 
> in the case below:
>
> import sys, Image
>
> if len(sys.argv) ==  2:
>  print "\nReading: "+sys.argv[1]
>  image_file = open(sys.argv[1], "rb")
>  pixel_data = image_file.read()
>
> im = Image.fromstring("RGB", (326, 325), pixel_data)
> im.show()
>
> When run, I get:
>
> ValueError: not enough image data
>
> Which I'm pretty sure is because it's expecting a 24bit image.  Of course 
> if I tune down the width and height or change the format to B&W ("L") then 
> it *does* display an image, the B&W one even having recognizable features, 
> just not the right one.  :(
>
> I've read through the documentation a thousand times trying to understand 
> the raw decoder and plugins, etc. but I still can't figure this out...
>
> Any help is greatly appreciated!
>
> Thanks,
> J
> 


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


Re: How can I catch all exception in python?

2007-03-27 Thread Gabriel Genellina
En Tue, 27 Mar 2007 15:09:18 -0300, [EMAIL PROTECTED] <[EMAIL PROTECTED]>  
escribió:

> I read the document here about exception handling in python:
>
> http://www.diveintopython.org/file_handling/index.html
>
> Can you please tell me how can I catch all exception in python?
> like this in Java:
> try {
>  
> } catch (Throwable t) {
>  ...
> }

See the Further Reading section on that same page.
Exceptions are covered in the Python Tutorial here:  
http://docs.python.org/tut/node10.html

-- 
Gabriel Genellina

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


16bit RGB with Image module

2007-03-27 Thread Jason B
Hi all,

I'm still new to all of this, but I'm trying to do something here that 
*seems* like it should be pretty simple.  All I want to do is take an array 
of pixel data from a file (no header data or anything, just pixel data) in 
RGB565 format and save it off to a bitmap file - or display it, in the case 
below:

import sys, Image

if len(sys.argv) ==  2:
  print "\nReading: "+sys.argv[1]
  image_file = open(sys.argv[1], "rb")
  pixel_data = image_file.read()

im = Image.fromstring("RGB", (326, 325), pixel_data)
im.show()

When run, I get:

ValueError: not enough image data

Which I'm pretty sure is because it's expecting a 24bit image.  Of course if 
I tune down the width and height or change the format to B&W ("L") then it 
*does* display an image, the B&W one even having recognizable features, just 
not the right one.  :(

I've read through the documentation a thousand times trying to understand 
the raw decoder and plugins, etc. but I still can't figure this out...

Any help is greatly appreciated!

Thanks,
J 


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


Re: How can I catch all exception in python?

2007-03-27 Thread kyosohma
On Mar 27, 1:09 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> I read the document here about exception handling in python:
>
> http://www.diveintopython.org/file_handling/index.html
>
> Can you please tell me how can I catch all exception in python?
> like this in Java:
> try {
>  
>
> } catch (Throwable t) {
>  ...
> }

Technically speaking, you can catch all errors as follows:

try:
   # do something
except Exception, e:
   print e


However, this is NOT the recommended way of handling errors. Typically
you catch only expected errors, such as when you open a file, you
check for an IOError. By catching all errors, you will learn less and
likely have hard-to-understand bugs in your program.

Mike

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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Erik Johnson

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> Sheesh. Do Java developers go around telling everybody that Java is an
> interpreted language? I don't think so.
>
> What do you think the "c" in ".pyc" files stands for? "Cheese"?

On the contrary... Sun is very careful to make sure you understand that Java
is *COMPILED*!
Remember, remember, always remember: Java is COMPILED! See that: the java
"compiler": javac.  You have to call it explicitly when you build your Java
software so that it compiles Java source code (that way Java executes really
fast)!! (And don't forget, Java source is *compiled*, just like C++.)

What's a JVM? Why would you need one since Java is *compiled*, remember?

But seriously... I'm not a language or architecture guru.  Is there any
real difference between a JVM and an interpreter? I mean, I have some
general feel that bytecode is a lower-level, more direct and more efficient
thing to be interpreting that Java or Python source, but at the bottom
level, you are still running an interpreter which is going to be
(significantly?) more inefficient than executing native machine instructions
directly on the CPU, right?

Why is Python able to automatically compile source into bytecode on the
fly (when needed) but Java still forces you to do so explicitly?

I don't mean to bash Java - I think it has it's place as well, but I
mean to note that Java is very carefully marketed whereas Python's image is
not managed by a major, international corporation.


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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Mark Morss
On Mar 27, 12:55 pm, Jaap Spies <[EMAIL PROTECTED]> wrote:
> Mark Morss wrote:
>
> > Maybe somebody reading this will be able to convince me to look again
> > at Numpy/Scipy, but for the time being I will continue to do my
> > serious numerical computation in Fortran.
>
> What I am missing in this discussion is a link to Pyrex to speed up
> Python: Pyrex is almost Python with the speed of compiled 
> C.http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/
>
> Pyrex is adapted in SAGE (Software for Algebra and Geometry
> Experimentation) as Sagex:http://modular.math.washington.edu/sage/
>
> Jaap

Well, the discussion was about Python vs. Fortran, and Pyrex, as I
understand it, is a tool for linking C to Python.  So I am not sure of
the relevance of Pyrex to this particular discussion.  F2PY is the
leading tool for linking Fortran to Python, and I did mention that.

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


Re: pattern search

2007-03-27 Thread Fabian Braennstroem
Hi to all,

Wojciech Mu?a schrieb am 03/27/2007 03:34 PM:
> Fabian Braennstroem wrote:
>> Now, I would like to improve it by searching for different 'real'
>> patterns just like using 'ls' in bash. E.g. the entry
>> 'car*.pdf' should select all pdf files with a beginning 'car'.
>> Does anyone have an idea, how to do it?
> 
> Use module glob.

Thanks for your help! glob works pretty good, except that I just
deleted all my lastet pdf files :-(

Greetings!
Fabian

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


How can I catch all exception in python?

2007-03-27 Thread [EMAIL PROTECTED]
I read the document here about exception handling in python:

http://www.diveintopython.org/file_handling/index.html

Can you please tell me how can I catch all exception in python?
like this in Java:
try {
 
} catch (Throwable t) {
 ...
}

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


Re: Help in Placing Object in Memory

2007-03-27 Thread [EMAIL PROTECTED]
On Mar 27, 10:33 am, "Clement" <[EMAIL PROTECTED]> wrote:
> I am newbie to Python.. i want to know something..
>
> can i place an object in disk instead of placing in Main Memory...?
>
> If possible, can you please explain with some scripts...?
>
> can two python script share a common object?


POSH allows shared objects, but it's not built-in.  
http://poshmodule.sourceforge.net/

If you're only looking for persistence (and not sharing), there's the
(standard) shelve module.  http://docs.python.org/lib/module-shelve.html
If your need to share objects is fairly minimal and not performance-
sensitive, you might be able to get by with shelves, sync, and file
locking or some other locking.

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


Handling exception thrown by Boost.Python c-extension in Python code

2007-03-27 Thread MarkE
I'm just getting started on Boost Python and may have missed this
obvious looking problem somewhere.

Given a c-extension "testext" written using Boost Python containing a
base class "Base", a derived class "Derived", and a function
"doSomething" which expects a "Derived" parameter, if I pass it a
"Base" parameter an exception is thrown. This is a
Boost.Python.ArgumentError. My question is how do I catch this error ?

I tried the following bit of investigation:
#Start code
import testext
b = testext.Base()
try:
   testext.doSomething(b)
except Exception, e:
pass
help(e.__class__)
#End code

which produces
#Start output
Help on class ArgumentError:

class ArgumentError(exceptions.TypeError)
 |  Method resolution order:
 |  ArgumentError
 |  exceptions.TypeError
 |  exceptions.StandardError
 |  exceptions.Exception
 |
 |  Methods inherited from exceptions.Exception:
 |
 |  __getitem__(...)
 |
 |  __init__(...)
 |
 |  __str__(...)
#End output

"print e" produces ""

So I could handle this by writing an except clause for TypeError.

Boost.Python doesn't exist as a module i.e. it's not in sys.modules,
and I don't know how to import it - should there be a Boost.Python
module somewhere on my PythonPath that I've forgotten to setup ?
Is there a standard way of catching these errors by their actual
type ?
Is there an easy way to export the exception classes from my c-
extension (testext) so that I can use that ? Thus "except
testext.ArgumentError" would catch the "Boost.Python.ArgumentError" ?

Thanks for any help,
Mark

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


Re: Auto execute python in USB flash disk

2007-03-27 Thread Tim Golden
Brian Erhard wrote:
> Is there
> a way to auto execute a python script after a user double clicks to
> open a folder on the USB drive? How can you capture that double click
> event on a specific folder?

That would depend on what desktop / Operating System you're
using. If it's Windows, you need a shell extension (which
is non-trivial to understand and write). If it's one of the
Linux desktops, someone else had better chip in!

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


Re: Numeric Soup

2007-03-27 Thread Robert Kern
Ene wrote:
> As it stands Matplotlib does not
> support numpy (thus my suggestion to install two of the three - my
> choice: numarray + numpy)

matplotlib certainly supports numpy.

-- 
Robert Kern

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

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


Re: Numeric Soup

2007-03-27 Thread Ene
On Mar 27, 9:49 am, "Erik Johnson" <[EMAIL PROTECTED]> wrote:
> I am just starting to explore doing some scientific type data analysis
> using Python, and am a little confused by the different incarnations of
> modules (e.g., try Google("Python numeric").
>
> There is SciPy, NumPy, NumArray, Numeric...  I know some of these are
> related and some are separate, some are oudated, etc. but can someone sort
> of give a general run-down in layman's terms of what's what, what's used for
> what, what depends on what, and what's current?
>
> At this point my interest is just sort of general, fast array
> manipulation and DSP.
>
> Thanks!

Numeric was slow at large-arrays, so numarray was born.  Well numarray
turned out to be slow at small arrays, so numpy was born. It is trying
to merge Numeric and Numpy together. As it stands Matplotlib does not
support numpy (thus my suggestion to install two of the three - my
choice: numarray + numpy)

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


Re: Auto execute python in USB flash disk

2007-03-27 Thread kyosohma
On Mar 27, 11:56 am, "Brian Erhard" <[EMAIL PROTECTED]> wrote:
> I am still fairly new to python and wanted to attempt a home made
> password protection program.  There are files that I carry on a USB
> flash drive that I would like to password protect.  Essentially, I
> would like to password protect an entire directory of files.  Is there
> a way to auto execute a python script after a user double clicks to
> open a folder on the USB drive? How can you capture that double click
> event on a specific folder?
>
> Thanks.

I've never done this before, but it sounds cool. You would need to
create some kind of python file object to do this properly. So instead
of actually clicking a folder, you would click a pickled file or
something. I found some cool info about encrypting files here:

http://www.methods.co.nz/python/

There's also a python cryptography kit: 
http://www.amk.ca/python/writing/pycrypt/

Finally, I found a fellow python programmer that wrote his own:
http://mail.python.org/pipermail/python-list/2006-April/378510.html

There's also PortablePython...

Enjoy!

Mike

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


Re: Auto execute python in USB flash disk

2007-03-27 Thread Ene
On Mar 27, 9:56 am, "Brian Erhard" <[EMAIL PROTECTED]> wrote:
> I am still fairly new to python and wanted to attempt a home made
> password protection program.  There are files that I carry on a USB
> flash drive that I would like to password protect.  Essentially, I
> would like to password protect an entire directory of files.  Is there
> a way to auto execute a python script after a user double clicks to
> open a folder on the USB drive? How can you capture that double click
> event on a specific folder?
>
> Thanks.

Install the free PortablePython from http://www.portablepython.com/ on
your USB
flash drive, and go from there.

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


Re: Numeric Soup

2007-03-27 Thread Robert Kern
Erik Johnson wrote:
> I am just starting to explore doing some scientific type data analysis
> using Python, and am a little confused by the different incarnations of
> modules (e.g., try Google("Python numeric").
> 
> There is SciPy, NumPy, NumArray, Numeric...  I know some of these are
> related and some are separate, some are oudated, etc. but can someone sort
> of give a general run-down in layman's terms of what's what, what's used for
> what, what depends on what, and what's current?

http://www.scipy.org/History_of_SciPy

numpy is the current array package and supercedes Numeric and numarray. scipy
provides a bunch of computational routines (linear algebra, optimization,
statistics, signal processing, etc.) built on top of numpy.

-- 
Robert Kern

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

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


Re: Please help!! SAXParseException: not well-formed (invalid token)

2007-03-27 Thread jvictor118
I checked the file format (of the file containing the n-tilde - ñ) and
it is indeed UTF-8! I'm baffled! Any ideas?

Thanks,
Jason

On Mar 27, 11:16 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I've been using the xml.sax.handler module to do event-driven parsing
> > of XML files in this python application I'm working on. However, I
> > keep having really pesky invalid token exceptions. Initially, I was
> > only getting them on control characters, and a little "sed -e 's/
> > [^[:print:]]/ /g' $1;" took care of that just fine. But recently, I've
> > been getting these invalid token excpetions with n-tildes (like the n
> > in España), smart/fancy/curly quotes and other seemingly harmless
> > characters. Specifying encoding="utf-8" in the xml header hasn't
> > helped matters.
>
> > Any ideas? As a last resort, I'd be willing to scrub invalid
> > characters it just seems strange that curly quotes and n-tildes
> > wouldn't be valid XML! Is that really the case?
>
> It's not the case, unless you have a wrong encoding. Then the whole
> XML-Document isn't a XML-document at all.
>
> Just putting an encoding header that doesn't match the actually used
> encoding won't fix that.
>
> Read up on what encodings are, and ensure your XML-generation respects that.
> Then reading these files will cause no problems.
>
> Diez

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


Auto execute python in USB flash disk

2007-03-27 Thread Brian Erhard
I am still fairly new to python and wanted to attempt a home made
password protection program.  There are files that I carry on a USB
flash drive that I would like to password protect.  Essentially, I
would like to password protect an entire directory of files.  Is there
a way to auto execute a python script after a user double clicks to
open a folder on the USB drive? How can you capture that double click
event on a specific folder?

Thanks.

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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Jaap Spies
Mark Morss wrote:

> 
> Maybe somebody reading this will be able to convince me to look again
> at Numpy/Scipy, but for the time being I will continue to do my
> serious numerical computation in Fortran.
> 

What I am missing in this discussion is a link to Pyrex to speed up
Python: Pyrex is almost Python with the speed of compiled C.
http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/

Pyrex is adapted in SAGE (Software for Algebra and Geometry 
Experimentation) as Sagex: http://modular.math.washington.edu/sage/

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


Re: Help in Placing Object in Memory

2007-03-27 Thread Bruno Desthuilliers
Clement a écrit :
> I am newbie to Python.. 

To Python only, or to both Python and programming in general ?

> i want to know something..
> 
> can i place an object in disk instead of placing in Main Memory...?

You can store it on disk (cf pickles and friends), but to actually use 
it you'll have to load it in memory anyway.

> can two python script share a common object?

While there are technical answers on this, I guess you'd better learn 
how to use functions and pass objects between them.

My 2 cents.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: enumerating processes

2007-03-27 Thread Shane Geiger



I believe you are looking for os.getpid()
I apologize for providing that bit of incorrect info. 

It looks to me as if Python 1.5 had os.process which might have done 
what you wanted (although perhaps not in an OS-independent way).  I 
wonder why there isn't an OS-independent way to do that in Python now.


After having seen your message about tomcat.exe, I assume we are talking 
just about Windows.  ;-)  This looks like an excellent way to deal with 
processes on Windows:


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

# List all running processes

import wmi
c = wmi.WMI ()
for process in c.Win32_Process ():
 print process.ProcessId, process.Name


# List all running notepad processes

import wmi
c = wmi.WMI ()
for process in c.Win32_Process (name="notepad.exe"):
 print process.ProcessId, process.Name


# Create and then destroy a new notepad process

import wmi
c = wmi.WMI ()
process_id, return_value = c.Win32_Process.Create 
(CommandLine="notepad.exe")

for process in c.Win32_Process (ProcessId=process_id):
 print process.ProcessId, process.Name

result = process.Terminate ()









李现民 wrote:

hi ,all
   any one knows how to enumerate the current running processes , or 
how to obtain a specific process by its name or process id. I know I 
can do this in many  programming languages , but how in python? any 
one know?

 Thanks for any guidance.

--
li xianmin

   [EMAIL PROTECTED]  




--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Numeric Soup

2007-03-27 Thread Erik Johnson

I am just starting to explore doing some scientific type data analysis
using Python, and am a little confused by the different incarnations of
modules (e.g., try Google("Python numeric").

There is SciPy, NumPy, NumArray, Numeric...  I know some of these are
related and some are separate, some are oudated, etc. but can someone sort
of give a general run-down in layman's terms of what's what, what's used for
what, what depends on what, and what's current?

At this point my interest is just sort of general, fast array
manipulation and DSP.

Thanks!



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


Re: shutil.copy Problem

2007-03-27 Thread John Nagle
Facundo Batista wrote:
> David Nicolson wrote:
> 
> 
>>Thanks, but it's definitely not the print. In original the code the  
>>print statements are replaced by a call to a log method.
>>
>>Besides, the exception would be different if it was thrown outside of  
>>the try block.
> 
> 
> The best you can do is take the piece of code that has the problem, show
> it to us, and then copy the traceback.
> 
> Regards,

   There may be some problem here with a file being recognized as Unicode
in binary mode.  That shouldn't happen, but looking at the Windows
UNICODE support, it might not be impossible.

   Information needed:

- Platform (Windows, Linux, ...)
- Python version
- A hex dump of the first few bytes of the input file.

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


Re: Zip file writing progress (callback proc)

2007-03-27 Thread Larry Bates
durumdara wrote:
> Hi!
> 
> I want to check my zip file writings.
> I need some callback procedure to show a progress bar.
> Can I do that?
> I don't want to modify the PyLib module to extend it, because if I get
> another py, the changes are lost.
> This happening too if I copy the zip module to modify it.
> Any solution?
> 
> Thanks for it:
>dd

I did this by extending the write method of my zipfile module.

1) Add a callback= keyword argument to __init__ and saving that in
an instance variable (self._callback).

def __init__(self, file, mode="r", compression=ZIP_STORED,
 allowZip64=False, callback=None):

"""Open the ZIP file with mode read "r", write "w" or append "a"."""
self._allowZip64 = allowZip64
self._didModify = False
self._callback = callback  # new instance variable to be used in write




2) Change write method so that it calls the progress method of the callback
function after every block is written (if user passed in one).

while 1:
buf = fp.read(1024 * 8)
if not buf:
break
file_size = file_size + len(buf)
#-New lines follow
#
# Call the progress method of the callback function (if defined)
#
if self._callback is not None:
self._callback.progress(st.st_size, fp.tell())

#-End of new lines
CRC = binascii.crc32(buf, CRC)
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)



3) Define a callback class and use it:

import zipfile

class CB():
def progress(self, total, sofar):
zippercentcomplete=100.0*sofar/total
print "callback.progress.zippercentcomplete=%.2f" % zippercentcomplete
return

z=zipfile.ZipFile(r'C:\testzip.zip', mode='w', callback=CB())
z.write(r'c:\Library\TurboDelphi\TurboDelphi.exe')

At least by doing it this way you won't break anything if you get a new zipfile
module.  It just won't show progress any more and then you can patch it.

Hope info helps.

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


Re: exit to interpreter?

2007-03-27 Thread jay graves
On Mar 23, 12:52 pm, belinda thom <[EMAIL PROTECTED]> wrote:
> be processed up the call stack. My problem is this. I'd also like it
> to handle a special string (e.g. 'quit'), in which case control
> should return to the Python command line as opposed to returning the
> string up the call stack.

Maybe you are looking for the 'code' module.

http://docs.python.org/lib/module-code.html

...
Jay Graves

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


Re: Help in Placing Object in Memory

2007-03-27 Thread Erik Johnson

"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> What do you mean by that? They can both load a pickled object, yes. But
they
> can't share it as a at-runtime object, where changes in one script are
> immediately are known to the other.
>
> To do such a thing, look at pyro.

Or not natively (i.e., that battery isn't included). I believe it can
still be done, though: http://poshmodule.sourceforge.net/
(I haven't used the module - just used Google to locate it)

You could, of course, roll-your-own solution using shared memory and/or
other interprocess communication (http://docs.python.org/lib/ipc.html)

Hope that helps,
-ej


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


Re: Help in Placing Object in Memory

2007-03-27 Thread Michael L Torrie
On Tue, 2007-03-27 at 16:49 +0200, Diez B. Roggisch wrote:
> > can two python script share a common object?
> 
> What do you mean by that? They can both load a pickled object, yes. But they
> can't share it as a at-runtime object, where changes in one script are
> immediately are known to the other.

Remote procedure call, such as Python Twisted's PB library can allow
this to virtually be the case.

> 
> To do such a thing, look at pyro.
> 
> Diez

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


Re: pattern search

2007-03-27 Thread Wojciech Muła
Fabian Braennstroem wrote:
> Now, I would like to improve it by searching for different 'real'
> patterns just like using 'ls' in bash. E.g. the entry
> 'car*.pdf' should select all pdf files with a beginning 'car'.
> Does anyone have an idea, how to do it?

Use module glob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SPE question

2007-03-27 Thread SPE - Stani's Python Editor
On 27 Mrz., 14:01, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> I believe that just deleting the folders should work

No, never delete the folder if you used the windows installer (*.exe)!
Go to your control panel>Add/Remove Programs and there should be an
entry "python*-spe*" with an uninstall button. Probably you were only
looking for a SPE entry. Python modules are often listed with a python
prefix.

Stani

>
> Dick Moores wrote:
> > At 03:37 AM 3/27/2007, [EMAIL PROTECTED] wrote:
> > >On Mar 27, 11:39 am, "alain" <[EMAIL PROTECTED]> wrote:
> > > > Hi,
>
> > > > Could someone tell me how to uninstallSPEunder windows?
>
> > > > Alain
>
> > >Dunno aboutSPE, but most Python modules I've installed can
> > >be uninstalled from control panel/add remove programs.
>
> >SPEdoesn't show up on my win XP add/remove programs list.
>
> > Dick Moores


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


Re: pattern search

2007-03-27 Thread Diez B. Roggisch
Fabian Braennstroem wrote:

> Hi,
> 
> I wrote a small gtk file manager, which works pretty well. Until
> now, I am able to select different file (treeview entries) just by
> extension (done with 'endswith'). See the little part below:
> 
> self.pathlist1=[ ]
> self.patternlist=[ ]
> while iter:
> #print iter
> value = model.get_value(iter, 1)
> #if value is what I'm looking for:
> if value.endswith("."+ pattern):
> selection.select_iter(iter)
> selection.select_path(n)
> self.pathlist1.append(n)
> self.patternlist.append(value)
> iter = model.iter_next(iter)
> #print value
> n=n+1
> 
> Now, I would like to improve it by searching for different 'real'
> patterns just like using 'ls' in bash. E.g. the entry
> 'car*.pdf' should select all pdf files with a beginning 'car'.
> Does anyone have an idea, how to do it?

Use regular expressions. They are part of the module "re". And if you use
them, ditch your code above, and make it just search for a pattern all the
time. Because the above is just the case of

*.ext



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


Re: Please help!! SAXParseException: not well-formed (invalid token)

2007-03-27 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> I've been using the xml.sax.handler module to do event-driven parsing
> of XML files in this python application I'm working on. However, I
> keep having really pesky invalid token exceptions. Initially, I was
> only getting them on control characters, and a little "sed -e 's/
> [^[:print:]]/ /g' $1;" took care of that just fine. But recently, I've
> been getting these invalid token excpetions with n-tildes (like the n
> in España), smart/fancy/curly quotes and other seemingly harmless
> characters. Specifying encoding="utf-8" in the xml header hasn't
> helped matters.
> 
> Any ideas? As a last resort, I'd be willing to scrub invalid
> characters it just seems strange that curly quotes and n-tildes
> wouldn't be valid XML! Is that really the case?

It's not the case, unless you have a wrong encoding. Then the whole
XML-Document isn't a XML-document at all.

Just putting an encoding header that doesn't match the actually used
encoding won't fix that.

Read up on what encodings are, and ensure your XML-generation respects that.
Then reading these files will cause no problems.

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

Re: Please help!! SAXParseException: not well-formed (invalid token)

2007-03-27 Thread kyosohma
On Mar 27, 9:59 am, [EMAIL PROTECTED] wrote:
> I've been using the xml.sax.handler module to do event-driven parsing
> of XML files in this python application I'm working on. However, I
> keep having really pesky invalid token exceptions. Initially, I was
> only getting them on control characters, and a little "sed -e 's/
> [^[:print:]]/ /g' $1;" took care of that just fine. But recently, I've
> been getting these invalid token excpetions with n-tildes (like the n
> in España), smart/fancy/curly quotes and other seemingly harmless
> characters. Specifying encoding="utf-8" in the xml header hasn't
> helped matters.
>
> Any ideas? As a last resort, I'd be willing to scrub invalid
> characters it just seems strange that curly quotes and n-tildes
> wouldn't be valid XML! Is that really the case?
>
> TIA!
>
> Jason

Are you making sure to encode the strings you pass into the parser in
UTF-8 or UTF-16? This article was illuminating in that respect and may
be helpful in diagnosing your problem:

http://www.xml.com/pub/a/2002/11/13/py-xml.html?page=2

Mike

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


Re: exit to interpreter?

2007-03-27 Thread Steven W. Orr
On Friday, Mar 23rd 2007 at 10:52 -0700, quoth belinda thom:

=>I'm writing a function that polls the user for keyboard input,  
=>looping until it has determined that the user has entered a valid  
=>string of characters, in which case it returns that string so it can  
=>be processed up the call stack. My problem is this. I'd also like it  
=>to handle a special string (e.g. 'quit'), in which case control  
=>should return to the Python command line as opposed to returning the  
=>string up the call stack.
=>
=>sys.exit seemed like a good choice, but it exits the python interpreter.
=>
=>I could use an exception for this purpose, but was wondering if  
=>there's a better way?

I was reading other people's responses. Why not simply use the python 
debugger?

http://docs.python.org/lib/module-pdb.html

Yes? No?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about second parameter of signal handler func.

2007-03-27 Thread Gabriel Genellina
En Tue, 27 Mar 2007 02:34:48 -0300, Bjoern Schliessmann  
<[EMAIL PROTECTED]> escribió:

>> In C, a signal handler function has only one parameter, that is
>> signal number. But in Python(import signal), a signal handler
>> function has two parameters, the first is signal number, the
>> second is "frame"?
>>
>> What is "frame", please?
>
> Did you bother using help()?

The help text is of little help if you don't know what is it talking  
about...

The Python signal handler has additional information: you know *what* was  
being executed when the signal was caught (or nearly).
A little example:


import signal

def babies(n):
 if n<=1: return 1
 return adults(n-1)

def adults(n):
 if n<=1: return 0
 return adults(n-1)+babies(n-1)

def fibom(n):
 return adults(n)+babies(n)

def handler(signum, frame):
 print "At",frame.f_code.co_name, "in", frame.f_code.co_filename,  
"line", frame.f_lineno

# Press CTRL-C to see what's being executed
signal.signal(signal.SIGINT, handler)
for n in range(50):
 print n, fibom(n)

-- 
Gabriel Genellina

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


pattern search

2007-03-27 Thread Fabian Braennstroem
Hi,

I wrote a small gtk file manager, which works pretty well. Until
now, I am able to select different file (treeview entries) just by
extension (done with 'endswith'). See the little part below:

self.pathlist1=[ ]
self.patternlist=[ ]
while iter:
#print iter
value = model.get_value(iter, 1)
#if value is what I'm looking for:
if value.endswith("."+ pattern):
selection.select_iter(iter)
selection.select_path(n)
self.pathlist1.append(n)
self.patternlist.append(value)
iter = model.iter_next(iter)
#print value
n=n+1

Now, I would like to improve it by searching for different 'real'
patterns just like using 'ls' in bash. E.g. the entry
'car*.pdf' should select all pdf files with a beginning 'car'.
Does anyone have an idea, how to do it?

Greetings!
Fabian

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


Please help!! SAXParseException: not well-formed (invalid token)

2007-03-27 Thread jvictor118
I've been using the xml.sax.handler module to do event-driven parsing
of XML files in this python application I'm working on. However, I
keep having really pesky invalid token exceptions. Initially, I was
only getting them on control characters, and a little "sed -e 's/
[^[:print:]]/ /g' $1;" took care of that just fine. But recently, I've
been getting these invalid token excpetions with n-tildes (like the n
in España), smart/fancy/curly quotes and other seemingly harmless
characters. Specifying encoding="utf-8" in the xml header hasn't
helped matters.

Any ideas? As a last resort, I'd be willing to scrub invalid
characters it just seems strange that curly quotes and n-tildes
wouldn't be valid XML! Is that really the case?

TIA!

Jason

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


Re: Help in Placing Object in Memory

2007-03-27 Thread Diez B. Roggisch
Clement wrote:

> I am newbie to Python.. i want to know something..
> 
> can i place an object in disk instead of placing in Main Memory...? 
> If possible, can you please explain with some scripts...?

See the module pickle and it's examples.

> can two python script share a common object?

What do you mean by that? They can both load a pickled object, yes. But they
can't share it as a at-runtime object, where changes in one script are
immediately are known to the other.

To do such a thing, look at pyro.

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


Re: socket read timeout

2007-03-27 Thread skip

>> I am looking for the most efficient / cleanest way to implement a
>> socket read with timeout (Windows mainly but would be great if the
>> same code worked under *nix)

Jarek> Did you see http://www.timo-tasi.org/python/timeoutsocket.py ?

Also socket objects have timeout attributes now.

Skip

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


Help in Placing Object in Memory

2007-03-27 Thread Clement
I am newbie to Python.. i want to know something..

can i place an object in disk instead of placing in Main Memory...?

If possible, can you please explain with some scripts...?

can two python script share a common object?

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


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Mark Morss
On Mar 26, 12:59 pm, "Erik Johnson" <[EMAIL PROTECTED]> wrote:
> <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > OK...
> > I've been told that Both Fortran and Python are easy to read, and are
> > quite useful in creating scientific apps for the number crunching, but
> > then Python is a tad slower than Fortran because of its a high level
> > language nature, so what are the advantages of using Python for
> > creating number crunching apps over Fortran??
> > Thanks
> > Chris
>
> So, after reading much of animated debate here, I think few would
> suggest that Python is going to be faster than FORTRAN when it comes to raw
> execution speed. Numeric and SciPy are Python modules that are geared
> towards numerical computing and can give substantial performance gians over
> plain Python.
>
> A reasonable approach (which has already been hinted at here), is to try
> to have the best of both world by mixing Python and FORTRAN - doing most of
> the logic and support code in Python and writing the raw computing routines
> in FORTRAN. A reasonable approach might be to simply make your application
> work in Python, then use profiling to identify what parts are slowest and
> move those parts into a complied language such as FORTRAN or C if overall
> performance is not fast enough.  Unless your number crunching project is
> truly massive, you may find that Python is a lot faster than you thought and
> may be plenty fast enough on it's own.
>
> So, there is a tradeoff of resources between development time, execution
> time, readability, understandability, maintainability, etc.
>
> psyco is a module I haven't seen mentioned here - I don't know a lot
> about it, but have seen substantial increases in performance in what little
> I have used it. My understanding is that it produces multiple versions of
> functions tuned to particular data types, thus gaining some advantage over
> the default, untyped bytecode Python would normally produce. You can think
> of it as a JIT compiler for Python (but that's not quite what it is doing).
> The home page for that module is here:  http://psyco.sourceforge.net/
>
> Hope that help,
> -ej

The question as originally framed was a little ignorant, of course.
Python and Fortran are by no means subtitutes.  Python is interpreted,
comprehensively interroperates with just about anything, and is
relatively slow.  Fortran is compiled, interoperates with almost
nothing and is blindingly fast.  So it is like a battle between an
elephant and a whale.

If there is possible substitution, and hence competition, it is
between Python+Numpy/Scipy on the one hand and Python+Fortran, via
F2PY, on the other.  My personal taste is to do things in Fortran when
I can.  It is really pretty simple to write well-structured, clear
code in Fortran 95, and I don't find it troublesome to compile before
I run.  I don't find type declarations to be a nuisance; on the
contrary, I think they're very useful for good documentation.  Also I
am somewhat mistrustful of Numpy/Scipy, because when I visit their
forums, almost all the chatter is about bugs and/or failure of some
function to work on some operating system.  Perhaps I am wrong, but
Python+Numpy/Scipy looks a little unstable.

I understand that the purpose of Numpy/Scipy is to make it possible to
do large-scale numerical computation in Python (practically all
serious numerical computation these days is large-scale) without
paying too much of a penalty in speed (relative to doing the same
thing with a compiled language), but I have not yet been persuaded to
take the trouble to learn the special programming vocabulary,
essential tricks, and so forth, necessar for Numpy/Scipy when Fortran
is ready to hand, very well established, and definitely faster.

I do value Python very much for what it was designed for, and I do
plan eventually to hook some of my Fortran code to Python via F2PY, so
that interoperability with spreadsheets, OLAP and the like on the
front and back ends of my information flow.

Maybe somebody reading this will be able to convince me to look again
at Numpy/Scipy, but for the time being I will continue to do my
serious numerical computation in Fortran.

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


Re: Use threads or Tkinter event loop?

2007-03-27 Thread kyosohma
On Mar 27, 9:07 am, Kevin Walzer <[EMAIL PROTECTED]> wrote:
> Kevin Walzer wrote:
> > I'm trying to decide whether I need threads in my Tkinter application or
> > not. My app is a front end to a command-line tool; it feeds commands to
> > the command-line program, then reads its output and displays it in a
> > Tkinter text widget. Some of the commands are long-running and/or return
> > thousands of lines of output.
>
> > I initially thought I needed to use threading, because the GUI would
> > block when reading the output, even when I configured the blocking to be
> > non-blocking. I got threading to work, but it seemed a bit complicated.
> > So, I decided to try something simpler, by using the Tkinter event loop
> > to force the output to update/display.
>
> > it seems to work well enough. Here is my threaded code:
>
> > non-threaded:
>
> > def insertDump(self):
> >  self.finkinstalled = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK)
> > for line in self.finkinstalled:
> > self.t.insert(END, line)
> > self.update()
> > self.t.see(END)
>
> > And here is my non-threaded code (needs two functions to work)
>
> >  def insertDump(self):
> > try:
> > data = self.dataQueue.get(block=False)
> > for line in data:
> > self.t.insert(END, line)
> > self.t.see(END)
> > self.update()
>
> > except:
> > print "error"
> > raise
>
> > def getDump(self):
>
> > self.file = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK)
> > self.dataQueue.put(self.file)
>
> > This brings me to a design, as opposed to coding, question. The
> > non-threaded version seems to work just as well as the threaded one, in
> > terms of speed. Moreover, it is simpler to code and debug, because I
> > don't have to check to make sure the thread queue has data (I sometimes
> > get an 'Empty' error message when I first start the thread).  Simply
> > using the Tk event loop (self.update) is also how I would have coded
> > this in Tcl.
>
> > So my question is this: under what circumstances in Python are threads
> > considered "best practice"? Am I wrong to use the Tk event loop instead
> > of threads?
>
> D'oh, I got the code snippets mixed up:
>
> non-threaded:
>
> def insertDump(self):
>   self.finkinstalled = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK)
>  for line in self.finkinstalled:
>  self.t.insert(END, line)
>  self.update()
>  self.t.see(END)
>
> threaded:
>
>   def insertDump(self):
>  try:
>  data = self.dataQueue.get(block=False)
>  for line in data:
>  self.t.insert(END, line)
>  self.t.see(END)
>  self.update()
>
>  except:
>  print "error"
>  raise
>
>  def getDump(self):
>
>  self.file = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK)
>  self.dataQueue.put(self.file)
>
> Sorry!
> --
> Kevin Walzer
> Code by Kevinhttp://www.codebykevin.com

It looks like Tkinter is similar to wxPython in that you're not
supposed to use the mainloop for anything except the GUI and GUI
commands. The following websites have more info on Tkinter and
threads:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965
http://www.thescripts.com/forum/thread22536.html
http://forums.devshed.com/python-programming-11/tkinter-threads-123001.html

I use the Threading module for threading in wxPython. I think that
would probably serve you well with Tkinter as well. You can use the
join() method to wait for all the threads to exit.

Mike

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


Type allocation in extensions

2007-03-27 Thread Nicholas Milkovits
Hi everyone,

I've been reading through the documentation on extending and embedding
python and the C API and I have a question about how allocation occurs
of one type from another type. For example lets so I make to C module
foo.c and bar.c and each has a python type.  If I want to define a
method in foo.c that will return and new bar object how would I go
about doing that. Do I need to initialize tp_call and tp_alloc in
order to use PyObject_Call()? Also, If I do not supply an allocfunc
but instead initialize it to 0 when I declare my PyTypeObject for foo
does it automatically get set to a generic allocation function?

For example:

In python I want to be able to write:

f = Foo.new()
b = foo.bar()


bar.c

static PyTypeObject BarType = {
PyObject_HEAD_INIT(NULL)
0,// ob_size
"bar",  // tp_name
sizeof(bar),// tp_basicsize
0,  // tp_itemsize
(destructor) Bar_Free, // tp_dealloc
.snip...
0, //tp_call
.snip...
(initproc) Bar_Init,   // tp_init
0,// tp_alloc
Bar_New,// tp_new
0,   // tp_free


static PyObject *Bar_New(PyTypeObject *type, PyObject *args, PyObject
keywordArgs)
{
 // How does this call work if I never set an allocfunc pointer when I
// declared the bar type
 return= type->tp_alloc(type, 0);
}


foo.c

// Is PyObject_Call what I want to use and if so
// how does it work if tp_call was initialized to 0
// or not even specified in my BarType variable?
static PyObject *Foo_NewBar(foo *self, PyObject *args)  
{
PyObject *createArgs, *bar_ref;

createArgs = PyTuple_New();
if (!createArgs)
return NULL;
Py_INCREF(self);
bar_ref = PyObject_Call( (PyObject*) &BarType, createArgs, NULL);
Py_DECREF(createArgs);
return bar_ref;
}

Thanks in advace for the help,
Nick
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >