Python Knowledge Base Update -- March 1st, 2000

Nathan Wallace nathan at synop.com
Thu Mar 2 00:39:04 EST 2000


I've spent some time going back through newsgroup postings for the last
couple of days to start building the knowledge base:

  http://python.faqts.com

There are now 31 answers to 50 questions in the Python Knowledge Base. 
Please contribute and help build this resource.

It's generally a good idea to post these summarized answers back to the
newsgroup so people can see where their answers have been used, and
correct any mistakes I've made.  Sorry if you feel this post is
inappropriate.

Cheers,

Nathan


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


-------------------------------------------------------------
Why can I run an executable program using "python prog.py" but not as
"./prog.py"?
http://www.faqts.com/knowledge-base/view.phtml/aid/1353
-------------------------------------------------------------
Nathan Wallace
Michael Hudson

The only thing I can think of is that the hash-bang line has some
control characters or other gunk in it - have you tried `cat -v'-ing
it?


-------------------------------------------------------------
Are there any Python functions to help with linear algebra?
What is numpy used for?
http://www.faqts.com/knowledge-base/view.phtml/aid/1354
-------------------------------------------------------------
Nathan Wallace
William Park, Gary Herron

I'm looking for a module or a set of functions that does linear algebra,
things like inverses, multiplication, eigenvalues, etc..

That would be Numeric Python, which is a wrapper around Fortran
libraries, one of which does some matrix operations.  It was recently
made available on sourceforge:

  http://numpy.sourceforge.net/


-------------------------------------------------------------
How can I determine if a string is contained in a bigger string?
How can I find the position of a substring in a string?
http://www.faqts.com/knowledge-base/view.phtml/aid/1355
-------------------------------------------------------------
Nathan Wallace
Fredrik Lundh

if string.find(mystring, "foo") >= 0:
    ...

or

string.index(mystring, "foo")
...

The latter raises a ValueError exception if the substring isn't found.

For more info, see the "string" chapter in the library reference:

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


-------------------------------------------------------------
I'm new to Python, where should I start?
Can you give me an overview of the Python Documentation?
Do I need books to learn Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1356
-------------------------------------------------------------
Nathan Wallace
Tom Funk

The handbook is part of the on-line documentation available at the
Python web site and with the Python installation -- and it's free.

You may not need to go to a bookstore if you peruse the following page:

  http://www.python.org/doc/

The tutorial is quite complete:

  http://www.python.org/doc/current/tut/tut.html

If you work through the tutorial, it should carry you pretty far along
in your quest.  I found it to be *quite* useful.

The Library Reference discusses the modules that ship with Python. 

  http://www.python.org/doc/current/lib/lib.html

The Language Reference is a bit more abstract, and *much* more dry.  
However, it does completely describe the core Python language
constructs, grammar and syntax.   It's often referred to as material for
"Language Lawyers."

  http://www.python.org/doc/current/ref/ref.html

I like the Module Index:

  http://www.python.org/doc/current/modindex.html

It allows you to jump straight to the module of your choice.

If you're using Win32 (as I do), then you may find the MS HTML Help 
version to be useful (it's my favorite).  If you use Win32, you might 
want to check out:

  http://www.orgmf.com.ar/condor/pytstuff.html

Best of all, these very complete works of non-fiction are FREE.... gotta 
love that!  

I own five Python books, but I still find myself referring back to the 
Python documentation regularly.


-------------------------------------------------------------
How can I catch an error in re.compile?
How can I test for a bad regular expression?
http://www.faqts.com/knowledge-base/view.phtml/aid/1357
-------------------------------------------------------------
Nathan Wallace
Fredrik Lundh

Why not just compile a bad expression and see what happens? ;-)

>>> re.compile("(")
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "C:\py152\lib\re.py", line 79, in compile
    code=pcre_compile(pattern, flags, groupindex)
pcre.error: ('missing )', 1)

(to catch the exception, use try/except re.error)


-------------------------------------------------------------
How can I use a Microsoft Access database from Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1359
-------------------------------------------------------------
Nathan Wallace
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


-------------------------------------------------------------
How can I choose an element from a list at random?
http://www.faqts.com/knowledge-base/view.phtml/aid/1361
-------------------------------------------------------------
Nathan Wallace
Bruce Wolk

import random
random.choice(list)


-------------------------------------------------------------
Is there a extended library of Python functions for X windows?
Can I track the X-Y co-ordinates of the mouse from Python even over
other application windows?
http://www.faqts.com/knowledge-base/view.phtml/aid/1362
-------------------------------------------------------------
Nathan Wallace
Gerrit Holl, Sjoerd Mullender

Sjoerd Mullender has done that.  Parnassus links to his homepage

    http://www.cwi.nl/ftp/sjoerd/index.html

for an extensive X library in Python.

An update to this stuff is long overdue, but I have so little time to
make that update...


-------------------------------------------------------------
Where can I get a complete version history of Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1363
-------------------------------------------------------------
Nathan Wallace
Michael Hudson

Misc/HISTORY in the source distribution has more than 200k of what you
ask for; Misc/NEWS has the changes since 1.5.1.


-------------------------------------------------------------
Where can I find a good simple example using threads in Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1364
-------------------------------------------------------------
Nathan Wallace
Jeff Blaine, Steve Holden

Ripped straight from Aahz Maruch's post the other day and simplified
as more of a 'visual learning tool' demo.  Added a few comments...
whatever...just posting in case someone finds this one more graspable
at a thread-beginner level like me.

#!/usr/local/bin/python

import time, threading, whrandom

class MyThread(threading.Thread):
    """ Each thread picks a 'random' integer between 0 and 19 and 
        reports in once per second for that many seconds.
    """

    def run(self):
        iterations = whrandom.randint(0, 19)
        for i in range(iterations):
            print "   ", self.getName(), "is reporting in"
            time.sleep(1)
        print self.getName(), "is DONE"


if __name__ == '__main__':
    threadList = []

    # Create 5 MyThread() threads
    for i in range(5) :
        thread = MyThread()
        threadList.append(thread)

    # Start all threads
    for thread in threadList:
        thread.start()

    # As long as we have more than just the 'main' thread running, print 
    # out a status message
    while threading.activeCount() > 1 :
        print str(threading.activeCount()), "threads running incl. main"
        time.sleep(1)

Please note, you should not expect this to run under Idle, which gave
somewhat incomprehensible results to a newbie like me, but it works fine
as a standalone.


-------------------------------------------------------------
Where can I get more information about books on Python?
What are some good Python books?
http://www.faqts.com/knowledge-base/view.phtml/aid/1368
-------------------------------------------------------------
Nathan Wallace
Fredrik Lundh

"Learning Python" and "The Quick Python Book" are probably your best
bets at the moment.  they're a bit different in style; you may wish to
check them out in your local bookstore to see which one you prefer.

You can more info via the page:

    http://www.python.org/psa/bookstore/


-------------------------------------------------------------
What does del do for an instance of a wrapped C++ class?
Does del call the destructor of a wrapped C++ class?
http://www.faqts.com/knowledge-base/view.phtml/aid/1369
-------------------------------------------------------------
Nathan Wallace
Remco Gerlich

For example, let's say 'my_object' is a instance of wrapped C++ class.

  >>del my_object

All it's supposed to do is remove the name from the current namespace.
_If_ nothing else is still referring to it, then it may be removed, and
the destructor would be called then. You can't assume that 'del' will
call your destructor.


-------------------------------------------------------------
Can I get the variable name of an object instance?
http://www.faqts.com/knowledge-base/view.phtml/aid/1370
-------------------------------------------------------------
Nathan Wallace
Fredrik Lundh

Sorry, you can't do that.

Names are just names, not identities.  Any object can have lots of
different names, or none at all.

an example:

    clown = Hello(1)
    bobo = clown
    # here, bobo and clown both point to
    # the same instance
    del clown
    # now, only bobo points to that instance
    mylist = [bobo]
    del bobo
    # and here, nobody points directly to the
    # instance.

If you want to get the name of the class for an object instance, see
here:

  http://www.faqts.com/knowledge-base/view.phtml/aid/1328/fid/242


-------------------------------------------------------------
How can I get the state of the other mouse buttons in the callback for a
button1 event?
How can I get the state of buttons and keys in an event instance?
http://www.faqts.com/knowledge-base/view.phtml/aid/1371
-------------------------------------------------------------
Nathan Wallace
Fredrik Lundh

The event instance has a "state" member which reflects the state of
modifier keys and mouse buttons.

iirc, the relevant bitmasks are:

    Button1Mask = 1<<8
    Button2Mask = 1<<9
    Button3Mask = 1<<10


-------------------------------------------------------------
How do I use python code in ASP tags?
http://www.faqts.com/knowledge-base/view.phtml/aid/1372
-------------------------------------------------------------
Nathan Wallace
Tom Funk

There are a couple of things you might want to check:

That the Win32 Python Extensions are properly installed.

Your Python version is 1.5.2.

<%@Language=Python%> as the first executable line in the ASP file.

Between the <% %> delimiters, leading spaces are important. For
instance:

<%
import sys
pyVersion = sys.version
%>

will work. Whereas

<%
  import sys

  pyVersion = sys.version
%>

will fail.  The interpreter doesn't like the leading spaces in front of 
import and pyVersion.

Here's a sample ASP file that should work as-is (it works for me).  Copy 
and paste it into an ASP file and execute it from your server.  It
should 
display the current Python version and a list of server environment 
variables.  

If this doesn't work, your Win32 Extensions installation may be hosed
up.

-----------[ copy after this line ]--------------
<%@Language=Python%>
<html>
<body>
<%
# NO leading spaces here
indent = " " * 5

def emitEnv():
  # leading spaces needed here...
  import os
  
  for key in os.environ.keys():
    Response.Write("<br>%s<b>%s</b>=%s\n" % 
                   (indent, key, os.environ[key]))

# again, NO leading spaces here
import sys
pyVersion = sys.version
%>
<h3>Current Python Version</h3>
<p><%=indent + pyVersion%></p>
<h3>Server Environment Variables</h3>
<%
# no leading spaces, yet again
emitEnv()
%>
<body>
<html>
-----------[ copy before this line ]--------------


-------------------------------------------------------------
How can I convert a floating point number to a string?
http://www.faqts.com/knowledge-base/view.phtml/aid/1373
-------------------------------------------------------------
Nathan Wallace
Gerrit Holl, Carel Fellinger

>>> str(1.5)
'1.5'

You can use the builtin 'str' function if you want to convert _anything_
to a string: not only integers, lists, and dictionairies, but also file
objects and class instances. Please read the documentation for more
information.

If more control over the layout is needed you might use the "%" trickery
like:

>>> '%5.2f' % 123.4567
123.45
>>> '%5.2e' % 123.4567
1.23e+02


-------------------------------------------------------------
How can I run my Python programs in Windows?
How can I setup Python file extensions on Windows?
http://www.faqts.com/knowledge-base/view.phtml/aid/1374
-------------------------------------------------------------
Nathan Wallace
Tom Funk, Fredrik Lundh, David C. Ullrich

If you're running under Win32, you could download and install the Win32 
Extensions:

  http://www.python.org/download/download_windows.html

The installer will add the necessary registry entries to allow you to
run a .py or .pyw file from a command line or from within Windows
Explorer.

Also, most IDE's (including IDLE, PythonWin, emacs, etc) have commands
that run your Python program and displays the output.

Otherwise, if you're using Windows with any non-Python aware editor,
fire up a command window (aka MS-DOS prompt) and run the script from
there.  e.g:

    c:\mydir> python myscript.py

If you want to add the file associations by hand it's not hard to make
Windows understand what you want to do.  Like you can make a file py.reg
that looks like this:

REGEDIT4

[HKEY_CLASSES_ROOT\.py]
@="DUPythonFile"

[HKEY_CLASSES_ROOT\DUPythonFile]
@="DUPythonFile"

[HKEY_CLASSES_ROOT\DUPythonFile\DefaultIcon]
@="D:\\Python\\Py.ico"

[HKEY_CLASSES_ROOT\DUPythonFile\shell]
@="Edit"

[HKEY_CLASSES_ROOT\DUPythonFile\shell\Edit]

[HKEY_CLASSES_ROOT\DUPythonFile\shell\Edit\command]
@="C:\\windows\\notepad.exe %1"

[HKEY_CLASSES_ROOT\DUPythonFile\shell\Run(DOS)]

[HKEY_CLASSES_ROOT\DUPythonFile\shell\Run(DOS)\command]
@="d:\\python\\py.bat %1"

[HKEY_CLASSES_ROOT\DUPythonFile\shell\Initialize Interpreter]

[HKEY_CLASSES_ROOT\DUPythonFile\shell\Initialize Interpreter\command]
@="d:\\python\\python.exe -i %1"

[HKEY_CLASSES_ROOT\DUPythonFile\shell\PyWin(Edit)]

[HKEY_CLASSES_ROOT\DUPythonFile\shell\PyWin(Edit)\command]
@="d:\\Python\\Pythonwin\\pythonwin.exe /edit %1"

[HKEY_CLASSES_ROOT\DUPythonFile\shell\PyWin(Run)]

[HKEY_CLASSES_ROOT\DUPythonFile\shell\PyWin(Run)\command]
@="d:\\Python\\Pythonwin\\pythonwin.exe /run %1"

The REGEDIT4 should be the first line of the file. If you execute that
file then *.py files will have associations just like on my machine here
- if you edit the path names, etc then you get what you want.

And you save the py.reg file, so when installing something changes the
associations you re-merge the py.reg file and they're back the way you
want. Very handy for fixing things when some new program thinks you want
it to take over every file extension it can think of.



More information about the Python-list mailing list