Re: with timeout(...):

2007-03-27 Thread Nick Craig-Wood
Klaas <[EMAIL PROTECTED]> wrote:
>  On Mar 26, 3:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> > Did anyone write a contextmanager implementing a timeout for
> > python2.5?
> >
> > I'd love to be able to write something like
> >
> > with timeout(5.0) as exceeded:
> > some_long_running_stuff()
> > if exceeded:
> > print "Oops - took too long!"
> >
> > And have it work reliably and in a cross platform way!
> 
>  Doubt it.  But you could try:
> 
>  class TimeoutException(BaseException):
> pass
> 
>  class timeout(object):
> def __init__(self, limit_t):
> self.limit_t = limit
> self.timer = None
> self.timed_out = False
> def __nonzero__(self):
> return self.timed_out
> def __enter__(self):
> self.timer = threading.Timer(self.limit_t, ...)
> self.timer.start()
> return self
> def __exit__(self, exc_c, exc, tb):
> if exc_c is TimeoutException:
>self.timed_out = True
>return True # suppress exception
> return False # raise exception (maybe)
> 
>  where '...' is a ctypes call to raise the given exception in the
>  current thread (the capi call PyThreadState_SetAsyncExc)
> 
>  Definitely not fool-proof, as it relies on thread switching.  Also,
>  lock acquisition can't be interrupted, anyway.  Also, this style of
>  programming is rather unsafe.
> 
>  But I bet it would work frequently.

Here is my effort...  You'll note from the comments that there are
lots of tricky bits.

It isn't perfect though as it sometimes leaves behind threads (see the
FIXME).  I don't think it crashes any more though!



"""
General purpose timeout mechanism not using alarm(), ie cross platform

Eg

from timeout import Timeout, TimeoutError

def might_infinite_loop(arg):
while 1:
pass

try:
Timeout(10, might_infinite_loop, "some arg")
except TimeoutError:
print "Oops took too long"
else:
print "Ran just fine"

"""

import threading
import time
import sys
import ctypes
import os

class TimeoutError(Exception):
"""Thrown on a timeout"""
PyThreadState_SetAsyncExc = ctypes.pythonapi.PyThreadState_SetAsyncExc
_c_TimeoutError = ctypes.py_object(TimeoutError)

class Timeout(threading.Thread):
"""
A General purpose timeout class
timeout is int/float in seconds
action is a callable
*args, **kwargs are passed to the callable
"""
def __init__(self, timeout, action, *args, **kwargs):
threading.Thread.__init__(self)
self.action = action
self.args = args
self.kwargs = kwargs
self.stopped = False
self.exc_value = None
self.end_lock = threading.Lock()
# start subtask
self.setDaemon(True)# FIXME this shouldn't be needed 
but is, indicating sub tasks aren't ending
self.start()
# Wait for subtask to end naturally
self.join(timeout)
# Use end_lock to kill the thread in a non-racy
# fashion. (Using isAlive is racy).  Poking exceptions into
# the Thread cleanup code isn't a good idea either
if self.end_lock.acquire(False):
# gained end_lock => sub thread is still running
# sub thread is still running so kill it with a TimeoutError
self.exc_value = TimeoutError()
PyThreadState_SetAsyncExc(self.id, _c_TimeoutError)
# release the lock so it can progress into thread cleanup
self.end_lock.release()
# shouldn't block since we've killed the thread
self.join()
# re-raise any exception
if self.exc_value:
raise self.exc_value
def run(self):
self.id = threading._get_ident()
try:
self.action(*self.args, **self.kwargs)
except:
self.exc_value = sys.exc_value
# only end if we can acquire the end_lock
self.end_lock.acquire()

if __name__ == "__main__":

def _spin(t):
"""Spins for t seconds"""
start = time.time()
end = start + t
while time.time() < end:
pass

def _test_time_limit(name, expecting_time_out, t_limit, fn, *args, 
**kwargs):
"""Test Timeout"""
start = time.time()

if expecting_time_out:
print "Test",name,"should timeout"
else:
print "Test",name,"shouldn't timeout"

try:
Timeout(t_limit, fn, *args, **kwargs)
except TimeoutError, e:
if expecting_time_out:
print "Timeout generated OK"
else:
raise RuntimeError("Wasn't expecting TimeoutError Here")
else:
if expecting_time_out:
raise RuntimeError("Was expecting TimeoutError Here")
else:
print "No TimeoutError generated OK"

elapsed = time.time() - start
print "Th

Re: with timeout(...):

2007-03-27 Thread Nick Craig-Wood
Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
>  so Diez is probably right that the way to go is to put the timer in the
>  python interpreter loop, as its the only thing around that you could 
>  more or less trust to run all the time.
> 
>  But then it will not read as nice as Nick's wish, but more like this:
> 
>  id = setup_callback(error_routine, timeout_in_milliseconds)
>  long_running_stuff_that_can_block_on_IO(foo, bar, baz)
>  cancel_callback(id)
>  print "Hooray it worked !! "
>  sys.exit()
> 
>  def error_routine():
>  print "toughies it took too long - your chocolate is toast"
>  attempt_at_recovery_or_explanation(foo, bar, baz)
> 
>  Much more ugly.

I could live with that!

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

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

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fetch html page via isa proxy

2007-03-27 Thread Radek
> So you have already tried NTLM Authorization Proxy 
> Server?http://ntlmaps.sourceforge.net/
> This used to work fine for me but that was at least 3-4 years ago.

Actually NTLM proxy server works for most intranet addresses. Not for
the outside Internet ones, though.

Radek

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


SPE question

2007-03-27 Thread alain
Hi,

Could someone tell me how to uninstall SPE under windows?

Alain

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


Re: Tkinter Toplevel geometry

2007-03-27 Thread Chris

> A TRULY good way to show your thanks for help like this
> is to write up what you learned at theTkinterWiki 
> http://tkinter.unpythonic.net/wiki/>.  Note:
> A.  You have to log in to edit pages
> on this particular Wiki.  If you
> decide to join us, then, you'll
> first need to create an account.

I'll do that, yes. I guess I should create a 'Toplevel' page and put
the information on there? Unless someone can suggest something better.

I also wonder if I should have posted this question to the tkinter-
discuss mailing list (see http://tkinter.unpythonic.net/wiki/TkinterDiscuss)
instead of to comp.lang.python. However, I wasn't aware of that list
before, and it's not linked to from the python.org 'community' page
(as far as I can see - and in fact, the python.org pages imply that
tkinter questions should be asked on comp.lang.python). I'm new to
tkinter, so it wasn't immediately clear where to get help.

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


Re: __init__.py

2007-03-27 Thread Jorgen Grahn
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

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __init__.py

2007-03-27 Thread Steve Holden
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
> 
The presence of an __init__.py marks a directory as the root of a Python 
package, which means other modules can be found in it. This allows you 
to import names with multiple levels of dots, which are modules within 
packages.

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

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


plot dendrogram with python

2007-03-27 Thread Frank
Hi,

does anyone know if there is a way to plot a dendrogram with python.
Pylab or matplotlib do not provide such a function.

Thanks!

Frank

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


Re: PDB does not allow jumping to first statement?

2007-03-27 Thread Duncan Booth
Peter Otten <[EMAIL PROTECTED]> wrote:

>> Which version of Python, and what happens when you try it?
>> 
>> It works fine for me with Python 2.5 on Windows:
>> 
>> C:\Temp>\python25\python -m pdb t.py
>>> c:\temp\t.py(3)()
>> -> a = 1
>> (Pdb) s
>>> c:\temp\t.py(4)()
>> -> b = 2
>> (Pdb) j 3
>>> c:\temp\t.py(3)()
>> -> a = 1
>> (Pdb)
> 
> It looks like you successfully jumped to the first line, but it will 
be
> skipped if you try to execute it:
> 

That's why I asked what actually happened. Yes, you and the OP seem to 
be correct, jumping to the first executable line in a module appears not 
to execute the line.

I verified (with a print statement in pdb) that assigning to 
self.curframe.f_lineno sets self.curframe.f_lineno and 
sel.curframe.f_lasti incorrectly:

C:\Temp>\python25\python -m pdb t.py
> c:\temp\t.py(3)()
-> a = 1
(Pdb) s
> c:\temp\t.py(4)()
-> b = 2
(Pdb) s
> c:\temp\t.py(5)()
-> a = 3
(Pdb) l
  1 #!/usr/bin/env python
  2
  3 a = 1
  4 b = 2
  5  -> a = 3
  6 c = a + b
  7 import dis, sys
  8 dis.dis(sys._getframe().f_code)
  9 print c
[EOF]
(Pdb) j 4
f_lineno 4 f_lasti 6
> c:\temp\t.py(4)()
-> b = 2
(Pdb) j 3
f_lineno 4 f_lasti 6
> c:\temp\t.py(3)()
-> a = 1
(Pdb) j 5
f_lineno 5 f_lasti 12
> c:\temp\t.py(5)()
-> a = 3
(Pdb) j 3
f_lineno 4 f_lasti 6
> c:\temp\t.py(3)()
-> a = 1
(Pdb)

The problem looks to be in frameobject.c:

addr = 0;
line = f->f_code->co_firstlineno;
new_lasti = -1;
for (offset = 0; offset < lnotab_len; offset += 2) {
addr += lnotab[offset];
line += lnotab[offset+1];
if (line >= new_lineno) {
new_lasti = addr;
new_lineno = line;
break;
}
}

The first bytes in lnotab are the length and line increment for line 3 
(i.e. 6, 1). If line==f->f_code->co_firstlineno it should set new_lasti=
0, new_lineno=line but the loop still executes once which increments 
new_lasti and new_lineno to the next line (6, 4).


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


Re: PDB does not allow jumping to first statement?

2007-03-27 Thread [EMAIL PROTECTED]
On Mar 26, 6:06 pm, "Chris Lasher" <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I have a simple script:
>
> ---
> #!/usr/bin/envpython
>
> a = 1
> b = 2
>
> c = a + b
>
> print c
> ---
>
> I launch said script withpdb:
>
> python-mpdbsimple.py
>
> I noticed that I absolutely cannot jump back to the first statement
> (line 3, "a = 1") using the jump command. I can jump to any other line
> BUT the first statement's using the "jump " command. I
> experience the same behavior with Winpdb and rpdb2. Why is this?
>
> Stumped,
> Chris

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

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 pydb (http://bashdb.sf.net/pydb) there are two variations of
restarting a program, one which preserves debugger state ("run") and
one which doesn't ("restart") as it is just a re-exec of the program.
In the presence of multiple threads the exec restart the only reliable
way I know of to force a restart.

Recently in Python's SVN the patch I submitted over a year ago was
applied, so if you prefer pdb and want the "run"-like restart, you can
use that.

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


Re: Sending ECHO_REQUEST (pinging) with python

2007-03-27 Thread Jorgen Grahn
On Mon, 26 Mar 2007 16:50:09 +0200, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> 
wrote:
> Den Mon, 26 Mar 2007 11:24:34 +0200 skrev Michal 'vorner' Vaner:
>> On Mon, Mar 26, 2007 at 08:30:16AM +0200, Thomas Dybdahl Ahle wrote:
>
>>> Do anybody know how to do this in python?
>
>> You need root for that and the ping command is allowed to have them by
>> suid bit. You can execute ping from inside python and use ping as is, if
>> you need.
>
> Yeah, I could execute ping, but it would lock me harder to the platform.

True; Linux ping and Solaris ping have incompatible flags and output.
I even believe several implementations are in use on Linux. Then add
Windows to the mix ...

-Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


tkinter popup

2007-03-27 Thread Gigs_
Hi all

I cant figure out how to disable resizing of my popup window?
How to put this popup window to show in the middle of my text editor?
It is writen with Toplevel.


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


sys.excepthook and threads

2007-03-27 Thread ian
Hi,

sys.excepthook don't work if an exception come in a thread...
It's normal or its a bug ? There are any tip ? look here :
http://spyced.blogspot.com/2005_06_01_archive.html

Thx


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


Re: SPE question

2007-03-27 Thread Dick Moores
At 01:39 AM 3/27/2007, alain wrote:
>Hi,
>
>Could someone tell me how to uninstall SPE under windows?

Well, mine is in E:\Python25\Lib\site-packages\_spe, so I'd try 
deleting that folder.

Dick Moores 

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


Re: SPE question

2007-03-27 Thread irstas
On Mar 27, 11:39 am, "alain" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Could someone tell me how to uninstall SPE under windows?
>
> Alain

Dunno about SPE, but most Python modules I've installed can
be uninstalled from control panel/add remove programs.

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


Re: SPE question

2007-03-27 Thread Dick Moores
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 uninstall SPE under windows?
> >
> > Alain
>
>Dunno about SPE, but most Python modules I've installed can
>be uninstalled from control panel/add remove programs.

SPE doesn't show up on my win XP add/remove programs list.

Dick Moores


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


tkinter MVC

2007-03-27 Thread Gigs_
Can someone give me example how to write text editor in tkintter with 
model-view-controler?
What goes to controler and what goes to model?



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


Re: plot dendrogram with python

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

An ASCII solution:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/139422

Some graphics:
http://plone.org/products/phylogenetictree
http://www.bioinformatics.org/mavric/

Bye,
bearophile

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


Re: plot dendrogram with python

2007-03-27 Thread martin . laloux
I use pycluster

http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/cluster/software.htm#pycluster

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


pygtk button event

2007-03-27 Thread [EMAIL PROTECTED]
Hi


i am trying to implement the following:

I want to be able to press a button, perform a task and return a
value.

my button is named button1 and I used glade to build the gui.

so, something like this should work


application=gtk.glade.XML('app.glade','app')
bt=app.get_widget('button1')
bt.connect('clicked',on_btClicked)
def on_btClicked(widget,event):
  if data==0:
 P=1
  else:
 P=2
  return P

How can I get P?

Something like this doesn't work:

bt.connect('clicked',P=on_btClicked)

How can I return P???


Thanks!

Nick

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


Re: SPE question

2007-03-27 Thread [EMAIL PROTECTED]
I believe that just deleting the folders should work

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 uninstall SPE under windows?
> > >
> > > Alain
> >
> >Dunno about SPE, but most Python modules I've installed can
> >be uninstalled from control panel/add remove programs.
>
> SPE doesn't show up on my win XP add/remove programs list.
>
> Dick Moores

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


correction : Re: pygtk button event

2007-03-27 Thread [EMAIL PROTECTED]
Oups a small mistake:

bt=application.get_widget('button1')

[EMAIL PROTECTED] wrote:
> Hi
>
>
> i am trying to implement the following:
>
> I want to be able to press a button, perform a task and return a
> value.
>
> my button is named button1 and I used glade to build the gui.
>
> so, something like this should work
>
>
> application=gtk.glade.XML('app.glade','app')
> bt=app.get_widget('button1')
> bt.connect('clicked',on_btClicked)
> def on_btClicked(widget,event):
>   if data==0:
>  P=1
>   else:
>  P=2
>   return P
>
> How can I get P?
>
> Something like this doesn't work:
>
> bt.connect('clicked',P=on_btClicked)
>
> How can I return P???
>
>
> Thanks!
>
> Nick

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


Re: tkinter popup

2007-03-27 Thread Eric Brunel
On Tue, 27 Mar 2007 12:05:07 +0200, Gigs_ <[EMAIL PROTECTED]> wrote:

> Hi all
>
> I cant figure out how to disable resizing of my popup window?

myPopupWindow.wm_resizable(0, 0)

It may or may not make resize controls disappear depending on your  
platform and/or window manager. But the resizing will be impossible in any  
case.

> How to put this popup window to show in the middle of my text editor?
> It is writen with Toplevel.

A bit trickier. For example (untested):

myPopupWindow.after_idle(centerPopupWindow)

with:

def centerPopupWindow():
   x, y = editorWindow.winfo_rootx(), editorWindow.winfo_rooty()
   w, h = editorWindow.winfo_width(), editorWindow.winfo_height()
   ww, hh = myPopupWindow.winfo_width(), myPopupWindow.winfo_height()
   myPopupWindow.geometry('%sx%s+%s+%s', ww, hh, x + w/2 - ww/2, y + h/2 -  
hh/2)

The after_idle trick is needed since the dimensions for the popup window  
will only be known when the window is actually displayed. In theory,  
myPopupWindow.update_idletasks() should update the display so that the  
window dimensions are known, but there are cases where it doesn't work. So  
the after_idle trick is surer.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fortran vs Python - Newbie Question

2007-03-27 Thread Cameron Laird
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?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter MVC

2007-03-27 Thread Eric Brunel
On Tue, 27 Mar 2007 13:29:25 +0200, Gigs_ <[EMAIL PROTECTED]> wrote:

> Can someone give me example how to write text editor in tkintter with  
> model-view-controler?
> What goes to controler and what goes to model?
>
> thanks in advance

Others may have a different opinion, but I think using MVC to do a text  
editor is a bit overkill. Basically, the only operation needed on the  
model are reading and writing of the file, so a basic Python file object  
will be OK. Considering that, and since the Tkinter Text widget is  
basically already a full-featured text editor, the controller part is also  
quite limited. You could do it however, but it would just be a matter of  
moving the methods called by the bindings to a secondary class. If what  
you're doing is just a text editor, it may not be worth the effort.

Having an MVC architecture for a text editor may be a good idea if the  
file objects have to interact with other objects at a "functional" level,  
i.e without any impact on the GUI. If what you're doing is only a text  
editor, i.e only managing text files, the advantages of such an  
architecture won't really show up...

My [$£€¥]0.02...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: shutil.copy Problem

2007-03-27 Thread Facundo Batista
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,

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


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


Re: PMW widget - skip tabbing to it

2007-03-27 Thread jp
On Mar 26, 5:41 pm, John McMonagle <[EMAIL PROTECTED]> wrote:
> jp wrote:
> >>> On Mar 26, 10:51 am, "jp" <[EMAIL PROTECTED]> wrote:
>  I have multiple PMW widgets (EntryFields, ScrolledField etc), how can
>  I skip over these widgets when using the tab key?
>  Thank you,
>  John
>
> What version of Pmw are you using ?  Tabbing between widgets works fine
> on my system (Pmw 1.2,  tk 8.4, KDE)
>
> I can change the focus behaviour by using the takefocus option.  You
> were on the right track, you just did it wrong (see code below):
>
> 
> from Tkinter import *
> import Pmw
>
> root = Tk()
> entry = Pmw.EntryField(root, labelpos=W, value="", label_text='Name:')
> entry.grid(row=1)
> entry.component('entry').configure(takefocus=0)
>
> Button(root,text='test1').grid(row=2)
> Button(root,text='test2').grid(row=3)
> Button(root,text='test3').grid(row=4)
>
> root.mainloop()
> #
>
> Regards,
>
> John


Thank you for pointing out my error, John and James.  I had the syntax
of the command messed up.  Using the following does cause the field to
be skipped when tabbing:
entry.component('entry').configure(takefocus=0)

John

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


Python Error :(

2007-03-27 Thread Legend
I wasn't able to run a Python script. But then later I was able to run
it through the Shell. I was experimenting with cron jobs and set up
the python execution in as a cron. The first time it ran, It was fine
but then after that, it started giving me some errors. Now when I try
to run the script directly, I get the following error:



Traceback (most recent call last):
  File "", line 1, in ?
  File "userbot.py", line 637, in ?
con = connect()
  File "userbot.py", line 607, in connect
con.requestRoster()
  File "user.py", line 531, in requestRoster
self.SendAndWaitForResponse(rost_iq)
  File "user.py", line 326, in SendAndWaitForResponse
return self.waitForResponse(ID)
  File "user.py", line 300, in waitForResponse
self.process(1)
  File "xmlstream.py", line 459, in process
if not len(self.read()): # length of 0 means disconnect
  File "xmlstream.py", line 398, in read
data_in=data_in+self._sslObj.read(BLOCK_SIZE).decode('utf-8')
socket.sslerror: (6, 'TLS/SSL connection has been closed')


Any help please?

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


Re: tkinter popup

2007-03-27 Thread Gigs_
Eric Brunel wrote:
> On Tue, 27 Mar 2007 12:05:07 +0200, Gigs_ <[EMAIL PROTECTED]> wrote:
> 
>> Hi all
>>
>> I cant figure out how to disable resizing of my popup window?
> 
> myPopupWindow.wm_resizable(0, 0)
> 
> It may or may not make resize controls disappear depending on your 
> platform and/or window manager. But the resizing will be impossible in 
> any case.
> 
>> How to put this popup window to show in the middle of my text editor?
>> It is writen with Toplevel.
> 
> A bit trickier. For example (untested):
> 
> myPopupWindow.after_idle(centerPopupWindow)
> 
> with:
> 
> def centerPopupWindow():
>   x, y = editorWindow.winfo_rootx(), editorWindow.winfo_rooty()
>   w, h = editorWindow.winfo_width(), editorWindow.winfo_height()
>   ww, hh = myPopupWindow.winfo_width(), myPopupWindow.winfo_height()
>   myPopupWindow.geometry('%sx%s+%s+%s', ww, hh, x + w/2 - ww/2, y + h/2 
> - hh/2)
> 
> The after_idle trick is needed since the dimensions for the popup window 
> will only be known when the window is actually displayed. In theory, 
> myPopupWindow.update_idletasks() should update the display so that the 
> window dimensions are known, but there are cases where it doesn't work. 
> So the after_idle trick is surer.
> 
> HTH
> --python -c "print ''.join([chr(154 - ord(c)) for c in 
> 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"

thanks for both replay, they are very helpful. specially this one, it 
will took some times for me to figure this. i was completely forgot that 
this can be done like that

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


Re: Mastering Python

2007-03-27 Thread Bruno Desthuilliers
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:
> 
>> It will actually do something: rebind name 'a' to the method lower() of 
>> the string previously binded to 'a'
>>
>   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.

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


socket read timeout

2007-03-27 Thread hg
Hi,

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)

Tanks,

hg

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


Re: Python Error :(

2007-03-27 Thread Jarek Zgoda
Legend napisał(a):

> I wasn't able to run a Python script. But then later I was able to run
> it through the Shell. I was experimenting with cron jobs and set up
> the python execution in as a cron. The first time it ran, It was fine
> but then after that, it started giving me some errors. Now when I try
> to run the script directly, I get the following error:
> 
> 
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "userbot.py", line 637, in ?
> con = connect()
>   File "userbot.py", line 607, in connect
> con.requestRoster()
>   File "user.py", line 531, in requestRoster
> self.SendAndWaitForResponse(rost_iq)
>   File "user.py", line 326, in SendAndWaitForResponse
> return self.waitForResponse(ID)
>   File "user.py", line 300, in waitForResponse
> self.process(1)
>   File "xmlstream.py", line 459, in process
> if not len(self.read()): # length of 0 means disconnect
>   File "xmlstream.py", line 398, in read
> data_in=data_in+self._sslObj.read(BLOCK_SIZE).decode('utf-8')
> socket.sslerror: (6, 'TLS/SSL connection has been closed')
> 
> 
> Any help please?

Yes.

-- 
Jarek Zgoda

"We read Knuth so you don't have to."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket read timeout

2007-03-27 Thread Jarek Zgoda
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 ?

-- 
Jarek Zgoda

"We read Knuth so you don't have to."
-- 
http://mail.python.org/mailman/listinfo/python-list


Modules & positive surprises

2007-03-27 Thread Jan Danielsson
Hello all,



   Although I have encountered many modules that have impressed me with
regards to what they can actually do -- too be perfectly honest, it's
very rare that I become impressed by the _interfaces_ to the modules.

   Using a new module is normally, with my - admittedly - limited
experience, a pain. It's not just about reading the reference material,
and then just use it. You have to figure out how the developer who wrote
the module was thinking. Often there's a (more or less) natural way to
do things, and unfortunately that's not how module developers do it.
It's not a major issue to me personally, since the important part is
that the module can perform its function.

   But then there are a few modules that I just love to use, because
they are so "clean" from interface to function. Among them I can't help
mentioning optparse.

   Yesterday I found another module which I fell in love with: Python
Cryptography Toolkit (http://www.amk.ca/python/writing/pycrypt/).

   It's just so ... elegant, and functional.



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


Re: Modules & positive surprises

2007-03-27 Thread kyosohma
On Mar 27, 8:30 am, Jan Danielsson <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> 
>
>Although I have encountered many modules that have impressed me with
> regards to what they can actually do -- too be perfectly honest, it's
> very rare that I become impressed by the _interfaces_ to the modules.
>
>Using a new module is normally, with my - admittedly - limited
> experience, a pain. It's not just about reading the reference material,
> and then just use it. You have to figure out how the developer who wrote
> the module was thinking. Often there's a (more or less) natural way to
> do things, and unfortunately that's not how module developers do it.
> It's not a major issue to me personally, since the important part is
> that the module can perform its function.
>
>But then there are a few modules that I just love to use, because
> they are so "clean" from interface to function. Among them I can't help
> mentioning optparse.
>
>Yesterday I found another module which I fell in love with: Python
> Cryptography Toolkit (http://www.amk.ca/python/writing/pycrypt/).
>
>It's just so ... elegant, and functional.
>
> 
>
> --
> Kind regards,
> Jan Danielsson

Yeah. I've noticed that myself. There are tons of good modules, but a
lot of the docs are lousy. What's really annoying is that everyone
says that so-and-so is well documented. I love Python, but I wish when
they said some module was well documented, they meant that the docs
were understandable (to n00bs) as well.

Mike

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


Re: socket read timeout

2007-03-27 Thread Steve Holden
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

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


Re: Python Error :(

2007-03-27 Thread kyosohma
On Mar 27, 8:19 am, "Legend" <[EMAIL PROTECTED]> wrote:
> I wasn't able to run a Python script. But then later I was able to run
> it through the Shell. I was experimenting with cron jobs and set up
> the python execution in as a cron. The first time it ran, It was fine
> but then after that, it started giving me some errors. Now when I try
> to run the script directly, I get the following error:
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "userbot.py", line 637, in ?
> con = connect()
>   File "userbot.py", line 607, in connect
> con.requestRoster()
>   File "user.py", line 531, in requestRoster
> self.SendAndWaitForResponse(rost_iq)
>   File "user.py", line 326, in SendAndWaitForResponse
> return self.waitForResponse(ID)
>   File "user.py", line 300, in waitForResponse
> self.process(1)
>   File "xmlstream.py", line 459, in process
> if not len(self.read()): # length of 0 means disconnect
>   File "xmlstream.py", line 398, in read
> data_in=data_in+self._sslObj.read(BLOCK_SIZE).decode('utf-8')
> socket.sslerror: (6, 'TLS/SSL connection has been closed')
>
> Any help please?

I'll hazard a guess: Are you opening the socket explicitly when you
run this script?  If not, be sure to do so. And when you are finished
doing whatever it is you're doing, be sure to close it as well. You
may need to put in some kind of logic to check if the socket is still
open if you are transferring large files.

Mike

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


Re: enumerating processes

2007-03-27 Thread kyosohma
On Mar 27, 12:15 am, Shane Geiger <[EMAIL PROTECTED]> wrote:
> I believe you are looking for os.getpid()
>
> 李现民 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
>
>  sgeiger.vcf
> 1KDownload

You can also use Golden's WMI to grab a list. As I understand it, the
WMI module relies on the win32 modules, but it's a nice wrapper. Check
out the cookbook at:

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

Mike

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

Use threads or Tkinter event loop?

2007-03-27 Thread Kevin Walzer
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?

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use threads or Tkinter event loop?

2007-03-27 Thread Kevin Walzer
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 Kevin
http://www.codebykevin.com
-- 
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


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


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


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


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


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


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


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


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


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

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


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


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


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


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


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


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


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


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


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


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


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


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


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

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


  1   2   >