[FAQTS] Python Knowledge Base Update -- June 4th, 2000

Fiona Czuczman fiona at sitegnome.com
Sun Jun 4 08:21:13 EDT 2000


Hi Guys,

Sorry I haven't sent the summaries over the last couple of days.  I'm 
sure you'll all be happy to hear I had a great weekend :)

Cheers,

Fiona Czuczman


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


-------------------------------------------------------------
How can I setup Python on MacOS X?
Has anyone compiled Python for MacOS X?
http://www.faqts.com/knowledge-base/view.phtml/aid/3464
-------------------------------------------------------------
Fiona Czuczman
Joseph Block, James Felix Black, cliff crawford

You can download it from softrak.stepwise.com

Just search for Python and MacOS X

It builds right out of the box.  The only trap is if you build on  an 
HFS+ as opposed to UFS volume; then, you have to be careful about case 
(HFS+ is case-insensitive but preserving.)

Specifically, if you use HFS+ and want it to "just work" when you run
make, then you need to rename the Python directory to something else (I
called it Python.d), then change Makefile.in, configure.in, and
Python/Makefile.in to use the new directory name.  Then run autoconf,
then configure, etc.


-------------------------------------------------------------
How can I free a port that has been used by a python server?
http://www.faqts.com/knowledge-base/view.phtml/aid/3465
-------------------------------------------------------------
Fiona Czuczman
Johannes Stezenbach

Problem:

######################################################################
class Server (SocketServer.ThreadingMixIn,
              BaseHTTPServer.HTTPServer):
    pass
    
if __name__ == '__main__':

    port = 1729 # Called from interactive session, debug mode.

    proxy =  Server (('127.0.0.1', port), Handler)
    proxy.serve_forever ()
######################################################################
    
The problem is, when I run this more than once in interactive mode, I
get the error:

socket.error: (98, 'Address already in use')

Is there some way to free up port 1729 when proxy gets destroyed?

Solution:

Normally you should close the socket properly before exiting. You could 
try to catch KeyboardInterrupt or whatever signal you use to break out 
of serve_forever(), but it's problematic with multithreaded servers.

Workaround:
-----
class Server (SocketServer.ThreadingMixIn,
              BaseHTTPServer.HTTPServer):
    def server_bind(self):
        import socket
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 
1)
        BaseHTTPServer.HTTPServer.server_bind(self)
-----

Note that this doesn't free up the port, instead it allows more than  
one process to bind to it, under certain circumstances (bind() still
fails if there's already a socket actively listening on that port).
See socket(7) (Linux) for details.


-------------------------------------------------------------
Is it possible for Python to call commands, e.g. "find, perl scripts, nmap, and others"?
http://www.faqts.com/knowledge-base/view.phtml/aid/3469
-------------------------------------------------------------
Fiona Czuczman
Sean Blakey

There are many ways to call other programs from python.

First, and simplest, is os.system.  This simply fires off a sub-shell to
run the specified program, than returnsthe exit code of that program.
For example:
>>>import os
>>>os.system('wget ftp://ftp.python.org/pub/python/src/py152.tgz')
will download the python source distrobution.

If you want the output of a command (or want to write to a command on
stdin) you can use os.popen, which returns a python filehandle.  For
example, to get a listing of allfiles ending in .mp3 on your system, you
can do:
>>import os
>>import string
>>fd = os.popen('locate *.mp3')
>>filenames = string.split(fd.read, '\n')
You can also use popen to write to a process:
>>>import os
>>>fd = os.popen('/usr/sbin/sendmail nobody at localhost', 'w')
>>>fd.write('''Subject: test

this is a test.
''')
>>>fd.close()
Since you are working on a linux box, you probably also have access to
the popen2 module.  This allows you to use coprocesses (giving you
access to both stdin and stdout of a process).

The popen2 module is documented at
http://www.python.org/doc/current/lib/module-popen2.html

Note that os.popen works unreliably on Windows boxes, and the popen2
module is unix-specific.


-------------------------------------------------------------
I am writing a C++ program with embedded python.  How can I redirect import commands to read the file from a different source, possibly not a true file at all but an entry in a zip file?
http://www.faqts.com/knowledge-base/view.phtml/aid/3467
-------------------------------------------------------------
Fiona Czuczman
Michael Hudson

I don't know if being embedded offers other ways of doing this, but in
Python code (which should work here), you'd probably want to use Greg 
Stein's imputil.py:

   http://www.lyra.org/greg/python/

If you want to override *all* import unconditionally, you can assign
to __builtin__.__import__, but that requires a certain amount of Python 
internals knowledge.


-------------------------------------------------------------
How can I combine two BMP images so that one overlays the other?
http://www.faqts.com/knowledge-base/view.phtml/aid/3466
-------------------------------------------------------------
Fiona Czuczman
Robert Roy, Anders Eriksson

I think PIL might be what you need.

http://www.pythonware.com/products/pil/index.htm

This page of the tutorial talks about pasting images and transparency

http://www.pythonware.com/library/pil/handbook/intro01.htm

You may want to look up the function 'composite'.


-------------------------------------------------------------
Where can I find some kind of helping material (tutorials etc) about how to use XML and Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/3468
-------------------------------------------------------------
Fiona Czuczman
Boudewijn Rempt, Harry George

Have a look here:

http://www.valdyas.org/python/index.html

dbobj - the repository is XML based
kura  - webserver that takes XML templates and spews out HTML, and an
        XML data import utility.
kxml  - a small PyKDE xml file browser (unfinished!)

A really simplistic reader/writer for Abiword.  Available at:
  http://www.seanet.com/~hgg9140/comp/index.html

--------------------

Install PyXML, then try this.  Read the xml.dom.core for element names
and the basic functions.  If you are not familiar with xml itself, see
the XML Bible.  Try this routine on some known-good .xml file.

#!/usr/bin/env python
#/* helloxml.py 

"""
Usage: helloxml.py [options] filename
E.g.,  helloxml.py myfile
Options
-h,--help        this message
-v,--version     version

Revisions:
2000-02-23  Harry George   initial version
"""

import sys,os,getopt,time,re,string,exceptions

modname="helloxml"
__version__="0.1"

def debug(ftn,txt):
        sys.stdout.write(modname+'.'+ftn+':'+txt+'\n')
        sys.stdout.flush()

def fatal(ftn,txt):
        sys.stdout.write(modname+'.'+ftn+':FATAL:'+txt+'\n')
        sys.stdout.flush()
        sys.exit(1)

def usage():
        print __doc__

#====================================
from xml.dom import core, utils

def main():
        ftn = "main"
        pargs=[]    #positional args, default is empty
        opts,pargs=getopt.getopt(sys.argv[1:],'hv',['help','version'])
        for opt in opts:
                if opt[0]=='-h' or opt[0]=='--help':
                        usage()
                        sys.exit(0)
                elif opt[0]=='-v' or opt[0]=='--version':
                        print modname+": version="+__version__
                        sys.exit(0)

        #---get the DOM "doc"---
        if len(pargs)==0:
                        usage()
                        sys.exit(0)             
        filename = pargs[0]
        doc = utils.FileReader( filename ).document

        #---dump it out---
        doc.dump();

        #---convert DOM tree back to XML, and dump that
        xml = doc.toxml()
        print xml

        #---dump the doc manually---
        root=doc.get_documentElement()  
        mydump(root)

def mydump(node):
        ftn = "mydump"
        debug(ftn,"name=" +node.get_nodeName())
        #---dump attributes---
        attrs=node.get_attributes()
        keys=attrs.keys()
        for attr in keys:
                debug(ftn,"attr="+attr+" 
value="+attrs[attr].get_nodeValue())
        #---dump children---
        children=node.get_childNodes()
        for child in children:
        #--report only elements
                if child.get_nodeType()==core.ELEMENT: 
                        mydump(child)
                         
if __name__ == '__main__': main()







More information about the Python-list mailing list