[FAQTS] Python Knowledge Base Update -- May 20th, 2000

Fiona Czuczman fiona at sitegnome.com
Sat May 20 14:31:23 CEST 2000


Hello All,

Below are the entries I've entered today into http://python.faqts.com


[very off topic: 

"Python, embodies a harmony of chocolate kisses with hints of jasmine 
and rose. Trussardi's wild new fragrance."

Marie Claire Magazine, Australian edition - May 2000]

Enjoy your coding :-)

Fiona Czuczman


## New Entries #################################################


-------------------------------------------------------------
How can I create a stand alone "win32" executable file from a python script?
http://www.faqts.com/knowledge-base/view.phtml/aid/3111
-------------------------------------------------------------
Fiona Czuczman
Daley, MarkX

http://starship.python.net/crew/gmcm/index.html

This link will provide you with a pretty good wrapper that gives you a
one-file installer executable.  I'm pretty sure it's win32.


-------------------------------------------------------------
Where can I find information about how to manipulate Excel with Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/3093
-------------------------------------------------------------
Fiona Czuczman
Robert Citek

I strongly recommend the "Python Programming on Win32" by Mark Hammond &
Andy Robinson.  Visit http://www.oreilly.com/catalog/pythonwin32

Here is some sample code:

# this example starts Excel, creates a new workbook, 
# puts some text in the first and second cell
# closes the workbook without saving the changes
# and closes Excel.  This happens really fast, so
# you may want to comment out some lines and add them
# back in one at a time ... or do the commands interactively

from win32com.client import Dispatch

xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.Close(SaveChanges=0)
xlApp.Quit()
del xlApp

# raw_input("press Enter ...")


-------------------------------------------------------------
Is there any debugger available as part of the Python installation?
http://www.faqts.com/knowledge-base/view.phtml/aid/3106
-------------------------------------------------------------
Fiona Czuczman
Fredrik Lundh

Check out:

http://www.python.org/doc/current/lib/module-pdb.html


-------------------------------------------------------------
When a method has a boolean return, and two output-params, how do I call it?
http://www.faqts.com/knowledge-base/view.phtml/aid/3107
-------------------------------------------------------------
Fiona Czuczman
Dag Sunde, Oleg Broytmann, Fredrik Lundh

When the idl defines it like:
    boolean LoginToMarket
    (
        out long lLoginId,
        out Object supplier)
        raises (NoAccess);

...where both parameters are out-values, and the method has a 
return-value, it should be called without any parameters, and returns a 
list with the return-value at position 0, and the parameters following 
in the defined order...

[Dbg]>>> print self.m_pElTermin.LoginToMarket()
(1, 6, <omniORB.CORBA.Object instance at 1871cf0>)
[Dbg]>>>


-------------------------------------------------------------
What is the preferred way to modify an existing behaviour? Modifying inherited methods.
http://www.faqts.com/knowledge-base/view.phtml/aid/3109
-------------------------------------------------------------
Fiona Czuczman
Robin Becker, Thomas Thiele, Thomas Wouters

Problem:

Suppose I have a class A with a complicated __init__

class A:
        def __init__(self,a,b,c, d=[], e=.......):
                ......

I want to subclass A, but make some simple changes to the init
eg say I always know the value of b and d; ie b and d should be removed
from the new class __init__.

I seem to have to always copy the signature for A.__init__, is there a
way to say

class B(A):
        __init__ is like A.__init__ but has no 'b' and 'd' argument

then changes to A's signature wouldn't require recoding B's __init__

Solution:

class A:
    def __init__(self, a,b,c,d):
        .....

class B(A):
    def __init__(self, a,b):
        c = <defaultc>
        d= <defaultd>
        A.__init__(self, a,b,c,d)


When A.__init__ has a lot of arguments and you don't want to cut and 
paste these to a bunch of inheriting class methods.  Give all args from 
A.__init__not used in B default values. So you don't need to copy them.
Or put all the args together in a thing like a struct (for instance a
list) and create a default struct(list, tupel), so you need to handle
only one arg.

Use *args, **kwargs and apply()


-------------------------------------------------------------
Is there a HTML search engine written in Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/3105
-------------------------------------------------------------
Fiona Czuczman
Dale Strickland-Clark, Michal Wallace, Robert Roy, JRHoldem

If you're running it on NT, there's a free search engine you can tap 
into that comes as part of the NT 4.0 option pack.

Otherwise:

Check out http://ransacker.sourceforge.net/ .. There's an Index
class that lets you index arbitrary chunks of text.. But you'll have
to write the program that actually reads the HTML files (and strips
the HTML tags, if that's what you mean by "text content")... 

It also does a ranked searches, but you'll have to wrap that, too, if
you want the output to show up on the web.

A full featured full text indexing solution is not trivial. It all
depends on what kind of queries you want to perform. If all you want
to do are queries such as "find all files which contain the word
'dog'" that can be done quite easily, probably under 200  lines of
code for a trivial solution using sgmllib and gdbm. However if you
want to do phrase searching or stem searching or wild-card searching,
then it gets really complicated in a hurry. 

Another factor is how many files you are dealing with. Indices often
run 4-8X the size of the indexed files. And do you want to dynamically
update the index or are you happy just re-indexing the whole works
periodically. A static index is somewhat easier to build than a fully
dynamic one.

An interesting GPL'd indexing package is SWISH++
see:
http://www.best.com/~pjl/software/swish/

A good tactic might be to use this for your indexing, and running the
search engine as a daemon, building a python interface to talk to it
via Unix domain sockets or alternately shelling out and capturing and
parsing the return values.

You also might want to try using Index Server/ASP combo before going to 
any third party solution...full text searching is no trivial matter and 
chances are it'll give you all the tinkering options you could want.


-------------------------------------------------------------
I wonder if there is a way for Python to read directly the user input of a HTML form?
http://www.faqts.com/knowledge-base/view.phtml/aid/3112
-------------------------------------------------------------
Fiona Czuczman
Graham Bleach

You can use the cgi module.

There is an example of exactly that at:

http://www.devshed.com/Server_Side/Python/CGI/page4.html

You should probably read the whole article:

http://www.devshed.com/Server_Side/Python/CGI/

A good place to start for these topics:

http://www.python.org/topics/web/basic-cgi.html


-------------------------------------------------------------
How can I implement a "cancel"-button that allows a user to cancel a time-intensive function?
http://www.faqts.com/knowledge-base/view.phtml/aid/3108
-------------------------------------------------------------
Fiona Czuczman
Randall Hopper

Problem:

I have a simple graphical user interface written with Tkinter. This
allows a user to call a function by pressing on a button (or something 
like this). The function works for some minutes, somtimes up to an hour.

Solution:

The essence of the problem is you need to have your GUI (Tkinter)
process periodically checking for user events, either by returning to 
the main event loop or calling one of the "check for user events" APIs
(Tkinter's update method for example--though see caveats in the docs).

You have a number of options:

   1) Modify your work function to periodically check for user events.

                       worker() -> check_events()
                                -> check_events()
                                -> check_events()

   2) Change your work function to be event-driven.  That is, to do its 
work in pieces, saving appropriate state betweeen each piece. Just wake 
up to do a slice of work via Tkinter timers, and return to the main 
event loop after each slice to handle user events.

                       tk_timer_event -> worker()
                       tk_timer_event -> worker()
                       tk_timer_event -> worker()

   3) Fork off a subprocess to do the work.
   
   4) Create a thread to do the work.

Which one is simplest really depends on your situation (how much 
coupling there is between the GUI "thread" and the compute "thread", for 
example, using the term thread loosely here).


-------------------------------------------------------------
How do I connect to Postgresql on a Debian Linux box using Python from a Windows95 box?
http://www.faqts.com/knowledge-base/view.phtml/aid/3110
-------------------------------------------------------------
Fiona Czuczman
Johann Spies, Case Van Horsen, Martin Skøtt

Pygres is available as a Debian package.  

$apt-cache search pygres
python-pygresql - PostgreSQL module for Python
zope-pygresqlda - A Zope Database Adapter for PostgreSQL

'apt-get install python-pygresql' should install it for you.

OR:

Use the Windows ODBC drivers for Postgresql
(ftp://ftp.postgresql.org/pub/odbc/latest/) and mxODBC for Python (
http://starship.python.net/crew/lemburg/mxODBC-1.1.1.zip ).

If you havent't got a Windows compiler then try and install the
postgreSQL ODBC driver on your windows box and use the PythoN-ODBC
binding to access your database.


## Edited Entries ##############################################


-------------------------------------------------------------
How can I access MySQL from Python?
Should I use MySQLmodule or MySQLdb?
http://www.faqts.com/knowledge-base/view.phtml/aid/1432
-------------------------------------------------------------
Nathan Wallace, Fiona Czuczman
Andy Dustman

This was written by Andy Dustman.

Well, I'm the author of MySQLdb. MySQLdb is designed to work well in a
threaded environment (gives up the interpreter lock during blocking
calls), and to work with MySQL-3.22 and up; I have not tested it with
3.23, but once it stabilizes a bit, I will ensure that it continues to
work. Architecturally, it's really two modules:

_mysql: low-level C interface, transliteration of the MySQL C API to an
object-oriented Python interface.

MySQLdb: Python wrapper to _mysql that provides a DB API v2.0-compatible
interface. 

One weird/interesting thing it does is it lets you specify how values
are converted going from MySQL to Python and vice versa. There are two
dictionaries that key on types, which map to functions which do the
conversion, with sensible default conversions. (MySQL actually returns
all values to the C API as strings, and all values passed to MySQL must
be part of a literal query string.)

0.1.2 is the current version. I have reports that it dumps core on
RedHat/Alpha platforms, but I can't reproduce it on RedHat/Intel;
patches welcome. 0.1.1 doesn't have this problem, and it's still
available in the same location (no direct link on the page, however).
Other people have reported getting it to work on that crackpot OS from
out of Redmond. It also includes a patch to make Zope's ZMySQLDA to work
with it instead of MySQLmodule. Also check this page:

http://www.zope.org/Members/adustman/MySQLdb

I haven't looked at MySQLmodule a whole lot lately. Here's what I THINK
I know about it, some of which may be wrong:

- Doesn't give up the interpreter lock during blocking calls, causing
threads to block (bad for threaded things like Zope).

- MySQL-3.21 compatible only.

- Also a split interface (C module + Python wrapper).

- The C module exports a Perl-style interface (ick).

- Not really actively supported. Joe Skinner (original MySQLmodule
author) has expressed optimism that he might finally stop getting bugged
about MySQLmodule. :)


-------------------------------------------------------------
How can I use a Microsoft Access database from Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1359
-------------------------------------------------------------
Nathan Wallace, John Kos, Fiona Czuczman
Andy Robinson, Robert Roy

This is well covered in our book "Python Programming for Win32"
(O'Reilly 2000), and the examples can be downloaded from the book's
page:

  http://starship.python.net/crew/mhammond/ppw32/

Also see:

  http://starship.python.net/crew/bwilk/access.html

Unix and Linux developers can access remote MS Access databases using 
the Easysoft ODBC-ODBC Bridge. A free Personal Edition can be 
downloaded from www.easysoft.com.


-------------------------------------------------------------
How can I control MS-Access from Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1417
-------------------------------------------------------------
Nigel Linnett, Nathan Wallace, Fiona Czuczman
http://starship.python.net/crew/mhammond/win32/Downloads.html

This simple code depends on having Mark Hammond's win32-all extension 
installed.

For the best functionality run MakePy (In the tools menu of Pythonwin) 
on all Microsoft Excel Object Libraries.

###### Begin code here
# This code is available for you to use as you see fit
# Tested with Python 1.5.2 and Excel 97 and Excel 2000
# No Problems were apparent, but this does not mean there are none


import win32com.client
# Launch Excel and make it visible
ExcelApp=win32com.client.Dispatch("Excel.Application")
ExcelApp.visible = 1
# Add a new workbook to the collection (Excel doesn't always start up
# with a workbook open)
workbook = ExcelApp.Workbooks.Add()
# Add a worksheet to the current workbook
worksheet=workbook.Worksheets.Add()
 
# Do two simple nested loops
for row in range(1,10):
    for column in range(1,10):
        # Get a reference to the current cell
        cell = worksheet.Cells(row, column)
        # Create a value
        val = "Row %i, Col %i" % (row, column)
        # Set the cell Value
        # Use cell.formula to set a formula
        cell.Value=val
        #Do some fancy stuff
        cell.Font.Bold=1
# Loop through all the columns we just used
for column in range(1,10):
    # Set the width appropriately
    worksheet.Cells(1,column).ColumnWidth=12
# Save the workbook in the default location
workbook.SaveAs("exceldemo.xls")
# Quit Excel
ExcelApp.Quit()
# Then delete all the objects we just used
del(cell)
del(worksheet)
del(workbook)
del(ExcelApp)

#
###### Code Ends here
 
Hope this helps you out a bit, it works a lot better if you run makepy 
on the excel object libraries you will find.







More information about the Python-list mailing list