Pydev 1.3.1 Released

2007-03-27 Thread Fabio Zadrozny

Hi All,

Pydev and Pydev Extensions 1.3.1 have been released

Details on Pydev Extensions: http://www.fabioz.com/pydev
Details on Pydev: http://pydev.sf.net
Details on its development: http://pydev.blogspot.com

Release Highlights in Pydev Extensions:
-

* Interactive Console: jython process can receive vmargs (configured in the
preferences page)
* Code-Completion: auto-import completions will not be brought for tokens in
the current module
* Code-Completion: auto-import inserted as last import in imports list (so,
__future__ imports will remain in the 1st position)
* Code-Analysis: Only adds unused parameters in methods that have some
statement that is not a 'pass' or string
* Fix: Find Occurrences: will not 'overlap' occurrences anymore
* Fix: Code-Analysis: deep attribute access after finding __getattr__ does
not signal unresolved import errors anymore

Release Highlights in Pydev:
--

* Mylar integration: the pydev package explorer now supports mylar (packaged
as a separate feature: org.python.pydev.mylar.feature)
* Code-completion: comment completion is now the same as string completion
* Debug: Breakpoints can be set in external files
* Debug: Breakpoint annotations now show in external files
* Package Explorer: filter for import nodes created
* Fix: Package Explorer Actions: Open action does not expand children when
opening python file
* Fix: Project Explorer (WTP) integration: does not conflict with elements
from other plugins anymore (such as java projects)
* Fix: halt in new project wizard: when creating a new project from the
pydev wizard it was halting in some platforms
* Fix: ${string_prompt} in run config: now only evaluated on the actual run
* Fix: Code-Completion: jython shell was not handling
java.lang.NoClassDefFoundError correctly


What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python and Jython
development -- making Eclipse a first class Python IDE -- It comes with many
goodies such as code completion, syntax highlighting, syntax analysis,
refactor, debug and many others.


Cheers,

--
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Elixir 0.3.0 released!

2007-03-27 Thread Gaetan de Menten
We are pleased to announce that version 0.3.0 of Elixir is now
available. As always, feedback is very welcome, preferably on Elixir
mailing list.

Highlights for this release
-

- Added support for autoloading/reflecting databases with
 has_and_belongs_to_many relationships. See the docs for details.
- Added support for the version_id_col option on entities. This option adds
 a column to the table which will be used to prevent concurrent modifications
 on any row of the entity's table (i.e. it will raise an error if it happens).
- Added an ondelete argument to belongs_to relationships.
- The tablename option can now be given a callable so that people can provide
 their own function to get the table name for an entity.
- Made the provided metadata not threadlocal. This could break things for you
 in some rare case. Please see the (newly created) FAQ file for details about
 this.

- Fixed bug preventing having entities without any statement.
- Fixed typo which broke the use_alter argument on belongs_to relationships.

The full list of changes can be seen at:
http://elixir.ematia.de/svn/elixir/tags/0.3.0/CHANGES

What is Elixir?
-

Elixir is a declarative layer on top of SQLAlchemy. It is a fairly
thin wrapper, which provides the ability to define model objects
following the Active Record design pattern, and using a DSL syntax
similar to that of the Ruby on Rails ActiveRecord system.

Elixir does not intend to replace SQLAlchemy's core features, but
instead focuses on providing a simpler syntax for defining model
objects when you do not need the full expressiveness of SQLAlchemy's
manual mapper definitions.

Mailing list


http://groups.google.com/group/sqlelixir/about


-- 
Gaëtan de Menten
http://openhex.org
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


python-cjson 1.0.3x2 released

2007-03-27 Thread Ferenczi Viktor
This is an enhanced version of python-cjson, the fast JSON encoder/decoder.

Qiangning Hong submitted a patch to fix segfault with Python 2.5 on 64 bit
platforms. Version python-cjson 1.0.3x2 released to incorporate this patch.

It's numbered 1.0.3x, where x stands for eXtension.

The main improvement is the ability to extend the JSON encoder and decoder
with extensions functions to serialize/unserialize objects not in the
original JSON specification. This is achieved without sacrificing the speed
and stability of the original implementation. Please send bug reports to
[EMAIL PROTECTED] and do not contact the original author (Dan Pascu) about this
version.

Download and more information:
http://cx.hu/python-cjson/

Example to encode/decode python date objects as JavaScript Date:

import re
import cjson
import datetime

# Encoding Date objects:
def dateEncoder(d):
assert isinstance(d, datetime.date)
return 'new Date(Date.UTC(%d,%d,%d))'%(d.year, d.month, d.day)

json=cjson.encode([1,datetime.date(2007,1,2),2], extension=dateEncoder)
assert json=='[1, new Date(Date.UTC(2007,1,2)), 2]'

# Decoding Date objects:
re_date=re.compile('^new\sDate\(Date\.UTC\(.*?\)\)')
def dateDecoder(json,idx):
json=json[idx:]
m=re_date.match(json)
if not m: raise 'cannot parse JSON string as Date object: %s'%json[idx:]
args=cjson.decode('[%s]'%json[18:m.end()-2])
dt=datetime.date(*args)
return (dt,m.end()) # must return (object, character_count) tuple

data=cjson.decode('[1, new Date(Date.UTC(2007,1,2)), 2]',
extension=dateDecoder)
assert data==[1,datetime.date(2007,1,2),2]

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


ANN: python-ldap-2.3.0

2007-03-27 Thread Michael Ströder
Find a new release of python-ldap:

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

python-ldap provides an object-oriented API to access LDAP directory
servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for
that purpose. Additionally it contains modules for other LDAP-related
stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema).


Released 2.3.0 2007-03-27

Changes since 2.2.1:

* OpenLDAP 2.3+ required now to build.
* Added support for Cancel operation ext. op. if supported
in OpenLDAP API of the libs used for the build.

Modules/
* Removed deprecated code for setting options by name
* Added l_ldap_cancel()
* Some modifications related to PEP 353 for
  Python 2.5 on 64-bit platforms (see SF#1467529, thanks to Matej)
* Added new function l_ldap_str2dn(), removed functions
  l_ldap_explode_dn() and l_ldap_explode_rdn()
  (see SF#1657848, thanks to David)

Lib/
* Added method ldapobject.LDAPObject.cancel()
* ldap.schema.subentry.urlfetch() now can do non-anonymous
  simple bind if the LDAP URL provided contains extensions
  'bindname' and 'X-BINDPW'. (see SF#1589206)
* ldap.filter.escape_filter_chars() has new a key-word argument
  escape_mode now which defines which chars to be escaped
  (see SF#1193271).
* Various important fixes to ldapobject.ReconnectLDAPObject
* Moved all DN-related functions to sub-module ldap.dn,
  import them in ldap.functions for backward compability
* ldap.dn.explode_dn() and ldap.dn.explode_rdn() use the new
  wrapper function ldap.dn.str2dn() (related to SF#1657848)
* changetype issue partially fixed (see SF#1683746)

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: with timeout(...):

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


 Nick Craig-Wood 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!
 
 Cross platform isn't the issue here - reliability though is. To put it
 simple: can't be done that way. You could of course add a timer to the
 python bytecode core, that would jump back to a stored savepoint or
 something like that.
 
 But to make that work reliably, it has to be ensured that no sideeffects
 occur while being in some_long_running_stuff. which doesn't only extend to
 python itself, but also external modules and systems (file writing, network
 communications...). Which can't be done, unless you use a time-machine.
 Which I'd take as an personal insult, because in that rolled-back timeframe
 I will be possibly proposing to my future wife or something...
 

how does the timed callback in the Tkinter stuff work - in my experience so 
far it seems that it does the timed callback quite reliably...

probably has to do with the fact that the mainloop runs as a stand alone 
process, and that you set the timer up when you do the after call.

so it probably means that to emulate that kind of thing you need a 
separate thread that is in a loop to monitor the timer's expiry, that 
somehow gains control from the long running stuff periodically...

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

- Hendrik




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


Re: shutil.copy Problem

2007-03-27 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], David Nicolson
wrote:

 Hi,
 
 I wasn't exactly sure where to send this, I don't know if it is a bug  
 in Python or not. This is rare, but it has occurred a few times and  
 seems to be reproducible for those who experience it.
 
 Examine this code:
   try:
   shutil.copy(/file.xml,/Volumes/External/file.xml)
   except Exception, err:
   print sys.exc_info()[0]
   print err
 
 This is the output:
 exceptions.UnicodeDecodeError
 'ascii' codec can't decode byte 0xd6 in position 26: ordinal not in  
 range(128)]
 
 What could the possible cause of this be? Shouldn't shutil simply be  
 reading and writing the bytes and not character decoding them?

Do you really get this error from the code above or just in the real
program?  Are the paths hard coded in the real program too?

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 Duncan Booth
Chris Lasher [EMAIL PROTECTED] wrote:

 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 line number command. I
 experience the same behavior with Winpdb and rpdb2. Why is this?
 

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)module()
- a = 1
(Pdb) s
 c:\temp\t.py(4)module()
- b = 2
(Pdb) j 3
 c:\temp\t.py(3)module()
- a = 1
(Pdb)
-- 
http://mail.python.org/mailman/listinfo/python-list


Nice plug for Python

2007-03-27 Thread Ant
Sourceforge's Project of the Month (an IT monitoring system written
using Zope and Twisted) is a good advert for Python:
http://sourceforge.net/potm/potm-2007-03.php

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


[ANN] python-gastables : Python modules for Compressible Gas Flow Calculations

2007-03-27 Thread Venkattraman A

Hello Pythoners! I would like to announce the first release of a Gas table
module for Python, to perform compressible flow calculations.

python-gastables includes python modules for compressible gas flow
calculations. It includes python modules for Isentropic Relations, Normal
Shock Relations, Oblique Shock Relations, Fanno Flow, Isothermal Flow,
Rayleigh Flow and Prandtl Meyer Functions.

Find it at: http://sourceforge.net/projects/gastables

Comments, suggestions and feedback is welcome.
--
A.Venkattraman
Undergraduate Student
Department of Aerospace Engineering
Indian Institute of Technology Madras
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PDB does not allow jumping to first statement?

2007-03-27 Thread Peter Otten
Duncan Booth wrote:

 Chris Lasher [EMAIL PROTECTED] wrote:
 
 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 line number command. I
 experience the same behavior with Winpdb and rpdb2. Why is this?
 
 
 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)module()
 - a = 1
 (Pdb) s
 c:\temp\t.py(4)module()
 - b = 2
 (Pdb) j 3
 c:\temp\t.py(3)module()
 - a = 1
 (Pdb)

It looks like you successfully jumped to the first line, but it will be
skipped if you try to execute it:

$ cat tmp.py
print aaa
print bbb
print ccc
print ddd
$ python2.5 -m pdb tmp.py
 /home/nn/tmp.py(1)module()
- print aaa
(Pdb) s
aaa
 /home/nn/tmp.py(2)module()
- print bbb
(Pdb) j 1
 /home/nn/tmp.py(1)module()
- print aaa
(Pdb) s
bbb -- wrong
 /home/nn/tmp.py(3)module()
- print ccc
(Pdb) s
ccc
 /home/nn/tmp.py(4)module()
- print ddd
(Pdb) j 2
 /home/nn/tmp.py(2)module()
- print bbb
(Pdb) s
bbb -- correct
 /home/nn/tmp.py(3)module()
- print ccc

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


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 That took,elapsed,seconds for timeout of,t_limit

def test():
Test code

# no nesting

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 
 URL: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 grahn@Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org  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)module()
 - a = 1
 (Pdb) s
 c:\temp\t.py(4)module()
 - b = 2
 (Pdb) j 3
 c:\temp\t.py(3)module()
 - 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)module()
- a = 1
(Pdb) s
 c:\temp\t.py(4)module()
- b = 2
(Pdb) s
 c:\temp\t.py(5)module()
- 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)module()
- b = 2
(Pdb) j 3
f_lineno 4 f_lasti 6
 c:\temp\t.py(3)module()
- a = 1
(Pdb) j 5
f_lineno 5 f_lasti 12
 c:\temp\t.py(5)module()
- a = 3
(Pdb) j 3
f_lineno 4 f_lasti 6
 c:\temp\t.py(3)module()
- 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 line number 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 grahn@Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org  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 stdin, 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 stdin, 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,

IMHO

   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.

/IMHO

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

 IMHO

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.

 /IMHO

 --
 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 stdin, 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] mailto:[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 panelAdd/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] mailto:[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 Boost.Python.ArgumentError instance

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 BW (L) then it 
*does* display an image, the BW 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 BW (L) then 
 it *does* display an image, the BW 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


  1   2   >