Version 2.3 of mod_wsgi is now available.

2008-08-25 Thread Graham Dumpleton
Version 2.3 of mod_wsgi is now available. The software and
documentation are both available from:

  http://www.modwsgi.org

The mod_wsgi package consists of an Apache web server module designed
and implemented specifically for hosting Python based web applications
that support the WSGI interface specification.

Examples of major Python web frameworks and applications which are
known to work in conjunction with mod_wsgi include CherryPy, Django,
MoinMoin, Pylons, Trac, TurboGears, Werkzeug and Zope.

Version 2.3 of mod_wsgi is a bug fix update. The most important of the
bug fixes addresses a data truncation issue when using
wsgi.file_wrapper extension (on Windows or Apache 1.3 on UNIX) with
file objects. Data truncation could also occur for all deployment
configurations for any other file like objects used with
wsgi.file_wrapper.

It is highly recommended that if you are using version 2.0 or 2.1 of
mod_wsgi that you upgrade, especially if using web applications such
as Trac, which make use of the wsgi.file_wrapper extension.

Note that version 2.3 of mod_wsgi was a quick fire release to fix
issues caused in version 2.2 release which preceded 2.3 by a day or
so. If you have already obtained version 2.2 of mod_wsgi, you should
ensure you upgrade to version 2.3.

A description of changes in version 2.2/2.3 can be found in the change
notes at:

  http://code.google.com/p/modwsgi/wiki/ChangesInVersion0202
  http://code.google.com/p/modwsgi/wiki/ChangesInVersion0203

If you have any questions about mod_wsgi or wish to provide feedback,
use the Google group for mod_wsgi found at:

  http://groups.google.com/group/modwsgi

Enjoy

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

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


ANN: Leo 4.5 beta 4 released

2008-08-25 Thread Edward K Ream
Leo 4.5 beta 4 is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106

This beta 4 release will likely be the last release before Leo 4.5 final.

Leo 4.5 contains many important new features.  See below for details.

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.5:
--

- Full support for @shadow files in Leo's core.
- Major improvements to Leo's key binding code.
- The beginning of usable vim-like bindings.
- uA's may now be associated with vnodes in @thin and @shadow files.
- Several magor reorganizations of Leo's code:
  including sax-based parsing, support for the Graph world (unified nodes),
  simplified drawing code.
- Leo is now an installable package.
- Prepared code to be ready for Python 3.0.
- Many small improvements and bug fixes.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Forum:http://groups.google.com/group/leo-editor
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
Bzr:  http://code.launchpad.net/leo-editor/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html


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

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


Elisa Media Center 0.5.7 Release

2008-08-25 Thread Olivier Tilloy
Dear Elisa users,

The Elisa team is happy to announce the release of Elisa Media Center
0.5.7 codenamed The Tipping Point.

This release fixes a handful of bugs and enhances the current user
experience with the following new features:

- Add Folders now allows you to browse all your devices (including
external hard drives), not just your home folder as it was before.
- Better feedback from the media scanner: it now informs you what is
being scanned and the overall progress as a percentage.

Installers and sources can be downloaded from
http://elisa.fluendo.com/download/

Bug reports and feature requests are welcome at
https://bugs.launchpad.net/elisa/+filebug


Have a nice night/day,

The Elisa team
Elisa 0.5.7 The Tipping Point
===

This is Elisa 0.5.7, seventh release of the 0.5 branch.

New features since 0.5.6:

- Add Folders now allows you to browse all your devices (including external
  hard drives), not just your home folder as it was before.
- Better feedback from the media scanner: it now informs you what is being
  scanned and the overall progress as a percentage.

Bugs fixed since 0.5.6:

- 257645: Seeking an audio playlist skip songs
- 257691: Contextual actions not accessible with the keyboard in grid view mode
- 259092: [win32] Streamzap and apple remotes do not work
- 259428: Debian package needs to depend on python-cssutils
- 249883: plugins configs not saved


Download

You can find source releases of Elisa on the download page:
http://elisa.fluendo.com/download


Elisa Homepage

More details can be found on the project's website: http://elisa.fluendo.com


Support and Bugs

We use Launchpad for bug reports and feature requests:
https://bugs.launchpad.net/elisa/+filebug


Developers

All code is in a Bazaar branch and can be checked out from there.
It is hosted on Launchpad: https://code.launchpad.net/elisa


Contributors to this release:

- Alessandro Decina
- Benjamin Kampmann
- David McLeod
- Florian Boucault
- Guido Amoruso
- Guillaume Emont
- Gunnar Holmberg
- Jesús Corrius
- Joshua Eichen
- Lionel Martin
- Olivier Tilloy
- Philippe Normand
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: Interrupt python thread

2008-08-25 Thread Fredrik Lundh

James Matthews wrote:


def __stop(self):
self.__block.acquire()
self.__stopped = True
self.__block.notifyAll()
self.__block.release()


have you tried using that method?  what happened?  looking at the code, 
what do you think it does?


/F

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


Re: How to check in CGI if client disconnected

2008-08-25 Thread Vishal
Hi,

  Thanks for the replies. In my case, the cgi is sending a large file
to the client. In case the the stop button is pressed on the browser
to cancel the download, i want to do some cleanup action. It's all one-
way transfer in this case, so i can't expect the client to send
anything to me. I read somewhere that apache sends the SIGTERM signal
to a cgi when the client disconnects. However, my cgi is not getting
the signal - is there a way to have the cgi catch and handle the
SIGTERM?

I tried using the signal module

---
def sigtermHandler(signum, frame):
# do some cleanup

signal.signal(signal.SIGTERM, sigtermHandler)

---

But even this doesn't work.

Regards,

-vishal.
On Aug 25, 2:58 am, Gabriel Genellina [EMAIL PROTECTED]
wrote:
 En Sun, 24 Aug 2008 17:51:36 -0300, Wojtek Walczak [EMAIL PROTECTED] 
 escribió:

  On Sun, 24 Aug 2008 17:21:52 -0300, Gabriel Genellina wrote:
     I am writing a CGI to serve files to the caller. I was wondering if
  there is any way to tell in my CGI if the client browser is still
  connected. If it is not, i want to execute some special code before
  exiting.

     Is there any way to do this? Any help on this is appreciated :)

  I don't think so. A CGI script runs once per request, and exits. The 
  server may find that client disconnected, but that may happen after the 
  script finished.

  I am not a web developer, but I think that the only way is to
  set a timeout on server side. You can't be sure that the client
  disconnected, but you can stop CGI script if there's no
  action on client side for too long.

 Which kind of client action? Every link clicked or form submitted generates a 
 different request that triggers a CGI script; the script starts, reads its 
 parameters, do its task, and exits. There is no long running process in CGI 
 - the whole world must be recreated on each request (a total waste of 
 resources, sure).

 If processing takes so much time, it's better to assign it a ticket - the 
 user may come back later and see if its ticket has been finished, or the 
 system may send an email telling him.

 --
 Gabriel Genellina

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


Re: How to check in CGI if client disconnected

2008-08-25 Thread Graham Dumpleton
On Aug 25, 4:26 pm, Vishal [EMAIL PROTECTED] wrote:
 Hi,

   Thanks for the replies. In my case, the cgi is sending a large file
 to the client. In case the the stop button is pressed on the browser
 to cancel the download, i want to do some cleanup action. It's all one-
 way transfer in this case, so i can't expect the client to send
 anything to me. I read somewhere that apache sends the SIGTERM signal
 to a cgi when the client disconnects. However, my cgi is not getting
 the signal - is there a way to have the cgi catch and handle the
 SIGTERM?

 I tried using the signal module

 ---
 def sigtermHandler(signum, frame):
     # do some cleanup

 signal.signal(signal.SIGTERM, sigtermHandler)

 ---

 But even this doesn't work.

Have you considered simply checking to see if the amount of POST
content read matches the inbound Content-Length specified in the CGI
environment. If your processing of POST content finds less than what
was meant to be sent, then likely that the client browser aborted
request before all content could be sent.

Graham

 Regards,

 -vishal.
 On Aug 25, 2:58 am, Gabriel Genellina [EMAIL PROTECTED]
 wrote:

  En Sun, 24 Aug 2008 17:51:36 -0300, Wojtek Walczak [EMAIL PROTECTED] 
  escribió:

   On Sun, 24 Aug 2008 17:21:52 -0300, Gabriel Genellina wrote:
      I am writing a CGI to serve files to the caller. I was wondering if
   there is any way to tell in my CGI if the client browser is still
   connected. If it is not, i want to execute some special code before
   exiting.

      Is there any way to do this? Any help on this is appreciated :)

   I don't think so. A CGI script runs once per request, and exits. The 
   server may find that client disconnected, but that may happen after the 
   script finished.

   I am not a web developer, but I think that the only way is to
   set a timeout on server side. You can't be sure that the client
   disconnected, but you can stop CGI script if there's no
   action on client side for too long.

  Which kind of client action? Every link clicked or form submitted generates 
  a different request that triggers a CGI script; the script starts, reads 
  its parameters, do its task, and exits. There is no long running process 
  in CGI - the whole world must be recreated on each request (a total waste 
  of resources, sure).

  If processing takes so much time, it's better to assign it a ticket - the 
  user may come back later and see if its ticket has been finished, or the 
  system may send an email telling him.

  --
  Gabriel Genellina

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


Re: Best way to set/get an object property

2008-08-25 Thread Hussein B
On Aug 24, 7:12 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Sun, 24 Aug 2008 12:28:53 +0200, Peter Otten wrote:
  Hussein B wrote:

  I noted that Python encourage the usage of: --
  obj.prop = data
  x = obj.prop
  --
  to set/get an object's property value. What if I want to run some logic
  upon setting/getting a property? What is Python preferred method to do
  so (using the new feature 'property')?
  I don't think __getattr__ and __setattr__ are practical (I have to code
  the property name into them).

  Hussein, I don't think you'll learn much from asking these abstract
  questions. At some point you have to get your hands dirty and write
  actual code to get a feel for the language.

  For example, it will then become obvious for you that property works
  best for individual attributes while __getattr__ and friends are more
  convenient if you want to treat multiple attributes the same way,
  attributes whose names may not even be known until runtime (think
  delegation).

 I think you are misunderstanding Hussein's question. I believe that he is
 using property to refer to what we would call an attribute. Naturally I
 could be wrong, but this is how I interpret his question.

 I think the actual answer to his question is that properties are the
 preferred way to run some logic upon setting/getting an attribute, that
 is, to implement getters and setters.

 Hussein, the Java habit of writing setters and getters for everything
 isn't considered good practice in Python, but if you need them, that's
 exactly what the property() function is for.

 --
 Steven

Thank you Steven :)
--
public class JClass {
  private int answer; // property
}
--
class PyClass(object):
  doc __init__(self):
self.answer = None
--
AFAIUY (understand you), what it is called a property in Java, it is
called an attribute in Python?
Why Python encourages direct access to object's attributes?  aren't
setters/getters considered vital in OOP (encapsulation)?
Thank you all for your time and help.
--
http://mail.python.org/mailman/listinfo/python-list


tkinter: Round Button - Any idea?

2008-08-25 Thread akineko
Hello everyone,

I'm trying to implement a virtual instrument, which has buttons and
displays, using Tkinter+Pmw.
One of items on the virtual instrument is a round button.
This is imitating a tact switch.

Tkinter has a Button class, which I can assign a button image.
However, when the button is depressed, the rectangle is sunken (rather
than the round button).

Probably I need to prepare two images, normal one and depressed one,
and implement all button behaviours by myself.
But before reinventing everything by myself, I'm wondering if there is
an easy way to implement or there is existing widget example of such
button.
So far, I couldn't find any good examples.

Any suggestions are highly appreciated.

Best regards,
Aki Niimura
--
http://mail.python.org/mailman/listinfo/python-list


Re: Interrupt python thread

2008-08-25 Thread janislaw
On 24 Sie, 10:48, BlueBird [EMAIL PROTECTED] wrote:

 Whenever an exception occurs, in the master thread or in one of the
 slave threads, I would like to interrupt all the threads and the main
 program. Threading API does not seem to provide a way to stop a
 thread, is there anyway to achieve that ?

Note that killing, stopping, suspending and resuming Your thread at
arbitrary time leads to unpredictable results. For this reason i.e.
Java deprecated all such functions, and python didn't introduce them
at all. It makes sense as it leads to better-designed-code.

Regards
JW


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


Re: Python cx_Oracle and Apache

2008-08-25 Thread Hrvoje Niksic
Raja [EMAIL PROTECTED] writes:

 The code is working fine on the command line but when executing it
 on the browser i get the famouse Premature end of script headers
 error.

Look at the server's error log to see what the real error message is.
You are probably missing an environment variable such as ORACLE_HOME.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check in CGI if client disconnected

2008-08-25 Thread Vishal
Hi Graham,

   Thanks for the reply. In my case, it's the other way round. I need
to check if the amount of data sent is equal to the file size i want
to send. However, the question is - when do i check this? Currently, i
am unable to call any cleanup code before exit.

Regards,

-vishal.

On Aug 25, 11:44 am, Graham Dumpleton [EMAIL PROTECTED]
wrote:
 On Aug 25, 4:26 pm, Vishal [EMAIL PROTECTED] wrote:



  Hi,

    Thanks for the replies. In my case, the cgi is sending a large file
  to the client. In case the the stop button is pressed on the browser
  to cancel the download, i want to do some cleanup action. It's all one-
  way transfer in this case, so i can't expect the client to send
  anything to me. I read somewhere that apache sends the SIGTERM signal
  to a cgi when the client disconnects. However, my cgi is not getting
  the signal - is there a way to have the cgi catch and handle the
  SIGTERM?

  I tried using the signal module

  ---
  def sigtermHandler(signum, frame):
      # do some cleanup

  signal.signal(signal.SIGTERM, sigtermHandler)

  ---

  But even this doesn't work.

 Have you considered simply checking to see if the amount of POST
 content read matches the inbound Content-Length specified in the CGI
 environment. If your processing of POST content finds less than what
 was meant to be sent, then likely that the client browser aborted
 request before all content could be sent.

 Graham

  Regards,

  -vishal.
  On Aug 25, 2:58 am, Gabriel Genellina [EMAIL PROTECTED]
  wrote:

   En Sun, 24 Aug 2008 17:51:36 -0300, Wojtek Walczak [EMAIL PROTECTED] 
   escribió:

On Sun, 24 Aug 2008 17:21:52 -0300, Gabriel Genellina wrote:
   I am writing a CGI to serve files to the caller. I was wondering if
there is any way to tell in my CGI if the client browser is still
connected. If it is not, i want to execute some special code before
exiting.

   Is there any way to do this? Any help on this is appreciated :)

I don't think so. A CGI script runs once per request, and exits. The 
server may find that client disconnected, but that may happen after 
the script finished.

I am not a web developer, but I think that the only way is to
set a timeout on server side. You can't be sure that the client
disconnected, but you can stop CGI script if there's no
action on client side for too long.

   Which kind of client action? Every link clicked or form submitted 
   generates a different request that triggers a CGI script; the script 
   starts, reads its parameters, do its task, and exits. There is no long 
   running process in CGI - the whole world must be recreated on each 
   request (a total waste of resources, sure).

   If processing takes so much time, it's better to assign it a ticket - 
   the user may come back later and see if its ticket has been finished, 
   or the system may send an email telling him.

   --
   Gabriel Genellina



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


Re: Interrupt python thread

2008-08-25 Thread BlueBird
On Aug 24, 8:35 pm, Dennis Lee Bieber [EMAIL PROTECTED] wrote:
 On Sun, 24 Aug 2008 01:48:46 -0700 (PDT), BlueBird
 [EMAIL PROTECTED] declaimed the following in comp.lang.python:



  Whenever an exception occurs, in the master thread or in one of the
  slave threads, I would like to interrupt all the threads and the main
  program. Threading API does not seem to provide a way to stop a
  thread, is there anyway to achieve that ?

         The only safe way to abort a thread is by having it exit on its
 own. This means one needs a means of setting an attribute that each
 thread periodically checks within a while loop.


Unfortunately, this does not map very well with my program. Each of my
threads are calling foreign code (still written in python though),
which might be busy for 1 to 10 minutes with its own job.

I wanted something to easily interrupt every thread to prevent my
program to stall for 10 minutes if I want to stop it (getting tired of
killing python all the time).

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


Re: Trouble importing modules in IDLE (Win32)

2008-08-25 Thread [EMAIL PROTECTED]
On Aug 22, 2:45 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] schrieb:



  Hello,

  I wrote aprogram that imports odbc and dbi. Originally I used PyWin,
  but now I prefer IDLE for working in Windows. Anyway, when I start my
  program from IDLE, it can't import the odbc and dbi modules. However,
  when I restart the shell and type import odbc at the prompt by, I
  don't get an error. When I try to run the program now, I get the error
  again. When I now type import odbc at the prompt, I get the error as
  well.

  In short:
  In a freshly (re)started shell, I can use import odbc by hand. I
  can't import odbc from within a script, or by hand after trying to
  start such a script. Screen capture follows.

  robert

   RESTART 
  import odbc # -no error here!
   RESTART 
  # script started here

  Traceback (most recent call last):
File H:\PythonProjekte\ADBExpress.py, line 1, in module
  import odbc
  ImportError: DLL load failed: Das angegebene Modul wurde nicht
  gefunden.

 In both shell and idle, do

   import sys
   print sys.prefix

 Most probably these differ, and you need to install the odbc-module to
 the python idle uses.

No, they're the same:

IDLE 1.2.2
 import sys
 print sys.prefix
C:\Python25


PythonWin 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin'
for further copyright information.
 import sys
 print sys.prefix
C:\Python25


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


Re: Trouble importing modules in IDLE (Win32)

2008-08-25 Thread [EMAIL PROTECTED]
On Aug 22, 10:43 pm, Terry Reedy [EMAIL PROTECTED] wrote:
 Diez B. Roggisch wrote:

 By shell, he means the IDLE shell.  But this is the direction to look
 first.  In the IDLE shell (3.0) those two lines give me the Python
 directory, the same as the command line interpreter.  When in a file
 that is *not* in that directory, ditto.

 Bob, if you run a file that consists of the one statement 'import odbc',
 what happens.  If that works, then something in your script (or
 something it calls) is fiddling with sys.path or something.  Try to find
 a *minimal* file that exhibits the problem.

 tjr

Hello Dietz,

1. The output of print sys.prefix is the same in both shells (see my
other posting).
2. The minimal file that exhibits the problem (in IDLE but not in
PythonWin) is one that consists of the single line import odbc.

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


Re: Python String Immutability Broken!

2008-08-25 Thread Hendrik van Rooyen
 
Patrick Maupin pmauail.com wrote:

Very entertaining.


Thanks. Nice to see that there is still some sense of humour
left somewhere - its all been so serious here lately - people
seem to forget that hacking is fun!

But let me get this straight:   Are you just complaining that if you
pass a string to an arbitrary C function using ctypes, that that
arbitrary function can modify the string?


Actually, I am not complaining - I am asking for advice on the side
effects of what I am doing, which is replacing a bunch of bits
in what is essentially an output bit field with the corresponding
input bits at the same addresses read back from a simulated i/o
bus structure.  And I would also like to know if there is a better
way of doing this.

The C code actually works, doing what was intended - the \xff that
one sees appearing back comes from the pullup resistors on the
eBox's i/o.  I can show that it is working by adding some resistance
and capacitance (by holding the connector against my tongue) in which
case I get a munged version of the fox back.  (- evidently my tongue
is not such a perfect communications medium as I would like to believe.)

Passing the fox is actually deceptive and misleading, as in real
use there would be no such correlation sideways across bits, as
they are just representations of output lines.
(Think coils in PLC jargon)

Because if you are, then I think you share a great deal of
responsibility for the death of that string -- sending the poor thing
to its grave through some unknown C function.

This string is NOT dead - it is alive, and not even stunned -
it just looks as if it is sleeping because of the \xff - which
comes from the fact that there is no real hardware out there yet.

The C functions are very simple ones actually - they just do
what are essentially Linux I/O system calls - setting direction
bits for a port (in or out) and then reading or writing the data.

- Hendrik



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


Re: Best way to set/get an object property

2008-08-25 Thread alex23
On Aug 25, 4:56 pm, Hussein B [EMAIL PROTECTED] wrote:
 AFAIUY (understand you), what it is called a property in Java, it is
 called an attribute in Python?
 Why Python encourages direct access to object's attributes?

The simplest answer is Because Python is not Java :)

Speaking of which, have you read the blog post of the same name? It
might be useful given your Java background: 
http://dirtsimple.org/2004/12/python-is-not-java.html

 aren't
 setters/getters considered vital in OOP (encapsulation)?

Not at all. They're definitely part of the mechanism that Java
provides for encapsulation, sure. However, because Python provides a
consistent interface for accessing attributes and properties, you
don't need to define a property unless your code requires it. If all
your getters  setters are doing is reading  writing to an attribute,
then why not just rw directly to the attribute? If you later need to
add more complexity to that process, you can easily create a property
without having to change how any other piece of code refers to that
property, given it shares the same interface with attributes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python cx_Oracle and Apache

2008-08-25 Thread Cousin Stanley

 

 def generate_output():
 print 'htmlbody/body/html'

 generate_output()

  Raja  

You might try adding a  Content-type  header followed by
a  blank line  to your  generate_output()  function 

def generate_output() : 
print 'Content-type:  text/html'
print  
print  rest of your html 


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


For loop inside an xml template

2008-08-25 Thread Amie
Hi,

Is it possible to have a for loop within an xml template?
--
http://mail.python.org/mailman/listinfo/python-list


Python Google Chart 0.2.1 released

2008-08-25 Thread Gerald Kaszuba
pygooglechart 0.2.1 has been released.

http://pygooglechart.slowchop.com/

Here are the changes:

 * Added support for QR Code chart (#8)
 * Added legend positioning (chdlp) (Steve Brandt)
 * Added line styles (chm=D) (Steve Brandt)
 * Added colours within series option to chart (chco=xxx|xxx) (Steve
Brandt)
 * Added QR codes and more line examples
 * Axis labels are now casted to strings automatically
 * Bug fixed where pie charts stopped working due to automatic scaling
 * Bug fixed where the module would download twice (#7) (Evan Lezar)
 * Bug fixed when automatic scaling is on and None values are in a
data set (#5) (Alec Thomas)
 * Bug fixed with auto-scaling, where the minimum y range was always
0. (#6) (Rohit Jenveja)
 * Bug fixed, replaced 1 with 0 in add_horizontal_range and
add_vertical_range (incorrect syntax for Google) (Steve Brandt)
 * Better clipping checks

I've also updated the home page with more examples.

Gerald

--
Gerald Kaszuba
http://geraldkaszuba.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to set/get an object property

2008-08-25 Thread Steven D'Aprano
On Sun, 24 Aug 2008 23:56:27 -0700, Hussein B wrote:

 On Aug 24, 7:12 pm, Steven D'Aprano [EMAIL PROTECTED]
 cybersource.com.au wrote:

  I noted that Python encourage the usage of: -- obj.prop = data
  x = obj.prop
  --
  to set/get an object's property value. What if I want to run some
  logic upon setting/getting a property? What is Python preferred
  method to do so (using the new feature 'property')? I don't think
  __getattr__ and __setattr__ are practical (I have to code the
  property name into them).
...
 I think the actual answer to his question is that properties are the
 preferred way to run some logic upon setting/getting an attribute,
 that is, to implement getters and setters.

 Hussein, the Java habit of writing setters and getters for everything
 isn't considered good practice in Python, but if you need them, that's
 exactly what the property() function is for.

 --
 Steven
 
 Thank you Steven :)
 --
 public class JClass {
   private int answer; // property
 }
 --
 class PyClass(object):
   doc __init__(self):
 self.answer = None
 --
 AFAIUY (understand you), what it is called a property in Java, it is
 called an attribute in Python?
 Why Python encourages direct access to object's attributes?  aren't
 setters/getters considered vital in OOP (encapsulation)?
 Thank you all for your time and help.


Hussein, first let me ask you to please stop using -- as a separator 
around code. Many News clients, including mine, expect -- on a line by 
itself to mean everything from here on is the writer's signature, and 
consequently that makes it harder to reply correctly to your posts. I had 
to manually copy and paste your text in order to quote it. Perhaps you 
could use === or +++ or ***  as a separator?


Now, back to your actual question... 

I'm not a Java coder, so the following should be read as my opinion. 
Python attributes are equivalent to Java _public_ properties, not 
private. If you can write:

public class JClass {
   public int answer;
}

then that would be more or less equivalent to Python's

class PyClass(object):
def __init__(self):
self.answer = None


Yes, Python does encourage direct access to an object's attributes. The 
Python philosophy is we're all adults here. If coders wish to shoot 
themselves in the foot by accessing clearly marked private attributes, 
then the language can't stop them and shouldn't try. It's easy to bypass 
such private/public protection in C++, and harder, but still possible, in 
Java.

The Python development team is certainly aware that such a tactic 
introduces some costs, by reducing encapsulation, but it also has many 
benefits (e.g. less boilerplate getter/setter methods, faster development 
time). It is their belief that such costs are worth paying in order to 
get the benefits. That's the philosophy of the language. Python is not 
trying to be Java, and Java should not try to be Python.

Python does not enforce private attributes. By convention attributes 
starting with a single underscore are considered private -- don't touch 
unless you know what you're doing. Attributes starting with a double 
underscore are really private, and Python mangles the name to (almost) 
enforce it.

Example:

def Parrot(object):
colour = 'red'  # public, free to use
_windspan = 15  # semi-private, use it at your own risk
__species = 'Norwegian Blue'  # mangled to _Parrot__species


But it's quite rare to see double-underscore really private attributes 
in Python code. It is considered to go against the spirit of the language.

I'm told that in Java it is quite difficult to change a class from using 
public attributes to getters/setters, and therefore many Java developers 
prefer to use getters/setters right from the beginning. But in Python it 
is very easy to change from a bare attribute to a computed property 
without messing up calling code. So there's no advantage to writing 
something like this:

class Foo(object):
def __init__(self):
self.__x = None  # private attribute
def setx(self, x):  # setter
self.__x = x
def getx(self):  # getter
return self.__x
x = property(getx, setx)


That is considered a waste of time in Python circles and is strongly 
discouraged.

You should read Python Is Not Java and Java Is Not Python Either:

http://dirtsimple.org/2004/12/python-is-not-java.html

http://dirtsimple.org/2004/12/java-is-not-python-either.html




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


generate methods at runtime, but the wrong one gets called

2008-08-25 Thread Steven Samuel Cole
Hello,

I am writing an application that controls robots. Different robots can
do different kinds of movements, such as e.g. open gripper, rotate
gripper, etc. My RobotControl class should support all kinds of
robots. I therefore delegate the actual control work to extra
control-specific classes, one class per movement type, e.g.
OpenGripperControl, RotateGripperControl. These movement control
classes are created by a simple class factory.

This is my class half-way through:

class RobotControl:

def __init__(self, movementTypes):
self.__controls = {}
motionControlFactory = MotionControlFactory()
for movementType in movementTypes:
self.__controls[movementType] =
motionControlFactory.create(movementType)

def __setMovementTypeValue(self, movementType, value):
control = self.__controls[movementType]
control.SetValue(value)

# I want to provide methods like these to the client app,
# but without typing them explicitely:
def SetOpenGripper(self, value):
self.__setMovementTypeValue('OpenGripper', value)

def SetRotateGripper(self, value):
self.__setMovementTypeValue('RotateGripper', value)


My application:

movementTypes = ['OpenGripper', 'RotateGripper']
robotCtrl = RobotControl(movementTypes)
robotCtrl.SetOpenGripper(1.0)
robotCtrl.SetRotateGripper(2.0)


While control object creation is abstracted out into the class
factory, SetOpenGripper(...) and SetRotateGripper(...) are still in
there and I obviously want to get rid of them, at least in their
explicitely implemented form. Instead, I want to generate them at
runtime, depending on what movement types are required.

I tried this in class RobotControl in __init__() in the 'for
movementType ...' loop:

funcName = 'Set' + movementType
function = lambda self, value:
self.__setMovementTypeValue(movementType, value)
method   = new.instancemethod(function, self, self.__class__)
setattr(self, funcName, method)

and the code somewhat seems to work, but instead of SetOpenGripper,
SetRotateGripper is called.

My questions:

1.) Does this look like a somewhat reasonable approach to someone who
knows more about Python than me ?
2.) What could I be doing wrong ?

I have a suspicion that my error is not even related to all this fancy
runtime code generation stuff, but something really dumb and I've just
been coding for too long to see it.

http://mail.python.org/pipermail/python-list/2007-June/446601.html
shows a somewhat comparable constellation and it was a good guideline.
But there, the function is created by the class factory, as well and I
unfortunately can't do that.

Thank you very much,

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


Re: Python cx_Oracle and Apache

2008-08-25 Thread Raja
On Aug 25, 1:53 pm, Cousin Stanley [EMAIL PROTECTED] wrote:
  

  def generate_output():
          print 'htmlbody/body/html'

  generate_output()

   Raja 

     You might try adding a  Content-type  header followed by
     a  blank line  to your  generate_output()  function 

     def generate_output() :
         print 'Content-type:  text/html'
         print                              
         print  rest of your html 

 --
 Stanley C. Kitching
 Human Being
 Phoenix, Arizona

Hi,
  Thanks for the help. I actually got the solution. The problem was
apache's timeout is set to 1second. I just changed that value and it
worked.


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


I can't fetch dom node in svg file with getElementById method (module minidom and libxml2dom)

2008-08-25 Thread KLEIN Stéphane
Hi,

I've a xml svg file and I would like to update it with Python.

First, I would like to fetch one dom node with getElementByID. I've one 
issue about this method.

This is my example :

My SVG file :


?xml version=1.0 encoding=UTF-8 standalone=no?
!-- Created with Inkscape (http://www.inkscape.org/) --
svg:svg
   xmlns:dc=http://purl.org/dc/elements/1.1/;
   xmlns:cc=http://creativecommons.org/ns#;
   xmlns:rdf=http://www.w3.org/1999/02/22-rdf-syntax-ns#;
   xmlns:svg=http://www.w3.org/2000/svg;
   xmlns:xlink=http://www.w3.org/1999/xlink;
   xmlns:sodipodi=http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd;
   xmlns:inkscape=http://www.inkscape.org/namespaces/inkscape;
   width=210mm
   height=297mm
   id=svg2383
   sodipodi:version=0.32
   inkscape:version=0.46
   sodipodi:docname=product_page.svg
   inkscape:output_extension=org.inkscape.output.svg.inkscape
/svg:svg


$ ipython

In [1]: from xml.dom import minidom

In [2]: dom1 = minidom.parse(myfile.svg)

In [3]: print(dom1.getElementById(usvg2383))
None

In [4]: print(dom1.getElementById(svg2383))
None

I don't understand why getElementById return always None.

Other example with libxml2dom library :

$ ipython

In [1]: import libxml2dom

In [2]: dom2 = libxml2dom.parseFile(myfile.svg)

In [3]: print(dom2.getElementById(usvg2383))
None

In [4]: print(dom2.getElementById(svg2383))

I don't understand why getElementById return always None.

Well, my final purpose isn't to fetch root dom node but to fetch many 
other sub node.

Thanks for your informations.
Stephane


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


Re: Python String Immutability Broken!

2008-08-25 Thread Simon Brunning
2008/8/25 Hendrik van Rooyen [EMAIL PROTECTED]:
 It is reputed to belong to a programmer who was flayed alive
 by the C.L.P. group, because he had violated the immutability
 of a python string.

You can indeed use ctypes to modify the value of a string - see
http://tinyurl.com/5hcnwl. You can use it to crash the OS, too.

My advice - don't.

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns
--
http://mail.python.org/mailman/listinfo/python-list


Re: For loop inside an xml template

2008-08-25 Thread Simon Brunning
2008/8/25 Amie [EMAIL PROTECTED]:
 Hi,

 Is it possible to have a for loop within an xml template?

Python has a whole bunch of template libraries. Which are you using?

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python String Immutability Broken!

2008-08-25 Thread Ken Seehart
You can also use ctypes to globally change the value of integers less 
than 101.   Personally, I don't particularly like the number 14.  I 
changed it to 9 and I am much happier now.


I love ctypes.  So cool.  It's not supposed to be safe.

   Life is either a daring adventure or nothing. Security does not
   exist in nature, nor do the children of men as a whole experience
   it. Avoiding danger is no safer in the long run than exposure.
   *Helen Keller http://www.quotationspage.com/quotes/Helen_Keller/*
   /US blind  deaf educator (1880 - 1968)/

Of course I would not hire anyone who believes this quote, other than 
Helen Keller, if she were still with us.


It is quite possible to write a small program that works using abused 
strings.  But my life better not depend on it.  Among other things, if 
you use the abused string as a key anywhere, you will not get correct 
results.  Trying to change the length of the string will cause 
disasters.  Lengthening a string will corrupt memory, and shortening the 
string will not shorten it but rather embed '\0' in it.


Ken

Hendrik van Rooyen wrote:
 
Patrick Maupin pmauail.com wrote:


  

Very entertaining.




Thanks. Nice to see that there is still some sense of humour
left somewhere - its all been so serious here lately - people
seem to forget that hacking is fun!

  

But let me get this straight:   Are you just complaining that if you
pass a string to an arbitrary C function using ctypes, that that
arbitrary function can modify the string?




Actually, I am not complaining - I am asking for advice on the side
effects of what I am doing, which is replacing a bunch of bits
in what is essentially an output bit field with the corresponding
input bits at the same addresses read back from a simulated i/o
bus structure.  And I would also like to know if there is a better
way of doing this.

The C code actually works, doing what was intended - the \xff that
one sees appearing back comes from the pullup resistors on the
eBox's i/o.  I can show that it is working by adding some resistance
and capacitance (by holding the connector against my tongue) in which
case I get a munged version of the fox back.  (- evidently my tongue
is not such a perfect communications medium as I would like to believe.)

Passing the fox is actually deceptive and misleading, as in real
use there would be no such correlation sideways across bits, as
they are just representations of output lines.
(Think coils in PLC jargon)

  

Because if you are, then I think you share a great deal of
responsibility for the death of that string -- sending the poor thing
to its grave through some unknown C function.



This string is NOT dead - it is alive, and not even stunned -
it just looks as if it is sleeping because of the \xff - which
comes from the fact that there is no real hardware out there yet.

The C functions are very simple ones actually - they just do
what are essentially Linux I/O system calls - setting direction
bits for a port (in or out) and then reading or writing the data.

- Hendrik



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

  


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


Re: generate methods at runtime, but the wrong one gets called

2008-08-25 Thread Maric Michaud
Le Monday 25 August 2008 11:37:23 Steven Samuel Cole, vous avez écrit :
 Hello,

 I am writing an application that controls robots. Different robots can
 do different kinds of movements, such as e.g. open gripper, rotate
 gripper, etc. My RobotControl class should support all kinds of
 robots. I therefore delegate the actual control work to extra
 control-specific classes, one class per movement type, e.g.
 OpenGripperControl, RotateGripperControl. These movement control
 classes are created by a simple class factory.


i don't get your design, it seems over-complicated to mee at first glance.

 This is my class half-way through:
...

 I tried this in class RobotControl in __init__() in the 'for
 movementType ...' loop:

 funcName = 'Set' + movementType
 function = lambda self, value:
 self.__setMovementTypeValue(movementType, value)
 method   = new.instancemethod(function, self, self.__class__)
 setattr(self, funcName, method)

 and the code somewhat seems to work, but instead of SetOpenGripper,
 SetRotateGripper is called.


The free variable movementType in the lambda is evaluated lately as it were in 
its last state once you return from __init__, if you want to early bind it to 
its value in each step of a for loop, you must use :

func = lambda s, v, m_t=movementType : s.__setMovementTypeValue(m_t, v)

 My questions:

 1.) Does this look like a somewhat reasonable approach to someone who
 knows more about Python than me ?

At first, what you do is creating instancemethod and bound them to an instance 
of your class, I find this confusing. Why not just use __getattr__ special 
method ?

(you don't need __setMovementTypeValue in this example)

def __getattr__(self, name) :
if name.startswith('Set') :
movement = name.lstrip('Set')
if movement in self.__controls :
return lambda value : self.__controls[movement].SetValue(value)
raise AttributeError

That said, if I understand you well, your class RobotControl seems to contain 
only logic that is not specific to an instance, nor to a class of instances. 
In other OOP language I would encourage you to implement this logic in some 
sort of singleton, but in python we don't like this construct, module level 
variables and function do perfectly the job, simple as they are.

 2.) What could I be doing wrong ?

 I have a suspicion that my error is not even related to all this fancy
 runtime code generation stuff, but something really dumb and I've just
 been coding for too long to see it.

 http://mail.python.org/pipermail/python-list/2007-June/446601.html
 shows a somewhat comparable constellation and it was a good guideline.
 But there, the function is created by the class factory, as well and I
 unfortunately can't do that.

 Thank you very much,

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



-- 
_

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


Re: Python String Immutability Broken!

2008-08-25 Thread Ken Seehart

Hendrik van Rooyen wrote:
 
...


Actually, I am not complaining - I am asking for advice on the side
effects of what I am doing, which is replacing a bunch of bits
in what is essentially an output bit field with the corresponding
input bits at the same addresses read back from a simulated i/o
bus structure.  And I would also like to know if there is a better
way of doing this.
  

Yes, there is a better way.  Use a character array instead of a string.

http://python.net/crew/theller/ctypes/tutorial.html#arrays

...

- Ken

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


Re: I can't fetch dom node in svg file with getElementById method (module minidom and libxml2dom)

2008-08-25 Thread Paul Boddie
On 25 Aug, 11:43, KLEIN Stéphane [EMAIL PROTECTED] wrote:
 Hi,

 I've a xml svg file and I would like to update it with Python.

 First, I would like to fetch one dom node with getElementByID. I've one
 issue about this method.

[SVG file with id attribute on svg element]

 In [1]: from xml.dom import minidom

 In [2]: dom1 = minidom.parse(myfile.svg)

 In [3]: print(dom1.getElementById(usvg2383))
 None

 In [4]: print(dom1.getElementById(svg2383))
 None

 I don't understand why getElementById return always None.

Here's a possible explanation:

http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-getElBId

Attributes with the name ID are not of type ID unless so defined.
Implementations that do not know whether attributes are of type ID or
not are expected to return null.

 Other example with libxml2dom library :

 $ ipython

 In [1]: import libxml2dom

 In [2]: dom2 = libxml2dom.parseFile(myfile.svg)

 In [3]: print(dom2.getElementById(usvg2383))
 None

 In [4]: print(dom2.getElementById(svg2383))

 I don't understand why getElementById return always None.

Here it's because I programmed it to do so. ;-) In fact, the
getElementById method provided by documents parsed by the
libxml2dom.svg module also return None in this case, although if I
were to take a look at the SVG DTD or schema, perhaps I should provide
such behaviour for SVG documents specifically.

 Well, my final purpose isn't to fetch root dom node but to fetch many
 other sub node.

You could always try using an XPath expression:

  node = (dom2.xpath(//[EMAIL PROTECTED]'svg2383']) or [None])[0]

Similar things could be done in PyXML and other libraries, I'm sure,
but minidom lacks XPath support, if I remember correctly.

Paul

P.S. There's so much I could be doing with libxml2dom, but we don't
all have enough time for everything we'd like to do (as I'm sure many
can understand). However, a Mercurial repository tracking the latest
work is available here:

https://hg.boddie.org.uk/libxml2dom
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check in CGI if client disconnected

2008-08-25 Thread Graham Dumpleton
On Aug 25, 5:49 pm, Vishal [EMAIL PROTECTED] wrote:
 Hi Graham,

    Thanks for the reply. In my case, it's the other way round. I need
 to check if the amount of data sent is equal to the file size i want
 to send. However, the question is - when do i check this? Currently, i
 am unable to call any cleanup code before exit.

Best you will do for writing, is to catch exceptions around the call
outputing the data. If an exception occurs then a problem has
obviously occurred.

Graham

 Regards,

 -vishal.

 On Aug 25, 11:44 am, Graham Dumpleton [EMAIL PROTECTED]
 wrote:

  On Aug 25, 4:26 pm, Vishal [EMAIL PROTECTED] wrote:

   Hi,

     Thanks for the replies. In my case, the cgi is sending a large file
   to the client. In case the the stop button is pressed on the browser
   to cancel the download, i want to do some cleanup action. It's all one-
   way transfer in this case, so i can't expect the client to send
   anything to me. I read somewhere that apache sends the SIGTERM signal
   to a cgi when the client disconnects. However, my cgi is not getting
   the signal - is there a way to have the cgi catch and handle the
   SIGTERM?

   I tried using the signal module

   ---
   def sigtermHandler(signum, frame):
       # do some cleanup

   signal.signal(signal.SIGTERM, sigtermHandler)

   ---

   But even this doesn't work.

  Have you considered simply checking to see if the amount of POST
  content read matches the inbound Content-Length specified in the CGI
  environment. If your processing of POST content finds less than what
  was meant to be sent, then likely that the client browser aborted
  request before all content could be sent.

  Graham

   Regards,

   -vishal.
   On Aug 25, 2:58 am, Gabriel Genellina [EMAIL PROTECTED]
   wrote:

En Sun, 24 Aug 2008 17:51:36 -0300, Wojtek Walczak [EMAIL PROTECTED] 
escribió:

 On Sun, 24 Aug 2008 17:21:52 -0300, Gabriel Genellina wrote:
    I am writing a CGI to serve files to the caller. I was wondering 
 if
 there is any way to tell in my CGI if the client browser is still
 connected. If it is not, i want to execute some special code before
 exiting.

    Is there any way to do this? Any help on this is appreciated :)

 I don't think so. A CGI script runs once per request, and exits. The 
 server may find that client disconnected, but that may happen after 
 the script finished.

 I am not a web developer, but I think that the only way is to
 set a timeout on server side. You can't be sure that the client
 disconnected, but you can stop CGI script if there's no
 action on client side for too long.

Which kind of client action? Every link clicked or form submitted 
generates a different request that triggers a CGI script; the script 
starts, reads its parameters, do its task, and exits. There is no long 
running process in CGI - the whole world must be recreated on each 
request (a total waste of resources, sure).

If processing takes so much time, it's better to assign it a ticket - 
the user may come back later and see if its ticket has been finished, 
or the system may send an email telling him.

--
Gabriel Genellina

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


Re: For loop inside an xml template

2008-08-25 Thread Paul Boddie
On 25 Aug, 10:58, Amie [EMAIL PROTECTED] wrote:

 Is it possible to have a for loop within an xml template?

Yes it is:

http://www.w3.org/TR/xslt.html#for-each

Depending on what you mean by xml template, of course.

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


python/xpath issue..

2008-08-25 Thread bruce
hey guys...

got a weird, hopefully simple issue.

the following sample bit of script is stripped down, and simply gets the
form node from the specified site schedule.psu.edu.

the problem i run into is that the dom/xpath from the libxml2dom works, and
i get the dom object everytime i run the app, but that the xpath is
intermittent!!! in other words, i can run the script 10 times.. and it might
work 7 or 8 times.. the other times, the xpath doesn't give the nodes
back...

when it works, name1_ in the app should be a list of nodes (for the 2 forms
in the page). and len_ should be 2.

is there anything you might suggest that i try in order to get a better
handle on exactly what might be going on here...

keep in mind, i'm not a python guy, just trying to get this to consistently
work... my suspicion is that the culprit might be memory related...

i'm running linux, on a x86 dual core with 4G ram. the python is 2.5.1.

thoughts/comments/etc would be appreciated...

-thanks!!!


#!/usr/bin/python
#
# test.py
#
# scrapes/extracts the basic data for the college
#
#
# the app gets/stores
#  name
#  url
#  address (street/city/state
#  phone
#
##
#test python script
import re
import libxml2dom
import urllib
import urllib2
import sys, string
from  mechanize import Browser
import mechanize
#import tidy
import os.path
import cookielib
from libxml2dom import Node
from libxml2dom import NodeList
import subprocess
import time


#
# Parse pricegrabber.com

##cj = p
##COOKIEFILE = 'cookies.lwp'
#cookielib = 1


urlopen = urllib2.urlopen
#cj = urllib2.cookielib.LWPCookieJar()
##cj = cookielib.LWPCookieJar()
Request = urllib2.Request
br = Browser()
br2 = Browser()

##if cj != None:
##  print sss
###install the CookieJar for the default CookieProcessor
##  if os.path.isfile(COOKIEFILE):
##  cj.load(COOKIEFILE)
##  print foo\n
##  if cookielib:
##  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
##  urllib2.install_opener(opener)
##  print foo2\n

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values1 = {'name' : 'Michael Foord',
  'location' : 'Northampton',
  'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

url=http://schedule.psu.edu/;
#===


if __name__ == __main__:
# main app

txdata = None

#

##br.set_cookiejar(cj)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.addheaders = [('User-Agent', 'Firefox')]

print url =,url
br.open(url)
##cj.save(COOKIEFILE)# resave cookies

res = br.response()  # this is a copy of response
s = res.read()
print slen=,len(s)

# s contains HTML not XML text
d = libxml2dom.parseString(s, html=1)
print d,d

name_=[]
len_=0
name_ = d.xpath(//form)
#name_ = d.xpath(/html/body/form)
print name1,name_
len_ = len(name_)
print len,len(name_)
#print sdlfs
sys.exit()
#   else:
#   print err in form_ID


print here...


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


Tkinter - How to create combo box using Tix with the existing Tkinter widgets/

2008-08-25 Thread dudeja . rajat
Hi,

I'm using Tkinter module to create a GUI application. I found that the
combo box is not present in Tkinter module.
It comes with Tix module. Could some one give me an example to create
a combo box whilst using Tix and Tkinter?

I've been using the following to create my tkinter widgets:
myRoot = Tk()

and in my Gui code, I've been using
self.lbAnalysisLib = Listbox(master, \
 yscrollcommand = self.vsbAnalysisLib.set,\
 height = 1,
 width = 30)

Please suggest how could I call the Tix's combo box from my existing
GUI application that heavily uses the Tkinter widgets?
Kindly provide me some code examples.

Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: swig double[], under the gun and need help

2008-08-25 Thread Diez B. Roggisch
Sells, Fred wrote:

 I'm using python 2.4 under linux (centos 5.1).
 I need to pass an array of doubles to a c function
 but am getting an error, shown near the bottom of
 this post.
 
 my swig interface file looks like this
 
 * File: rug520.i */
 %module rug520
 %include typemaps.i
 %include carrays.i
 %array_class(double, doubleArray);
 %{
 #define SWIG_FILE_WITH_INIT
 #include rug520.h
 extern double[] nCmiArray;
 %}
 
 
 %apply int *OUTPUT { char *sRugHier,
  char * sRugMax,
  int * iRugHier,
  int * iRugMax,
  double * nCmiValueHier,
  double * nCmiValueMax,
  int * iAdlSum,
  int * iCpsCode,
  char * sRugsVersion,
  char * sDllVersion,
  int * iError };
 
 
 int RugCalc( char * sMdsRecord,
  char * sRehabType,
  char * sModel,
  int iQuarterlyFlag,
  double nCmiArray[],
 
   char * sRugHier,
  char * sRugMax,
  int * iRugHier,
  int * iRugMax,
  double * nCmiValueHier,
  double * nCmiValueMax,
  int * iAdlSum,
  int * iCpsCode,
  char * sRugsVersion,
  char * sDllVersion,
  int * iError );
 
 --
 my test code looks like this:
 import sys, os, rug520
 cmi=[0.0] *59
 
 def getrug(mds):
 results = rug520.RugCalc(mds, 'mcare', '34', 0, cmi)
 print 'results', results
 
 datafile = open('mdsdata.txt')
 for d in datafile:
 if d[0]=='B':
 getrug(d)
 
 I get this error message
 File testrug520.py, line 11, in ?
 getrug(d)
   File testrug520.py, line 5, in getrug
 results = rug520.RugCalc(mds, 'mcare', '34', 0, cmi)
 TypeError: in method 'RugCalc', argument 5 of type 'double []'
 
 --
 
 I'm guessing that I am not passing a double array to the c code.  I cannot
 change
 the c code due to politics.  I could write a c wrapper if I had to, but
 would rather stay within python or the swig interface definitions if
 possible/practical.
 
 I'm not much of a c programmer; mostly java and python with a little c++.
 I've looked in the swig docs and tried google, but either have not found
 it or just don't understand what they are telling me here.

I don't know swig, but if all you have is a real C-API, try  use ctypes.
It's much easier to create bindings for, keeps you fully in the warm and
cozy womb of python programming and doesn't need no compilation to create
the actual binding.

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


Re: Best way to set/get an object property

2008-08-25 Thread Hussein B
On Aug 25, 4:31 am, Steven D'Aprano
[EMAIL PROTECTED] wrote:
 On Sun, 24 Aug 2008 23:56:27 -0700, Hussein B wrote:
  On Aug 24, 7:12 pm, Steven D'Aprano [EMAIL PROTECTED]
  cybersource.com.au wrote:
   I noted that Python encourage the usage of: -- obj.prop = data
   x = obj.prop
   --
   to set/get an object's property value. What if I want to run some
   logic upon setting/getting a property? What is Python preferred
   method to do so (using the new feature 'property')? I don't think
   __getattr__ and __setattr__ are practical (I have to code the
   property name into them).
 ...
  I think the actual answer to his question is that properties are the
  preferred way to run some logic upon setting/getting an attribute,
  that is, to implement getters and setters.

  Hussein, the Java habit of writing setters and getters for everything
  isn't considered good practice in Python, but if you need them, that's
  exactly what the property() function is for.

  --
  Steven

  Thank you Steven :)
  --
  public class JClass {
private int answer; // property
  }
  --
  class PyClass(object):
doc __init__(self):
  self.answer = None
  --
  AFAIUY (understand you), what it is called a property in Java, it is
  called an attribute in Python?
  Why Python encourages direct access to object's attributes?  aren't
  setters/getters considered vital in OOP (encapsulation)?
  Thank you all for your time and help.

 Hussein, first let me ask you to please stop using -- as a separator
 around code. Many News clients, including mine, expect -- on a line by
 itself to mean everything from here on is the writer's signature, and
 consequently that makes it harder to reply correctly to your posts. I had
 to manually copy and paste your text in order to quote it. Perhaps you
 could use === or +++ or ***  as a separator?

 Now, back to your actual question...

 I'm not a Java coder, so the following should be read as my opinion.
 Python attributes are equivalent to Java _public_ properties, not
 private. If you can write:

 public class JClass {
public int answer;

 }

 then that would be more or less equivalent to Python's

 class PyClass(object):
 def __init__(self):
 self.answer = None

 Yes, Python does encourage direct access to an object's attributes. The
 Python philosophy is we're all adults here. If coders wish to shoot
 themselves in the foot by accessing clearly marked private attributes,
 then the language can't stop them and shouldn't try. It's easy to bypass
 such private/public protection in C++, and harder, but still possible, in
 Java.

 The Python development team is certainly aware that such a tactic
 introduces some costs, by reducing encapsulation, but it also has many
 benefits (e.g. less boilerplate getter/setter methods, faster development
 time). It is their belief that such costs are worth paying in order to
 get the benefits. That's the philosophy of the language. Python is not
 trying to be Java, and Java should not try to be Python.

 Python does not enforce private attributes. By convention attributes
 starting with a single underscore are considered private -- don't touch
 unless you know what you're doing. Attributes starting with a double
 underscore are really private, and Python mangles the name to (almost)
 enforce it.

 Example:

 def Parrot(object):
 colour = 'red'  # public, free to use
 _windspan = 15  # semi-private, use it at your own risk
 __species = 'Norwegian Blue'  # mangled to _Parrot__species

 But it's quite rare to see double-underscore really private attributes
 in Python code. It is considered to go against the spirit of the language.

 I'm told that in Java it is quite difficult to change a class from using
 public attributes to getters/setters, and therefore many Java developers
 prefer to use getters/setters right from the beginning. But in Python it
 is very easy to change from a bare attribute to a computed property
 without messing up calling code. So there's no advantage to writing
 something like this:

 class Foo(object):
 def __init__(self):
 self.__x = None  # private attribute
 def setx(self, x):  # setter
 self.__x = x
 def getx(self):  # getter
 return self.__x
 x = property(getx, setx)

 That is considered a waste of time in Python circles and is strongly
 discouraged.

 You should read Python Is Not Java and Java Is Not Python Either:

 http://dirtsimple.org/2004/12/python-is-not-java.html

 http://dirtsimple.org/2004/12/java-is-not-python-either.html

 --
 Steven

Thank you all guys and big thank you Steven, I owe you a beer.
Sorry, I wasn't aware of the two dashes problem as I use Google Group/
Reader.
comp.lang.python really rocks  much more friendly and useful than
comp.lang.ruby
--
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 HTTPBasicAuthHandler and resumingbroken downloads

2008-08-25 Thread Brendan
On Aug 22, 1:59 pm, Gabriel Genellina [EMAIL PROTECTED]
wrote:
 En Fri, 22 Aug 2008 08:55:57 -0300, Brendan [EMAIL PROTECTED]  
 escribi :





  On Aug 21, 3:57 pm, Gabriel Genellina [EMAIL PROTECTED]
  wrote:
  En Thu, 21 Aug 2008 15:37:41 -0300, Brendan [EMAIL PROTECTED]  
   
  escribi :

   Is there any way to resume an https file download using urllib2 and an
   HTTPBasicAuthHandler?

  You should provide the Range header (and probably If-Range too) in the  
  request.http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35

  Ug. Why does everything in Python boil down to reading rfcs? It really
  slows us non computer science types down. I'll probably spend a day on
  this instead of an hour. I did search the web but had no luck finding
  an example, so I posted here as a last resort.

 The easy way is to use wget...
 If you want a Python example, go to the Python 
 cookbook:http://code.activestate.com/recipes/langs/python/
 enter resume download in the search box, and the very first recipe shows  
 how to use the Range header.

 --
 Gabriel Genellina- Hide quoted text -

 - Show quoted text -

Thanks for the link. Much appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Equivalents of Ruby's ! methods?

2008-08-25 Thread Simon Mullis
Hi All,

Quick question, I can't seem to find the answer online (well, at the
moment I think the answer is a simple no but I would like to
confirm).

Consider the following hash:

h = { 1 : a\r, 2 : b\n }

In order to strip the dict values in Python I (think) I can only do
something like:

for k,v in h.items:
h[k] = v.strip()

While in Ruby - for the equivale dict/hash - I have the option of an
in-place method:

h.each_value { |v| val.strip! }

Are there Python equivalents to the ! methods in Ruby?

The reason I ask is that I have some fairly complex data-structures
and this would make my code alot cleaner... If this is not an accepted
and pythonic way of doing things then please let me know... and I'll
stop!

Thanks in advance

SM


-- 
Simon Mullis
_
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


rspec for python

2008-08-25 Thread Rustom Mody
Is there anything equivalent to rspec for python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: I can't fetch dom node in svg file with getElementById method (module minidom and libxml2dom)

2008-08-25 Thread KLEIN Stéphane
Le Mon, 25 Aug 2008 04:30:00 -0700, Paul Boddie a écrit :

 Well, my final purpose isn't to fetch root dom node but to fetch many
 other sub node.
 
 You could always try using an XPath expression:
 
   node = (dom2.xpath(//[EMAIL PROTECTED]'svg2383']) or [None])[0]
 
 Similar things could be done in PyXML and other libraries, I'm sure, but
 minidom lacks XPath support, if I remember correctly.

Thanks ! It work.

Regards,
Stephane


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

Re: Tkinter - How to create combo box using Tix with the existing Tkinter widgets/

2008-08-25 Thread dudeja . rajat
On Mon, Aug 25, 2008 at 12:57 PM,  [EMAIL PROTECTED] wrote:
 Hi,

 I'm using Tkinter module to create a GUI application. I found that the
 combo box is not present in Tkinter module.
 It comes with Tix module. Could some one give me an example to create
 a combo box whilst using Tix and Tkinter?

 I've been using the following to create my tkinter widgets:
 myRoot = Tk()

 and in my Gui code, I've been using
 self.lbAnalysisLib = Listbox(master, \
 yscrollcommand = self.vsbAnalysisLib.set,\
 height = 1,
 width = 30)

 Please suggest how could I call the Tix's combo box from my existing
 GUI application that heavily uses the Tkinter widgets?
 Kindly provide me some code examples.

 Thanks and regards,
 Rajat


Ok...now I  found the way to do that. But I'm stuck further.
my code is as below:


main module
**
myRoot = Tix.Tk()
myAppGUIObject = myAppGUI(myRoot)

Gui module

class myAppGUI:
def __init__(self, master):

self.cbAnalysisLib = Tix.ComboBox(master, label = Analysis Library:)
self.cbAnalysisLib.grid(row = 3, column = 1, padx = 30, pady = 30,
sticky = W)
self.cbAnalysisLib.config(editable = 0)

   self.cbAnalysisLibVersion = Tix.ComboBox(master, label = Reference
Analysis Library Version:, \

labelside = 'left')
  self.cbAnalysisLibVersion.grid(row = 5, column = 1, padx = 30, pady
= 30, sticky = W)
  self.cbAnalysisLibVersion.config(editable = 0)


The problem is that the labelside option is not working. I'm not able
to use even the wraptext option.

-- 
Regrads,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Leo Jay
On Mon, Aug 25, 2008 at 8:52 PM, Simon Mullis [EMAIL PROTECTED] wrote:
 Hi All,

 Quick question, I can't seem to find the answer online (well, at the
 moment I think the answer is a simple no but I would like to
 confirm).

 Consider the following hash:

 h = { 1 : a\r, 2 : b\n }

 In order to strip the dict values in Python I (think) I can only do
 something like:

 for k,v in h.items:
h[k] = v.strip()

 While in Ruby - for the equivale dict/hash - I have the option of an
 in-place method:

 h.each_value { |v| val.strip! }

 Are there Python equivalents to the ! methods in Ruby?

 The reason I ask is that I have some fairly complex data-structures
 and this would make my code alot cleaner... If this is not an accepted
 and pythonic way of doing things then please let me know... and I'll
 stop!


how about this one:
 h = { 1 : a\r, 2 : b\n }
 dict((k, h[k].strip()) for k in h)
{'1': 'a', '2': 'b'}



-- 
Best Regards,
Leo Jay
--
http://mail.python.org/mailman/listinfo/python-list


Re: For loop inside an xml template

2008-08-25 Thread Amie
On Aug 25, 1:33 pm, Paul Boddie [EMAIL PROTECTED] wrote:
 On 25 Aug, 10:58, Amie [EMAIL PROTECTED] wrote:



  Is it possible to have a for loop within an xml template?

 Yes it is:

 http://www.w3.org/TR/xslt.html#for-each

 Depending on what you mean by xml template, of course.

 Paul

Thanks, that seems to help a bit
Cheers
--
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Ben Finney
Simon Mullis [EMAIL PROTECTED] writes:

 Consider the following hash:
 
 h = { 1 : a\r, 2 : b\n }

This is a 'dict' instance in Python. A 'hash' is a different concept.

 In order to strip the dict values in Python I (think) I can only do
 something like:
 
 for k,v in h.items:
 h[k] = v.strip()

The above won't do what you describe, since 'h.items' evaluates to
that function object, which is not iterable. If you want the return
value of the function, you must call the function:

for (k, v) in h.items():
h[k] = v.strip()

This will create a new value from each existing value, and re-bind
each key to the new value for that key. Clear, straightforward, and
Pythonic.

You can also create a new dict from a generator, and re-bind the name
to that new dict:

h = dict(
(k, v.strip())
for (k, v) in h.items())

Also quite Pythonic, but rather less clear if one hasn't yet
understood generator expressions. Very useful to have when needed,
though.

 While in Ruby - for the equivale dict/hash - I have the option of an
 in-place method:
 
 h.each_value { |v| val.strip! }
 
 Are there Python equivalents to the ! methods in Ruby?

I'm not overly familiar with Ruby, but the feature you describe above
seems to rely on mutating the string value in-place. Is that right?

Strings in Python are immutable (among other reasons, this allows them
to meet the requirement of dict keys to be immutable, which in turn
allows dict implementations to be very fast), so you can only get a
new value for a string by creating a new string instance and re-bind
the reference to that new value.

Either of the above Python implementations will do this.

-- 
 \   “Kissing a smoker is like licking an ashtray.” —anonymous |
  `\   |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python String Immutability Broken!

2008-08-25 Thread Steven D'Aprano
On Mon, 25 Aug 2008 03:43:01 -0700, Ken Seehart wrote:

 You can also use ctypes to globally change the value of integers less
 than 101.   Personally, I don't particularly like the number 14.  I
 changed it to 9 and I am much happier now.

Okay, you've got me curious. How do you do that, and why only up to 101?



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


Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Paul McGuire
On Aug 25, 7:52 am, Simon Mullis [EMAIL PROTECTED] wrote:
 Consider the following hash:

 h = { 1 : a\r, 2 : b\n }

In Python, this called a dict.  hash sounds so... perlish.


 In order to strip the dict values in Python I (think) I can only do
 something like:

 for k,v in h.items:
     h[k] = v.strip()

 While in Ruby - for the equivale dict/hash - I have the option of an
 in-place method:

 h.each_value { |v| val.strip! }

 Are there Python equivalents to the ! methods in Ruby?

You have pretty much answered your own question.  ! methods are not
specially named or annotated in Python, str.strip is the method that
corresponds to strip!.  It looks a little different since you left off
the ()'s in the Ruby example (as is your privilege and right in Ruby).

Pythonistically speaking, even though a dict is a mutable thing, I'm
learning that the accepted practice for methods like this is not so
much to update in place as it is to use generator expressions to
construct a new object.  For example, given a list of integers to 100,
instead of removing all of the even numbers (with the attendant
hassles of updating a list while iterating over it), just create a new
list of the numbers that are not even.

In your dict case, this would just be:

   h = dict( k,v.strip() for k,v in h.iteritems() )

Perhaps I am overgeneralizing from comments I have read here on c.l.py
about creating new lists instead updating old ones.  But in your loop,
you *will* end up doing a re-assignment of every value in the dict,
even if the original value had no whitespace to strip.

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


Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Simon Mullis
Thanks to all for the quick responses.

2008/8/25 Ben Finney [EMAIL PROTECTED]:

 This is a 'dict' instance in Python. A 'hash' is a different concept.

 In order to strip the dict values in Python I (think) I can only do
 something like:

 for k,v in h.items:
 h[k] = v.strip()

 The above won't do what you describe, since 'h.items' evaluates to
 that function object, which is not iterable. If you want the return
 value of the function, you must call the function:

for (k, v) in h.items():
h[k] = v.strip()


Yes - absolutely, a typo on my part.

 This will create a new value from each existing value, and re-bind
 each key to the new value for that key. Clear, straightforward, and
 Pythonic.

 You can also create a new dict from a generator, and re-bind the name
 to that new dict:

h = dict(
(k, v.strip())
for (k, v) in h.items())

 Also quite Pythonic, but rather less clear if one hasn't yet
 understood generator expressions. Very useful to have when needed,
 though.


Thanks for this - I'll have a look!

 While in Ruby - for the equivale dict/hash - I have the option of an
 in-place method:

 h.each_value { |v| val.strip! }

 Are there Python equivalents to the ! methods in Ruby?

 I'm not overly familiar with Ruby, but the feature you describe above
 seems to rely on mutating the string value in-place. Is that right?


There are a number of methods that can be used to change things
in-place such as:

 String.new().grep_methods(!)
= [upcase!, gsub!, downcase!, chop!, capitalize!, tr!,
chomp!, swapcase!, tr_s!, succ!, strip!, delete!,
lstrip!, squeeze!, next!, rstrip!, slice!, reverse!,
sub!]

Or,

 Array.new().grep_methods(!)
= [map!, shuffle!, uniq!, reject!, compact!, slice!,
sort!, flatten!, collect!, reverse!]

They normally have a non-! partner which is used only for a return
value and does not affect the original object.

But! This isn't a Ruby group so I'll stop now... ;-)

 Strings in Python are immutable (among other reasons, this allows them
 to meet the requirement of dict keys to be immutable, which in turn
 allows dict implementations to be very fast), so you can only get a
 new value for a string by creating a new string instance and re-bind
 the reference to that new value.

Normally I would use a Ruby symbol as a hash key:

h = { :key1 = val1, :key2 = val2 }

From the stdlib docs:

The same Symbol object will be created for a given name or string for
the duration of a program's execution, regardless of the context or
meaning of that name. Thus if Fred is a constant in one context, a
method in another, and a class in a third, the Symbol :Fred will be
the same object in all three contexts. 

There is no equivalent in Python (as far as I know, and I'm only in my
second week of Python so I'm more than likely incorrect!).

If you're interested:
http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol

Thanks again for the pointers.

-- 
Simon Mullis
_
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


passing arguments to exec

2008-08-25 Thread Alexandru Mosoi
i want to execute a python script using exec open('script.py'). how do
I pass arguments?
--
http://mail.python.org/mailman/listinfo/python-list


Re: passing arguments to exec

2008-08-25 Thread Wojtek Walczak
On Mon, 25 Aug 2008 06:31:53 -0700 (PDT), Alexandru Mosoi wrote:
 i want to execute a python script using exec open('script.py'). how do
 I pass arguments?

Take a look at subprocess module. It comes with a set of examples.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


signal and threading

2008-08-25 Thread ~levon
Hello group,

in following example, a signal handler is registered and a thread
started. if I call self.doSomethin() directly
the code works as I would expect. as i send a SIGINT shutdown is
called and the script terminates.

as soon as I call doSomething() in a thread the the SIGINT handler is
never called again and
i have to terminate the script with a SIGTERM or SIGKILL.

well, i would expect the handler to be called in both cases, am i
missing something?

by the way. calling os.kill(os.getpid(), signal.SIGINT) works as I
would expect, what
don't is kill -s SIGINT pid # where pid is the actual process id

the code:

class Runner(object):
def __init__(self):
print os.getpid()
self.shd = False
signal.signal(signal.SIGINT, self.shutdown)
threading.Thread(target=self.doSomething).start()
# the following works fine:
#os.kill(os.getpid(), signal.SIGINT)

def doSomething(self):
while not self.shd:
pass

def shutdown(self, signo, frm):
self.shd = True

if __name__ == '__main__':
Runner()

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


Re: Python String Immutability Broken!

2008-08-25 Thread Peter Otten
Steven D'Aprano wrote:

 On Mon, 25 Aug 2008 03:43:01 -0700, Ken Seehart wrote:
 
 You can also use ctypes to globally change the value of integers less
 than 101.   Personally, I don't particularly like the number 14.  I
 changed it to 9 and I am much happier now.
 
 Okay, you've got me curious. How do you do that, and why only up to 101?

Up to 256 in current Python. Small integers are shared to save memory.
After a quick look into the ctypes tutorial and the python source I came up
with

# 64-bit linux

 from ctypes import *
 libc = cdll.LoadLibrary(libc.so.6)
 libc.memset(id(14)+16, 0, 8)
7742336
 14
0
 14 == 0
True

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


When I do from lxml import etree I've this error : AttributeError: 'module' object has no attribute 'BytesIO'

2008-08-25 Thread KLEIN Stéphane
Hi,

I'm on Ubuntu 8.04.1

I've installed lxml with easy_install lxml command.

Now, when I load etree I've this error :

$ python
Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) 
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type help, copyright, credits or license for more information.
 from lxml import etree
Traceback (most recent call last):
  File stdin, line 1, in module
  File lxml.etree.pyx, line 40, in lxml.etree (src/lxml/
lxml.etree.c:119415)
AttributeError: 'module' object has no attribute 'BytesIO'
 

Have you some idea about this issue ?

Thanks for your help,
Stephane

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


Re: When I do from lxml import etree I've this error : AttributeError: 'module' object has no attribute 'BytesIO'

2008-08-25 Thread KLEIN Stéphane
Le Mon, 25 Aug 2008 13:50:50 +, KLEIN Stéphane a écrit :

 Hi,
 
 I'm on Ubuntu 8.04.1
 
 I've installed lxml with easy_install lxml command.
 
 Now, when I load etree I've this error :
 
 $ python
 Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu
 4.2.3-2ubuntu7)] on linux2 Type help, copyright, credits or
 license for more information.
 from lxml import etree
 Traceback (most recent call last):
   File stdin, line 1, in module
   File lxml.etree.pyx, line 40, in lxml.etree (src/lxml/
 lxml.etree.c:119415)
 AttributeError: 'module' object has no attribute 'BytesIO'
 
 
 Have you some idea about this issue ?

I've this bug only with lxml2, lxml 1.3.3 work very well.

Regards,
Stephane


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

Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread bearophileHUGS
Simon Mullis:
 h = { 1 : a\r, 2 : b\n }
 I have the option of an in-place method:
 h.each_value { |v| val.strip! }

This in-place version may be the closer code for Python 2.x:

d = {1: a\r, 2: b\n}
d.update((k, v.strip()) for k, v in d.iteritems())

You may also want to use v.rstrip() there instead.

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


windows / Tkinter - Tix - combo box - how to bind function to an event

2008-08-25 Thread dudeja . rajat
Hi,
I'm using Tkinter and Tix. I've created a combo box which I am able to
fill it up.
I'm want to call a function as soon as user selects some thing from
the combo box.

More precisely, I want to know how can i bind my function to this
selection event.
What this event is technically called?

Please suggest how can I do this?

-- 
Regrads,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


newbie question

2008-08-25 Thread sharon k
hi all,

i am new to python.

i fetch a webpage with urllib, extract a few numbers in a format as follow;

10,884
24,068

my question is how to remove the comma between the number, since i have to
add them up later.

sorry for my bad english.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Hrvoje Niksic
Simon Mullis [EMAIL PROTECTED] writes:

 There is no equivalent in Python (as far as I know, and I'm only in
 my second week of Python so I'm more than likely incorrect!).

Python uses strings for that purpose, which works well due to their
immutability.  Python automatically interns strings used in source
code that look like identifiers, so memory is saved.

An even closer equivalent of symbols are interned strings (see the
intern built-in), but they are not as nice to work with as real
symbols.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is class method?

2008-08-25 Thread Hrvoje Niksic
Steven D'Aprano [EMAIL PROTECTED] writes:

 On Sun, 24 Aug 2008 11:09:46 +0200, Hrvoje Niksic wrote:

 Use [classmethod] when your method needs to know what class it is
 called from.

 Ordinary methods know what class they are called from

I guess I should have added and no more.  :-)

 Why is this useful? Consider the dict method fromkeys. You can
 call it from any dictionary, but it doesn't care which dict you call
 it from, only that it is being called from a dict:

That's also a good example of the difference between classmethod and
staticmethod, since fromkeys is smart enough to use the type
information.

 class X(dict):
...   pass
...
 x = X.fromkeys({1: 2})
 type(x)
class '__main__.X' # not type 'dict'

If 'fromkeys' were a staticmethod, it would have to be hardcoded to
always create dicts.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Filling in Degrees in a Circle (Astronomy)

2008-08-25 Thread Gerard flanagan

W. eWatson wrote:
The other night I surveyed a site for astronomical use by measuring the 
altitude (0-90 degrees above the horizon) and az (azimuth, 0 degrees 
north clockwise around the site to 360 degrees, almost north again) of 
obstacles, trees. My purpose was to feed this profile of obstacles 
(trees) to an astronomy program that would then account for not sighting 
objects below the trees.


When I got around to entering them into the program by a file, I found 
it required the alt at 360 azimuth points in order from 0 to 360 (same 
as 0). Instead I have about 25 points, and expected the program to be 
able to do simple linear interpolation between those.


Is there some simple operational device in Python that would allow me to 
create an array (vector) of 360 points from my data by interpolating 
between azimuth points when necessary? All my data I rounded to the 
nearest integer. Maybe there's an interpolation operator?


As an example, supposed I had made 3 observations: (0,0) (180,45) and 
(360,0). I would want some thing like (note the slope of the line from 0 
to 179 is 45/180 or 0.25):

alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0
az : 0, 1,2,3,  180

Of course, I don't need the az.



Using one of the Python maths packages (scipy, sage, ...) is no doubt 
better, but out of interest here is some first-principles interpolation:


8-

class NewtonInterpolatingPolynomial(object):

def __init__(self):
self._domain = []
self._codomain = []
self._diffs = None
self._coeffs = []

def add_data_point(self, x, y):
self._domain.append(x)
self._codomain.append(y)
if self._diffs is None:
self._diffs = {}
else:
degree = len(self._domain) - 2
_x = self._domain[-2]
_y = self._codomain[-2]
self._diffs[(degree, degree+1)] = (y - _y) / (x - _x)
indices = range(degree+2)
for t in ( tuple(indices[i:]) for i in 
reversed(indices[:-2]) ):

denominator = self._domain[t[0]] - self._domain[t[-1]]
k, _k = self._diffs[t[1:]], self._diffs[t[:-1]]
self._diffs[t] = (_k - k) / denominator
self._coeffs.append(self._diffs[tuple(indices)])

def __str__(self):
N = len(self._domain)
if not N:
return ''
parts = [str(self._codomain[0])]
multipliers = [''.join(('(X - ',str(C),')')) for C in 
self._domain[:-1]]

for i, k in enumerate(self._coeffs):
parts.append('*'.join([str(k)] + multipliers[:i+1]))
return ' + '.join(parts)

def interpolate(self, gamma):
#return eval(str(self).replace('X', str(gamma)))
ret = self._codomain[0]
K = 1
multipliers = [gamma-C for C in self._domain[:-1]]
for i, k in enumerate(multipliers):
K *= k
ret += self._coeffs[i] * K
return ret

def __call__(self, x):
return self.interpolate(x)


rawdata = '''
018
18   18
27   16
34   20
48   20
59  28
72  32
'''

data = [map(float, line.split() ) for line in rawdata.splitlines() if line]

newton = NewtonInterpolatingPolynomial()

for x, y in data:
newton.add_data_point(x, y)
print newton
for P in range(80):
print P, '- ', newton(P)

18.0 + 0.0*(X - 0.0) + -0.0082304526749*(X - 0.0)*(X - 18.0) + 
0.00170098903759*(X - 0.0)*(X - 18.0)*(X - 27.0) + -8.87803681143e-05*(X 
- 0.0)*(X - 18.0)*(X - 27.0)*(X - 34.0) + 3.29057245545e-06*(X - 0.0)*(X 
- 18.0)*(X - 27.0)*(X - 34.0)*(X - 48.0) + -8.98633510787e-08*(X - 
0.0)*(X - 18.0)*(X - 27.0)*(X - 34.0)*(X - 48.0)*(X - 59.0)

0 -  18.0
1 -  26.0156268043
2 -  31.8038369501
3 -  35.719116702
4 -  38.0797664434
5 -  39.1701395406
6 -  39.2428165062
7 -  38.5207144606
8 -  37.1991318912
9 -  35.4477287116
10 -  33.4124416172
11 -  31.2173347409
12 -  28.9663856061
13 -  26.7452063785
14 -  24.6227004166
15 -  22.6526541194
16 -  20.8752640745
17 -  19.3185995022
18 -  18.0
19 -  16.9274085845
20 -  16.1006400316
21 -  15.5125845157
22 -  15.1503465468
23 -  14.996319206
24 -  15.0291936797
25 -  15.2249040921
26 -  15.5575076355
27 -  16.0
28 -  16.525066101
29 -  17.1057661048
30 -  17.7161567532
31 -  18.3318479864
32 -  18.9304948638
33 -  19.4922247833
34 -  20.0
35 -  20.4399154416
36 -  20.8014318237
37 -  21.0775440624
38 -  21.2648849859
39 -  21.3637643445
40 -  21.3781431185
41 -  21.3155431251
42 -  21.1868919232
43 -  21.0063030167
44 -  20.7907913565
45 -  20.5599241405
46 -  

Re: newbie question

2008-08-25 Thread Gerhard Häring

sharon k wrote:

hi all,

i am new to python.



i fetch a webpage with urllib, extract a few numbers in a format as follow;

10,884
24,068

my question is how to remove the comma between the number, since i have 
to add them up later.


Strings have a replace method. Calling replace(,, ) on the string 
will do the trick here.


-- Gerhard

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


Re: newbie question

2008-08-25 Thread Manuel Ebert

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi sharon,

as I understand, you want to remove certain characters of a string. Try:

number = int(fetched_number.replace(',', ''))

this will first remove any , characters and then convert the string  
into an integer.


Best,
Manuel

On Aug 25, 2008, at 4:15 PM, sharon k wrote:


hi all,

i am new to python.

i fetch a webpage with urllib, extract a few numbers in a format as  
follow;


10,884
24,068

my question is how to remove the comma between the number, since i  
have to add them up later.


sorry for my bad english.
--
http://mail.python.org/mailman/listinfo/python-list


-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (Darwin)

iD8DBQFIssKJcZ70OCIgLecRAkxTAJ4wWKxmlAS8hdQZK0Eoj7pAxwx41wCaA/eI
NY9GZKX6+PNIYIGaaghNvZg=
=JN2/
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: rspec for python

2008-08-25 Thread Gerhard Häring

Rustom Mody wrote:

Is there anything equivalent to rspec for python?


I had to Google to see what it is: A Behaviour Driven Development 
framework for Ruby.


In a blog article from Ian Bicking says that it is impossible to have a 
Python port of this because Python doesn't allow you to inject methods 
into the object class and suggests Python's doctest module as an 
alternative.


Have you actually used this rspec thing in Ruby? I always wonder with 
such things.


Same with all the other hyped technologies of yesteryear. Anybody out 
there who really uses model-driven development?


-- Gerhard

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


Re: newbie question

2008-08-25 Thread sharon k
thank you for your prompt reply.


 sorry seems i run into another problem, as follow;

  a = 12,123
  b = str(a)
  c = int(b.replace(',', ''))
 Traceback (most recent call last):
   File stdin, line 1, in module
 ValueError: invalid literal for int() with base 10: '(12 123)'

 the comma has become an empty space, it cannot be converted to an integer.
 i try the above in a winxp python command line.


 On Mon, Aug 25, 2008 at 10:48 PM, Gerhard Häring [EMAIL PROTECTED] wrote:

 sharon k wrote:

 hi all,

 i am new to python.

 

 i fetch a webpage with urllib, extract a few numbers in a format as
 follow;

 10,884
 24,068

 my question is how to remove the comma between the number, since i have
 to add them up later.


 Strings have a replace method. Calling replace(,, ) on the string will
 do the trick here.

 -- Gerhard


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



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

ANN: python-unixtools 0.0.1

2008-08-25 Thread Hartmut Goebel
I'm pleased to announce python-unixtools 0.0.1, a set of Unix tools
implemented in pure Python.

These tools are currently only meant as supplement to be able to use
distutils's sdist_tar, sdist_bztar and sdist_gztar on Windows/Wine.
Thus they currently only support the flags required by distutils.

But perhaps this will grow. Feel free to enhance.

Includes tools:
* tar
* gzip
* bzip2


:Quick Installation:
easy_install -U python-unixtools

:Download:
http://python-unixtools.origo.ethz.ch/download/


:Author:Hartmut Goebel [EMAIL PROTECTED]
:Copyright: GNU Public Licence v3 (GPLv3)
:Homepage:  http://python-unixtools.origo.ethz.ch/

-- 
Schönen Gruß - Regards
Hartmut Goebel
Dilp.-Informatiker (univ.), CISSP

Goebel Consult
Spezialist für IT-Sicherheit in komplexen Umgebungen
http://www.goebel-consult.de
--
http://mail.python.org/mailman/listinfo/python-list


Read dbf file as read only

2008-08-25 Thread ajak_yahoo
Hi,

How can I access a foxpro dbf file from my python program.
 I just want to read it as a read only file.

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

ANN: pyspread 0.0.9

2008-08-25 Thread Martin Manns
pyspread 0.0.9 has been released.

About:
pyspread is a spreadsheet that accepts a pure python expression in
each cell.

New features:
+ Find  Replace
+ Undo  Redo
+ New context menu in grid
+ Improved speed especially for large grids
+ Relative addressing revamped
+ CSV import improved
+ Icons changed to Tango iconset
+ Docstrings improved
+ Bug fixes in print framework

Highlights:
+ Numpy high performance arrays for spreadsheet calculation
+ Full access to python batteries from each cell
+ No non-python syntax add-ons
+ 3D grid
+ Cell access via slicing of numpy array S
+ X, Y, and Z yield current cell location for relative reference

Notes:
Please use distutils for installation.
Make sure that the old files are deleted:
$ su
$ rm -Rf [MyPythonPath]/site-packages/pyspread*
$ python setup.py install
$ exit
$ pyspread.py

Requires: Python =2.4, Numpy =1.1.0, and wxPython =2.8.7.1.
License: GPL

Project page: http://pyspread.sourceforge.net

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


Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Steven D'Aprano
On Mon, 25 Aug 2008 06:21:09 -0700, Paul McGuire wrote:

 On Aug 25, 7:52 am, Simon Mullis [EMAIL PROTECTED] wrote:
 Consider the following hash:

 h = { 1 : a\r, 2 : b\n }
 
 In Python, this called a dict.  hash sounds so... perlish.

A hash is also a mixture, a jumble or mess, as in hash browns, or as in 
to make a hash of something.

Also, a hash table is the conventional Computer Science term for what 
Python calls dicts and Perl calls associative arrays.


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

Re: Python String Immutability Broken!

2008-08-25 Thread Gabriel Genellina
En Mon, 25 Aug 2008 17:31:22 -0300, Hendrik van Rooyen [EMAIL PROTECTED] 
escribió:
 Patrick Maupin pmauail.com wrote:

But let me get this straight:   Are you just complaining that if you
pass a string to an arbitrary C function using ctypes, that that
arbitrary function can modify the string?

 Actually, I am not complaining - I am asking for advice on the side
 effects of what I am doing, which is replacing a bunch of bits
 in what is essentially an output bit field with the corresponding
 input bits at the same addresses read back from a simulated i/o
 bus structure.  And I would also like to know if there is a better
 way of doing this.

To avoid altering the equilibrium of the whole universe, use 
ctypes.create_string_buffer:
http://python.net/crew/theller/ctypes/tutorial.html#fundamental-data-types

-- 
Gabriel Genellina

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


Re: newbie question

2008-08-25 Thread Manuel Ebert

Hi sharon,

the problem is here that
a = 12,123
will actually create a tuple with two elements (namely 12 and 123):
 a = 12,123
 a
(12, 123)

Converting this to a string yields '(12, 123)', which is not what you  
want (sounds confusing, bit soon you'll see how many amazing things  
can be done like this :-)


Try:
 a = 12,123
 a = int(a.replace(',', ''))

I don't know the urllib, but I suppose if you use it to fetch content  
from a web page it will return strings anyway.


On Aug 25, 2008, at 5:14 PM, sharon k wrote:




thank you for your prompt reply.

sorry seems i run into another problem, as follow;

 a = 12,123
 b = str(a)
 c = int(b.replace(',', ''))
Traceback (most recent call last):
  File stdin, line 1, in module
ValueError: invalid literal for int() with base 10: '(12 123)'

the comma has become an empty space, it cannot be converted to an  
integer. i try the above in a winxp python command line.



On Mon, Aug 25, 2008 at 10:48 PM, Gerhard Häring [EMAIL PROTECTED]  
wrote:

sharon k wrote:
hi all,

i am new to python.

i fetch a webpage with urllib, extract a few numbers in a format as  
follow;


10,884
24,068

my question is how to remove the comma between the number, since i  
have to add them up later.


Strings have a replace method. Calling replace(,, ) on the  
string will do the trick here.


-- Gerhard


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


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


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


Re: rspec for python

2008-08-25 Thread John Roth
On Aug 25, 8:58 am, Gerhard Häring [EMAIL PROTECTED] wrote:
 Rustom Mody wrote:
  Is there anything equivalent to rspec for python?

 I had to Google to see what it is: A Behaviour Driven Development
 framework for Ruby.

 In a blog article from Ian Bicking says that it is impossible to have a
 Python port of this because Python doesn't allow you to inject methods
 into the object class and suggests Python's doctest module as an
 alternative.

 Have you actually used this rspec thing in Ruby? I always wonder with
 such things.

 Same with all the other hyped technologies of yesteryear. Anybody out
 there who really uses model-driven development?

 -- Gerhard

In this case Ian (for whom I have a great deal of respect) is simply
wrong. I know because I did it. Of course, it wasn't a port - I
implemented the underlying language of an earlier version from scratch
before I lost interest.

Injecting methods into the object class is a tactical decision. There
are a lot of things that make Ruby more suitable than Python for
writing embedded DSLs; that is only one of them. Compare Rake and
Scons - the Ruby and Python embedded DSL build systems that are
intended to replace Make, Ant and similar external build DSLs. You can
see the difference in fluency.

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


Re: Python String Immutability Broken!

2008-08-25 Thread Patrick Maupin
On Aug 25, 3:31 pm, Hendrik van Rooyen [EMAIL PROTECTED] wrote:
 Actually, I am not complaining - I am asking for advice on the side
 effects of what I am doing, which is replacing a bunch of bits
 in what is essentially an output bit field with the corresponding
 input bits at the same addresses read back from a simulated i/o
 bus structure.  And I would also like to know if there is a better
 way of doing this.

Whenever I do low-level stuff like this, I'm in one of two modes:

Mode #1:  I'm using somebody else's C library and the overhead of
doing so is small.

Mode #2:  I need to code my own low-level stuff (for speed, IO access,
whatever).

In mode 1, I try not to break out a compiler.  ctypes is great for
this, and the results are pure python to the extent that you can
give pure python to someone else with the same C library, and it will
work.  No muss, no fuss, no makefile, no question that ctypes is
awesome stuff.

In mode 2, I have to break out a compiler.  I almost never do this
without ALSO breaking out Pyrex.  Pyrex is also awesome stuff, and in
Pyrex, you can easily create a (new) Python string for your results
without having to worry about reference counting or any other really
nasty low level interpreter details.  You can code a lot of stuff in
pure Pyrex, and you can easily mix and match Pyrex and C.

Pyrex and ctypes are both tools which let me connect to non-Python
code without having to remember to handle Python interpreter internals
correctly.  If I can get by with ctypes, I do, but if I actually have
to code in something other than Python to get the job done, I bypass
ctypes and go straight for Pyrex.
--
http://mail.python.org/mailman/listinfo/python-list


Re: When I do from lxml import etree I've this error : AttributeError: 'module' object has no attribute 'BytesIO'

2008-08-25 Thread Stefan Behnel
KLEIN Stéphane wrote:
 Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) 
 from lxml import etree
 Traceback (most recent call last):
   File stdin, line 1, in module
   File lxml.etree.pyx, line 40, in lxml.etree (src/lxml/
 lxml.etree.c:119415)
 AttributeError: 'module' object has no attribute 'BytesIO'

Do you have a module called io lying around in your Python path somewhere?
lxml.etree checks for io.BytesIO (Py2.6/3.0) being available when it starts
up, and only failing that, falls back to StringIO.StringIO (Py = 2.5).

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

Re: newbie question

2008-08-25 Thread sharon k
much thanks, your instructions are clear, problem solved!

:)

On Mon, Aug 25, 2008 at 11:43 PM, Manuel Ebert [EMAIL PROTECTED] wrote:

 Hi sharon,

 the problem is here that
 a = 12,123
 will actually create a tuple with two elements (namely 12 and 123):
  a = 12,123
  a
 (12, 123)

 Converting this to a string yields '(12, 123)', which is not what you want
 (sounds confusing, bit soon you'll see how many amazing things can be done
 like this :-)

 Try:
  a = 12,123
  a = int(a.replace(',', ''))

 I don't know the urllib, but I suppose if you use it to fetch content from
 a web page it will return strings anyway.


 On Aug 25, 2008, at 5:14 PM, sharon k wrote:



 thank you for your prompt reply.

 sorry seems i run into another problem, as follow;

  a = 12,123
  b = str(a)
  c = int(b.replace(',', ''))
 Traceback (most recent call last):
  File stdin, line 1, in module
 ValueError: invalid literal for int() with base 10: '(12 123)'

 the comma has become an empty space, it cannot be converted to an integer.
 i try the above in a winxp python command line.


 On Mon, Aug 25, 2008 at 10:48 PM, Gerhard Häring [EMAIL PROTECTED] wrote:
 sharon k wrote:
 hi all,

 i am new to python.
 
 i fetch a webpage with urllib, extract a few numbers in a format as
 follow;

 10,884
 24,068

 my question is how to remove the comma between the number, since i have to
 add them up later.

 Strings have a replace method. Calling replace(,, ) on the string will
 do the trick here.

 -- Gerhard


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


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



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

Re: tkinter: Round Button - Any idea?

2008-08-25 Thread George Trojan

akineko wrote:

Hello everyone,

I'm trying to implement a virtual instrument, which has buttons and
displays, using Tkinter+Pmw.
One of items on the virtual instrument is a round button.
This is imitating a tact switch.

Tkinter has a Button class, which I can assign a button image.
However, when the button is depressed, the rectangle is sunken (rather
than the round button).

Probably I need to prepare two images, normal one and depressed one,
and implement all button behaviours by myself.
But before reinventing everything by myself, I'm wondering if there is
an easy way to implement or there is existing widget example of such
button.
So far, I couldn't find any good examples.

Any suggestions are highly appreciated.

Best regards,
Aki Niimura


Try 
http://search.cpan.org/~darnold/Tk-StyledButton-0.10/lib/Tk/StyledButton.pod. 
This is Perl, but it might be worthwhile to take a look at implementation.


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


Why do all my loggers start auto-disabled?

2008-08-25 Thread jonfroehlich
I am a relative newbie to Python and its logging infrastructure;
however, I have programmed extensively with Java/C# and log4j and
log4net. That, I suppose, could be the root of my problem :)

I am trying to setup one logger per module (as this is roughly
analogous to how I've used log4j/log4net). However, I've noticed that
my loggers have the disabled flag set to true (more accurately, 1)
when they are initialized. For each logger, do I have to force
disabled = False? To make this more concrete, here is an example.

In example.py:

import logging
import logging.config

_log = logging.getLogger(prediction.predict)

def main():
logging.config.fileConfig('logconfig.conf')
_log.warn(test warning!)

if __name__ == __main__:
main()

Unfortunately, this does not print out test warning! and if I put a
breakpoint at the _log.warn(test warning!) line, _log.disabled
equals 1. If I  change main to:

def main():
logging.config.fileConfig('predict_logconfig.conf')
_log.disabled = False
_log.warn(test warning!)

It works! So, am I doing something wrong or do I always have to force
my loggers to be enabled? Should I update my configuration file so
that loggers start as enabled? Here is my config file
(logconfig.conf):

[formatters]
keys: detailed,simple

[handlers]
keys: console,filelog

[loggers]
keys: root

[formatter_simple]
format: %(levelname)s : %(module)s.%(funcName)s (%(lineno)d): %
(message)s

[formatter_detailed]
format: %(asctime)s %(levelname)s : %(module)s.%(funcName)s (%
(lineno)d): %(message)s

[handler_console]
class: StreamHandler
args: []
formatter: simple

[handler_filelog]
class: FileHandler
args: [predictionLog.txt]
formatter: detailed

[logger_root]
level: INFO
handlers: filelog, console



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


How to setup environment for python?

2008-08-25 Thread Robert Dailey
Hi,

I'm running on Linux and I'm executing a python script as a subversion
post-commit hook. I'm finding that I'm running into a lot of random issues,
and I'm guessing this has to do with my environment not being properly
setup. From what I've gathered, the environment is not setup when the script
is run from Subversion. I've setup my Shebang to look like:

#!/usr/bin/env python

and:

#!/usr/bin/python

But still it continues to fail. The 'import' statements work perfectly fine,
but when I do something like:


raise Exception( os.getlogin() )

This fails, saying that is an invalid argument (when run by Subversion),
however when I run it manually from the console it works perfectly fine. I'm
assuming that os.getlogin(), when run by Subversion, is returning None, or
something similar, which is why this is failing. So, basically if someone
could tell me what I need to setup in my script file to make sure Python has
everything it needs to function properly I'd appreciate it. Thank you.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python String Immutability Broken!

2008-08-25 Thread Terry Reedy



Ken Seehart wrote:

Hendrik van Rooyen wrote:
 
...


Actually, I am not complaining - I am asking for advice on the side
effects of what I am doing, which is replacing a bunch of bits
in what is essentially an output bit field with the corresponding
input bits at the same addresses read back from a simulated i/o
bus structure.  And I would also like to know if there is a better
way of doing this.
  

Yes, there is a better way.  Use a character array instead of a string.

http://python.net/crew/theller/ctypes/tutorial.html#arrays


Which essentially is the bytearray type of 3.0.

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


ANN: Leo 4.5 beta 4 released

2008-08-25 Thread Edward K Ream
Leo 4.5 beta 4 is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106

This beta 4 release will likely be the last release before Leo 4.5 final.

Leo 4.5 contains many important new features.  See below for details.

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.5:
--

- Full support for @shadow files in Leo's core.
- Major improvements to Leo's key binding code.
- The beginning of usable vim-like bindings.
- uA's may now be associated with vnodes in @thin and @shadow files.
- Several magor reorganizations of Leo's code:
  including sax-based parsing, support for the Graph world (unified nodes),
  simplified drawing code.
- Leo is now an installable package.
- Prepared code to be ready for Python 3.0.
- Many small improvements and bug fixes.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Forum:http://groups.google.com/group/leo-editor
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
Bzr:  http://code.launchpad.net/leo-editor/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


QT 4.4 and timedelta

2008-08-25 Thread admoore
Maybe I'm missing something obvious, but is there a QT object to
represent time intervals, a la datetime.timedelta?

I'm working on a utility that displays database query results from a
postgres database (using psycopg2) in a QTableView.  For columns
created using age(some_date_column), I get a datetime.timedelta
object from psycopg2.

What I'd like is to be able to format this column in a friendly way
(say 7 years, 2 months, 4 days), yet have the QTableView treat it
properly (e.g. for sorting purposes, not sorting it lexically but by
the actual length of time).

Anyone have any input or ideas on this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: QT 4.4 and timedelta

2008-08-25 Thread Mohamed Yousef
I'm not very sure about this , but it's logicallay enough to be said
i think the QTableView ordering mechanism must provide some overriding
functionality through accepting a comparing function from you
check it

On Mon, Aug 25, 2008 at 7:48 PM, admoore [EMAIL PROTECTED] wrote:
 Maybe I'm missing something obvious, but is there a QT object to
 represent time intervals, a la datetime.timedelta?

 I'm working on a utility that displays database query results from a
 postgres database (using psycopg2) in a QTableView.  For columns
 created using age(some_date_column), I get a datetime.timedelta
 object from psycopg2.

 What I'd like is to be able to format this column in a friendly way
 (say 7 years, 2 months, 4 days), yet have the QTableView treat it
 properly (e.g. for sorting purposes, not sorting it lexically but by
 the actual length of time).

 Anyone have any input or ideas on this?
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Terry Reedy



Paul McGuire wrote:


Pythonistically speaking, even though a dict is a mutable thing, I'm
learning that the accepted practice for methods like this is not so
much to update in place as it is to use generator expressions to
construct a new object.


I disagree.  The convention is that mutation methods should return None.

  For example, given a list of integers to 100,

instead of removing all of the even numbers (with the attendant
hassles of updating a list while iterating over it), just create a new
list of the numbers that are not even.


This is because each removal is O(n), making the entire process O(n*2), 
whereas a new list is O(n) -- and the hassle of remembering to iterate 
in reverse when doing removals.



Perhaps I am overgeneralizing from comments I have read here on c.l.py
about creating new lists instead updating old ones.


I think so.  Removals and insertions are importantly different from 
change in place.  If I wanted to square each number in a list, and *did 
not need the original list*, I would not hesitate to do it in place.


The newish sorted() and reversed() built-ins were meant to complement 
list.sort and list.reverse, not replace them.


tjr

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


Re: The Importance of Terminology's Quality

2008-08-25 Thread norseman

Arne Vajhøj wrote:

Paul Wallich wrote:

Martin Gregorie wrote:

On Fri, 22 Aug 2008 22:56:09 +, sln wrote:

On Thu, 21 Aug 2008 09:11:48 -0500, [EMAIL PROTECTED] (Rob Warnock) wrote:

[EMAIL PROTECTED] wrote:



...(snip)


I thought microcode was relative well defined as being the software
used to implement instructions that were not fully implemented in
hardware.

http://en.wikipedia.org/wiki/Microcode does not make me think otherwise.

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




Right on. Microcode is the CPU's macro(s).
  Machine language is the bit patterns that cause whatever.
The CPU designer decides these.
  Assembly is the human memory aid nmenonices assigned to the 


bit patterns. This allows re-assigning bit patterns to the
nmenonices when changing designers.  An Assembler usually
has a few computing aids so the poor human doesn't have to
keep using his fingers to decide the address of or distance
to something. :)  Later models of Assemblers try to emulate
a high level compiler in terms of added functions supplied.
At any rate: Assembly is the nmenonices , Assembler is the
program that converts the nmenonices to machine code.

 ld a,02h
 ld b,1Ah
 Call OS

 0E021E1ACD20  (or z0: db 0E021E1ACD20h  for direct implant)

 1110001011010110011010010

On the Z80:
The first set is Assembly
The second is the hexadecimal version of the Assembly
The third is the machine language it generates represented in binary.
  (Do you really want to write Excel solely in machine language? You do
   realize the program would be completely non-portable?)

On a Televideo screen this is the CLEAR SCREEN command.  It was the 
standard clear screen for most terminals of the CP/M days.  One could 
simply use the debugger, type in the hex and save as z.com.  Then when 
one typed zcr the jumbled up screen cleared to system prompt in the 
upper left.
(Naturally Microsoft couldn't allow the standards long in use so today 
this would be stated as CLSENTER. :)


Question:  What does any of this have to do with:
 The Importance of Terminology's Quality
when using Webster to define the words in the above line?


Been fun.

Steve
[EMAIL PROTECTED]

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


Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Grzegorz Staniak
On 25.08.2008, Terry Reedy [EMAIL PROTECTED] wroted:

 The newish sorted() and reversed() built-ins were meant to complement 
 list.sort and list.reverse, not replace them.

BTW, is there a reason why sorted() on a list returns a list, while 
reversed() on the same list returns an iterator?

GS
-- 
Grzegorz Staniak gstaniak _at_ wp [dot] pl
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why do all my loggers start auto-disabled?

2008-08-25 Thread Peter Otten
jonfroehlich wrote:

 I am a relative newbie to Python and its logging infrastructure;
 however, I have programmed extensively with Java/C# and log4j and
 log4net. That, I suppose, could be the root of my problem :)
 
 I am trying to setup one logger per module (as this is roughly
 analogous to how I've used log4j/log4net). However, I've noticed that
 my loggers have the disabled flag set to true (more accurately, 1)
 when they are initialized. For each logger, do I have to force
 disabled = False? To make this more concrete, here is an example.
 
 In example.py:
 
 import logging
 import logging.config
 
 _log = logging.getLogger(prediction.predict)
 
 def main():
 logging.config.fileConfig('logconfig.conf')
 _log.warn(test warning!)
 
 if __name__ == __main__:
 main()
 
 Unfortunately, this does not print out test warning! and if I put a
 breakpoint at the _log.warn(test warning!) line, _log.disabled
 equals 1. If I  change main to:
 
 def main():
 logging.config.fileConfig('predict_logconfig.conf')
 _log.disabled = False
 _log.warn(test warning!)
 
 It works! So, am I doing something wrong or do I always have to force
 my loggers to be enabled? Should I update my configuration file so
 that loggers start as enabled? Here is my config file

I think you have to put the logger into your config file to avoid that it
will be disabled by fileConfig():

 (logconfig.conf):
 
 [formatters]
 keys: detailed,simple
 
 [handlers]
 keys: console,filelog
 
[loggers]
keys: root, predict

# ...

[logger_predict]
qualname: prediction.predict
handlers:

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


Micro-threading PEP proposal announcement

2008-08-25 Thread Bruce Frederiksen
I wanted to make everybody aware that I've posted a (rather long and
involved) PEP proposal for adding micro-threading to Python on
python-ideas for feedback and review.

In a nutshell, this proposal implements the Twisted Deferred/Reactor at
the C level so that the Python programmer gets the advantages that Twisted
offers without having to write their code in an event driven style.  Thus,
legacy Python code not written in the Twisted style (Django, TurboGears,
WSGI apps) will gain the benefits of Twisted with almost no additional
work.

This PEP provides similar benefits to GUI toolkits where, again, Python
programmers have been faced with event driven programming.  So using this
PEP, GUI toolkits could hide this event driven programming from the Python
programmer, making GUI programming much easier.  For example, you would no
longer have to use a modal dialog just to make the programming easier.

The C-level Deferreds and Reactor are not made visible to the Python
programmer (as they are in Twisted).

Rather, what is visible is a very simple micro-thread that allows for
start_and_forget threads, parallel threads (where you're only
interested in the final return value) and fully cooperative threads
communicating over micro-pipes (which, BTW, gives us a new way to write
generators that allows one generator to simply call another one to have
the second generator's output included with its own output without having
to capture and pass back values).

As there is a great deal of traffic on comp.lang.python, I don't expect to
be able to keep up with the posts here and would prefer to discuss this
on python-ideas...

If there is any interest in this, please let me know!  If I don't see any
interest, I'll assume that it's not solving a real problem and will let it
quietly die on the vine...

Thank you for your attention!

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


Re: Equivalents of Ruby's ! methods?

2008-08-25 Thread Fredrik Lundh

Grzegorz Staniak wrote:

BTW, is there a reason why sorted() on a list returns a list, while 
reversed() on the same list returns an iterator?


the algorithm required to sort a sequence is something entirely 
different from the algorithm required to loop over a sequence in 
reverse.  we went through this a few days ago.


/F

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


Re: generate methods at runtime, but the wrong one gets called

2008-08-25 Thread Marc 'BlackJack' Rintsch
On Mon, 25 Aug 2008 12:52:44 +0200, Maric Michaud wrote:

 In other OOP language I would encourage you to implement this logic in
 some sort of singleton, but in python we don't like this construct,
 module level variables and function do perfectly the job, simple as
 they are.

Modules are some sort of singletons in Python.

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


Re: py2exe importing a package not in library.zip

2008-08-25 Thread mypetslug
On Aug 20, 4:48 pm, [EMAIL PROTECTED] wrote:
 Hi,
 I'm sorry if this has been asked before, but I can't seem to find an
 answer to this anywhere and so far, trial and error hasn't gotten me
 far either.

 Using python 2.4, I've created a testing application.  When the app
 starts up, I do a [code]from tests import *[/code] and it looks at
 the /tests directory and loads up all the tests it finds at that
 time.  This works fine when interpreting the python code directly.
 The problem I'm having is trying to create an executable for
 distribution.

 What I'd like to be able to do is to include everything in the
 library.zip *except* the tests directory and then as I (or whoever)
 creates more and more tests, have the ability to simply drop them into
 the directory and the next time the app starts, it'll pick them up.
 However, if I don't include the tests in library.zip, then when I hit
 the [code]from tests import *[/code], it complains AttributeError:
 'module' object has no attribute 'test1' when it gets to the first
 test.  And If I do include the tests in the library.zip, it works with
 the tests that I have now, but then I still can't add any new ones
 without the attribute error unless I regenerate the exe every time.

 Basically, it seems like it comes down to importing a package outside
 the library.zip.  So, is there any way to do this with py2exe?  Or
 even another exe creating application?

 Thanks,MyPetSlug

Hi Again,
So, someone responded with some tips about paths, so my paths are
correct in the exe and I verified this by printing them out.  So, my
problem is not that, I guess.  And in my original email, I simplified
my scenario because I thought it was a problem with paths.  So, let me
back up a little.

My tests directory actually has several sub-directories, so it's laid
out like this: tests/testCategory1, tests/testCategory2, tests/
testCategory1/subCategory1/test1, and so on.  With potentially
hundreds of tests, I needed some organization.  Anyway, in my tests
directory, I have an __init__.py with  __all__=[testCategory1,
testCategory2] and it's this that the exe keeps choking on.  Even
though I append the path directly above the __all__ via 
sys.path.append(os.path.abspath('') + '\\tests') and
sys.path.append(os.path.abspath('') + '\\tests\\testCategory1') (the
second one just to be safe), when I execute the import *, it still
tells me AttributeError: 'module' object has no attribute
'testCategory1'

Again, this works fine when just executing the python code without the
exe.  What am I doing wrong?  Or can anyone even point me to the right
place to possibly find an answer?

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


RE: python/xpath issue..

2008-08-25 Thread bruce
never mind...

it was an issue with the targeted site... it's sending screwed up html the
times when i get an err...

thanks though!


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of bruce
Sent: Monday, August 25, 2008 4:49 AM
To: python-list@python.org
Subject: python/xpath issue..


hey guys...

got a weird, hopefully simple issue.

the following sample bit of script is stripped down, and simply gets the
form node from the specified site schedule.psu.edu.

the problem i run into is that the dom/xpath from the libxml2dom works, and
i get the dom object everytime i run the app, but that the xpath is
intermittent!!! in other words, i can run the script 10 times.. and it might
work 7 or 8 times.. the other times, the xpath doesn't give the nodes
back...

when it works, name1_ in the app should be a list of nodes (for the 2 forms
in the page). and len_ should be 2.

is there anything you might suggest that i try in order to get a better
handle on exactly what might be going on here...

keep in mind, i'm not a python guy, just trying to get this to consistently
work... my suspicion is that the culprit might be memory related...

i'm running linux, on a x86 dual core with 4G ram. the python is 2.5.1.

thoughts/comments/etc would be appreciated...

-thanks!!!


#!/usr/bin/python
#
# test.py
#
# scrapes/extracts the basic data for the college
#
#
# the app gets/stores
#  name
#  url
#  address (street/city/state
#  phone
#
##
#test python script
import re
import libxml2dom
import urllib
import urllib2
import sys, string
from  mechanize import Browser
import mechanize
#import tidy
import os.path
import cookielib
from libxml2dom import Node
from libxml2dom import NodeList
import subprocess
import time


#
# Parse pricegrabber.com

##cj = p
##COOKIEFILE = 'cookies.lwp'
#cookielib = 1


urlopen = urllib2.urlopen
#cj = urllib2.cookielib.LWPCookieJar()
##cj = cookielib.LWPCookieJar()
Request = urllib2.Request
br = Browser()
br2 = Browser()

##if cj != None:
##  print sss
###install the CookieJar for the default CookieProcessor
##  if os.path.isfile(COOKIEFILE):
##  cj.load(COOKIEFILE)
##  print foo\n
##  if cookielib:
##  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
##  urllib2.install_opener(opener)
##  print foo2\n

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values1 = {'name' : 'Michael Foord',
  'location' : 'Northampton',
  'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

url=http://schedule.psu.edu/;
#===


if __name__ == __main__:
# main app

txdata = None

#

##br.set_cookiejar(cj)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.addheaders = [('User-Agent', 'Firefox')]

print url =,url
br.open(url)
##cj.save(COOKIEFILE)# resave cookies

res = br.response()  # this is a copy of response
s = res.read()
print slen=,len(s)

# s contains HTML not XML text
d = libxml2dom.parseString(s, html=1)
print d,d

name_=[]
len_=0
name_ = d.xpath(//form)
#name_ = d.xpath(/html/body/form)
print name1,name_
len_ = len(name_)
print len,len(name_)
#print sdlfs
sys.exit()
#   else:
#   print err in form_ID


print here...


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

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


RE: swig or ctypes , under the gun and need help

2008-08-25 Thread Sells, Fred
Diez wrote...
 I don't know swig, but if all you have is a real C-API, try  
 use ctypes.
 It's much easier to create bindings for, keeps you fully in 
 the warm and
 cozy womb of python programming and doesn't need no 
 compilation to create
 the actual binding.
 
You're right the ctypes does seem more pythonesque; however I'm still stuck 
trying return all these parameters
that the c api uses.  my ctypes code is below.  It just quits running when I 
try to print 
one of the args I did a pass byref on, no error out, nothing.  admittedly I'm a 
newbie to ctypes and not much of a c programmer
but I could sure use some help.  my ctypes test code follows...

from ctypes import *

'''
create shared object file like so.
gcc -shared -o rug520.so  rug520.c

the c api I want to call is like this.
int RugCalc( char * sMdsRecord, 
 char * sRehabType, 
 char * sModel, 
 int iQuarterlyFlag, 
 double nCmiArray[], 
  char * sRugHier,
 char * sRugMax, 
 int * iRugHier,
 int * iRugMax, 
 double * nCmiValueHier,
 double * nCmiValueMax, 
 int * iAdlSum,
 int * iCpsCode, 
 char * sRugsVersion,
 char * sDllVersion, 
 int * iError );
'''
libc = CDLL(rug520.so)

CmiArrayDef = c_double * 59

ZeroCmi = CmiArrayDef( )  #this is a table used internally, but 0.0 should work 
until I figure out the rest.



def getrug(mds):
#print mds
sMdsRecord = c_char_p()
sRehabType = c_char_p()
sModel = c_char_p()
iQuarterlyFlag = c_int()
sRugHier  = c_char_p()
sRugMax = c_char_p()
iRugHier = c_int()
iRugMax = c_int()
nCmiValueHier = c_double()
nCmiValueMax  = c_double()
iAdlSum = c_int()
iCpsCode = c_int()
sRugsVersion = c_char_p()
sDllVersion = c_char_p()
iError = c_int()
sMdsRecord.value = mds
sRehabType = 'mcare'
sModel = '34'

results = libc.RugCalc(sMdsRecord, sRehabType, sModel, iQuarterlyFlag, 
 ZeroCmi,
 byref(sRugHier),
 byref(sRugMax), 
 byref(iRugHier),
 byref(iRugMax), 
 byref(nCmiValueHier),
 byref(nCmiValueMax), 
 byref(iAdlSum),
 byref(iCpsCode), 
 byref(sRugsVersion),
 byref(sDllVersion), 
 byref(iError ))
print 'results', results
print iQuarterlyFlag.value
print 'sRugMax', sRugMax  #this print causes an exit, tried .value with 
same results
print 'return'  #I never see this print.

datafile = open('mdsdata.txt')
for d in datafile:
if d[0]=='B':
getrug(d)
break

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


Re: Interrupt python thread

2008-08-25 Thread Gabriel Genellina
En Mon, 25 Aug 2008 05:00:07 -0300, BlueBird [EMAIL PROTECTED]  
escribi�:

On Aug 24, 8:35 pm, Dennis Lee Bieber [EMAIL PROTECTED] wrote:


        The only safe way to abort a thread is by having it exit on  
its

own. This means one needs a means of setting an attribute that each
thread periodically checks within a while loop.



Unfortunately, this does not map very well with my program. Each of my
threads are calling foreign code (still written in python though),
which might be busy for 1 to 10 minutes with its own job.

I wanted something to easily interrupt every thread to prevent my
program to stall for 10 minutes if I want to stop it (getting tired of
killing python all the time).


If the foreign Python code is running on your own process, can't you make  
it check a flag periodically?
If it runs as another process, killing it is a lot safer than killing a  
thread.


--
Gabriel Genellina

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

Private attribute

2008-08-25 Thread Ken Starks

I have a class with an attribute called 'gridsize' and I want
a derived class to force and keep it at 0.8 (representing 8mm).

Is this a correct, or the most pythonic approach?



def __getattr__(self,attrname):
if attrname == 'gridsize':
return 0.8

def __setattr__(self,attrname,value):
if attrname == 'gridsize':
pass
else:
self.__dict__[attrname]=value

#


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


os.popen() interferes with os.fork()?

2008-08-25 Thread JohnMudd
On Linux I get a close failed: [Errno 10] No child processes msg for
each fork.  But only if I have a pipe open.  I don't understand the
connection between the popen and the forks.  Am I doing something
wrong?


#! /usr/bin/env python

import os
import sys
import time

p = os.popen('top -b -d1')

n = 3
t1 = time.time()
for i in range(n):
  pid = os.fork()
  if pid == 0:
sys.exit(0)
delay = time.time() - t1
print 'rate: %.1f fork/sec' % (n/delay)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Private attribute

2008-08-25 Thread Ken Starks

Ken Starks wrote:

I have a class with an attribute called 'gridsize' and I want
a derived class to force and keep it at 0.8 (representing 8mm).

Is this a correct, or the most pythonic approach?



def __getattr__(self,attrname):
if attrname == 'gridsize':
return 0.8

def __setattr__(self,attrname,value):
if attrname == 'gridsize':
pass
else:
self.__dict__[attrname]=value

#


Cheers,
Ken.


Perhaps I should mention the alternative I had in mind:

###

class xyz:
  def __init__(self):
self.__dict__['a'] = 123
self.b=456


  def __setattr__(self,attrname,value):
if attrname == 'a':
pass
else:
self.__dict__[attrname]=value

  # __getattr__() not redefined.



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


Re: os.popen() interferes with os.fork()?

2008-08-25 Thread Hrvoje Niksic
JohnMudd [EMAIL PROTECTED] writes:

 On Linux I get a close failed: [Errno 10] No child processes msg
 for each fork.  But only if I have a pipe open.  I don't understand
 the connection between the popen and the forks.  Am I doing
 something wrong?

Yes: don't use sys.exit, use os._exit.  This is not specific to
Python; in C you'd also need to use _exit(2) in preference to exit(3)
to exit a forked process.

With sys.exit(0) changed to os._exit(0), the program outputs:

rate: 2962.1 fork/sec
--
http://mail.python.org/mailman/listinfo/python-list


Re: Private attribute

2008-08-25 Thread castironpi
On Aug 25, 2:09 pm, Ken Starks [EMAIL PROTECTED] wrote:
 Ken Starks wrote:
  I have a class with an attribute called 'gridsize' and I want
  a derived class to force and keep it at 0.8 (representing 8mm).

  Is this a correct, or the most pythonic approach?

  

      def __getattr__(self,attrname):
          if attrname == 'gridsize':
              return 0.8

      def __setattr__(self,attrname,value):
          if attrname == 'gridsize':
              pass
          else:
              self.__dict__[attrname]=value

  #

  Cheers,
  Ken.

 Perhaps I should mention the alternative I had in mind:

 ###

 class xyz:
    def __init__(self):
      self.__dict__['a'] = 123
      self.b=456

    def __setattr__(self,attrname,value):
          if attrname == 'a':
              pass
          else:
              self.__dict__[attrname]=value

    # __getattr__() not redefined.

 

This is just me, but I don't think that Python is the right language
for your program.  In Python it's extra easy to get around that
obstacle.  Python is more about freedom and discipline.
--
http://mail.python.org/mailman/listinfo/python-list


python - firefox dom/xpath question/issue

2008-08-25 Thread bruce
Hi.

Got a test web page, that basically has two html tags in it. Examining
the page via Firefox/Dom Inspector, I can create a test xpath query
/html/body/form which gets the target form for the test.

The issue comes when I examine the page's source html. It looks like:
html
body
/body
/html

html
body
.
.
.
/body
/html

I've simplified things a bit... but basically, the 1st html/body is empty,
with the 2nd containing the data/nodes I need.

In using xpath(/html/body/form), the app returns nothing/crashes.. I've
tried to do something like xpath(/html[position()=0]) as well with no
luck... It's as if xpath only looks at the 1st html that it sees in a given
page. I can't seem to find any docs for xpath to work around this. I'm using
the libxml2dom for python 2.5.1.

Any thoughts/comments...

If I comment out the 1st html section, things work as they should. The test
code is below...

thanks

--
#!/usr/bin/python
#
# test.py
#
# scrapes/extracts the basic data for the college
#
#
# the app gets/stores
#  name
#  url
#  address (street/city/state
#  phone
#
##3
#test python script
import re
import libxml2dom
import urllib
import urllib2
import sys, string
from  mechanize import Browser
import mechanize
#import tidy
import os.path
import cookielib
from libxml2dom import Node
from libxml2dom import NodeList
import subprocess
import time


#
# Parse pricegrabber.com

##cj = p
##COOKIEFILE = 'cookies.lwp'
#cookielib = 1


urlopen = urllib2.urlopen
Request = urllib2.Request
br = Browser()
br2 = Browser()

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values1 = {'name' : 'Michael Foord',
  'location' : 'Northampton',
  'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

url=http://schedule.psu.edu/;
#===


if __name__ == __main__:
# main app

txdata = None

#

##br.set_cookiejar(cj)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.addheaders = [('User-Agent', 'Firefox')]

print url =,url
#br.open(url)
##cj.save(COOKIEFILE)# resave cookies

#res = br.response()  # this is a copy of response
#s = res.read()
#print slen=,len(s)
tfile = open(/college/psu1.dat)
s = tfile.read()
print s


# s contains HTML not XML text
d=[]
d = libxml2dom.parseString(s, html=1)
print d,d

name_=[]
len_=0

br.open(url)
##cj.save(COOKIEFILE)# resave cookies

#res = br.response()  # this is a copy of response
#s = res.read()
print slen=,len(s)

# s contains HTML not XML text
#d=[]
#d = libxml2dom.parseString(s, html=1)
#print d,d

#name_ = d.xpath(//form)
name_ = d.xpath(/html/body/form)
len_ = len(name_)
print len=,len_

print name1,name_
print len,len(name_)
#print sdlfs
sys.exit()
#   else:
#   print err in form_ID


print here...


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


Struct class random access

2008-08-25 Thread castironpi
struct.Struct lets you encode Python objects into structured memory.
It accepts a format string, and optionally a buffer and offset to/from
which to read/write the structure.  What do you think of random access
for the results?

(unproduced)
 packer= struct.Struct( 'IIIf255p' )
 packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' )
 packer.unpack_from( buf, off, 2 ) #reads field 2
30

Does this take a PEP, or just a patch submission?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Private attribute

2008-08-25 Thread André
On Aug 25, 3:47 pm, Ken Starks [EMAIL PROTECTED] wrote:
 I have a class with an attribute called 'gridsize' and I want
 a derived class to force and keep it at 0.8 (representing 8mm).

 Is this a correct, or the most pythonic approach?

 

      def __getattr__(self,attrname):
          if attrname == 'gridsize':
              return 0.8

      def __setattr__(self,attrname,value):
          if attrname == 'gridsize':
              pass
          else:
              self.__dict__[attrname]=value

 #

 Cheers,
 Ken.

Why not make gridsize a property with no set method?

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


Unexpected global variable behaviour

2008-08-25 Thread RgeeK
I'm seeing something which make me think I'm missing something  about 
how global var's behave.  I've defined a global string, right at the 
start of my .py file.


outXMLfile = abc

I define a class and do a bunch of stuff below that.  Then I have 
another class, and in it, there is a method 'def' that has:


  def OnOutfileButton(self,evt):
   (fPath, fName)=os.path.split(fullName)
print Selected output file:  + fName
outXMLfile = fName

print output file:  + outXMLfile

Print statements in random other places in the project, show outXMLfile 
prints as abc  however, in this def, it comes out as the same as fName 
(e.g. myfile.xml)   If the print line for outXMLfile is before the 
assignment to fName, it throws the error:


 UnboundLocalError: local variable 'outXMLfile' referenced before 
assignment


If I remove the line that says outXMLfile = fName
then the print statement gives me the value abc

What am I missing?  When I assign a value to update my global variable, 
it becomes a local variable. If I don't try to update it, it stays 
global.  I assume it's acting like a constant, though I have a couple of 
global lists and I seem to be able to append to them okay.


I guess I can move the variable into the parent class and get at it that 
way, but want to understand the error of my ways...


Ross.

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


Re: iterparse and unicode

2008-08-25 Thread George Sakkis
On Aug 24, 1:12 am, Stefan Behnel [EMAIL PROTECTED] wrote:
 George Sakkis wrote:
  On Aug 21, 1:48 am, Fredrik Lundh [EMAIL PROTECTED] wrote:

  George Sakkis wrote:
  It's interesting that the element text attributes after a successful
  parse do not necessarily have the same type, i.e. all be str or all
  unicode. I ported some text extraction code from  BeautifulSoup (which
  handles all text as unicode) and I was surprized to find out that in
  xml.etree the returned text's type is not fixed, even within the same
  file. Although it's not a bug, having a mixed collection of byte and
  unicode strings from the same source makes me somewhat uneasy.
  If you don't care about memory and execution performance, there are
  plenty of toolkits that guarantee that you always get Unicode strings.

  As long as they are documented, both approaches are fine for different
  cases. Currently the only reference I found about unicode in
  ElementTree is All strings can either be Unicode strings, or 8-bit
  strings containing US-ASCII only. [1], which is rather ambiguous

 It's not ambiguous in Py2.x, where ASCII byte strings and unicode strings are
 compatible. No need to feel uneasy. :)

It depends on what you mean by compatible; e.g. you can't safely do
[s.decode('utf8') for s in strings] if you have byte strings mixed
with unicode.

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


  1   2   3   >