XML technologies / XML / Python & XML / The Simple API for XML / Searching file information

(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)

This section builds a file-indexing script generating an XML document representing all or part of your file system. XML file indexes are a powerful way to manage information or perform extensive operations on particular groups of files. Python makes an XML-producing indexer easy to create. The program index.py in example index.py starts in a directory of your choice and creates an element for every file and directory below it. Once the index exists, we will search it with SAX to filter the file list by whatever criteria interest us.

Building the index generator

The routine examines each file in the starting directory, then calls itself recursively for each subdirectory. Recursion can index an entire file system. On Unix, the program does considerable work, checking each file’s content using a popen call to the file command. (This could be more efficient if find were called less often to process several files at once, but that is outside this book’s scope.) A key method of this class is indexDirectoryFiles:

def indexDirectoryFiles(self, dir):     
     """Indexiert ein Verzeichnis und erzeugt eine XML-Ausgabedatei."""
     # Bereite XML-Ausgabedatei vor
     self.__fd = open(self.outputFile, "w")
     self.__fd.write('<?xml version="1.0" encoding="' + XML_ENC + '"?>\n')
     self.__fd.write("<IndexedFiles>\n")

     # Erledige das eigentliche Indexieren
     self.__indexDir(dir)

     # Beende und schließe XML-Datei
     self.__fd.write("</IndexedFiles>\n")
     self.__fd.close()

An XML file is created with the name specified in outputFile, and an XML declaration and root element are added. The method index-DirectoryFiles calls the internal method __indexDir, which does the actual work. It recursively descends the file hierarchy while indexing files.

def __indexDir(self, dir):
    """Rekursive Funktion für das eigentliche Indexieren."""    
    # Erzeuge ein indexFile für jede normale Datei, und
    # rufe die Funktion für jedes Verzeichnis erneut auf
    files = listdir(dir)
    for file in files:
      fullname = os.path.join(dir, file)
      st_values = stat(fullname)
        
      # Prüfe, ob es ein Verzeichnis ist
      if S_ISDIR(st_values[0]):
        print file
        # Erzeuge directory-Element
        self.__fd.write("<Directory ")
        self.__fd.write(' name="' + escape(fullname) + '">\n')
        self.__indexDir(fullname)
        self.__fd.write("</Directory>\n")
        
      else:
        # Erzeuge Eintrag für normale Datei
        print dir + file
        lf = IndexFile(fullname, st_values)
        self.__fd.write(lf.getXML())

The real work distinguishes directories from ordinary files, generating corresponding XML and writing it to the output file. Once all calls to __indexDir have finished, the XML file is closed.

The program is now almost finished. A helper function named escape is imported from the module xml.sax.saxutils to perform entity substitution on common characters in XML character data, ensuring they are not interpreted as markup in the resulting XML.

Building the IndexFile class

The IndexFile class represents file information in XML, mainly derived from the os.stat system call. Its method __init__ copies information from the call to stat into instance variables, as shown here:

def __init__(self, filename, st_vals):    
    """Extrahiere Attribute des angegebenen stat-Objekts."""
    self.filename = filename
    self.uid = st_vals[4]
    self.gid = st_vals[5]
    self.size = st_vals[6]
    self.accessed = ctime(st_vals[7])
    self.modified = ctime(st_vals[8])
    self.created = ctime(st_vals[9])


    # Prüfen der Dateinamenserweiterung
    self.extension = os.path.splitext(filename)[1]

This method extracts important file information from the tuple st_vals containing information returned by the stat call. The method _ _init _ _ also attempts to identify an extension by testing for the character “ . ”. On Unix, the script tries to use the function os.popen to invoke the file command, which returns a human-readable description of text and binary file contents. Generating this can take much longer, but the resulting XML is valuable and need not be regenerated every time it is needed:

# Prüfe Inhalt mit file-Befehl unter Linux
if os.name == "posix":
  # Öffne einen Prozeß zur Prüfung des Dateiinhalts
  fd = popen("file \"" + filename + "\"")
  self.contents = fd.readline().rstrip( )
  fd.close( )
else:
  # Keine Inhaltsinformation
  self.contents = self.extension

Outside Unix, the file command is unavailable, so content information comes from the extension. For a Word file, for example, the XML is <contents>.doc</contents>. On Unix, however, calling popen returns a file object. Command output is read using its readline method, trimmed and used as the content description. The class has one method, getXML, returning file information as a single XML element in string form:

def getXML(self):         
    """Gibt XML-Version aller Dateneinträge zurück."""
    return ("<file name=\"" + escape(self.filename) + "\">" +
         "\n\t<userID>" + str(self.uid) + "</userID>" +
         "\n\t<groupID>" + str(self.gid) + "</groupID>" +
         "\n\t<size>" + str(self.size) + "</size>" +
         "\n\t<lastAccessed>" + self.accessed +
         "</lastAccessed>" +
         "\n\t<lastModified>" + self.modified +
         "</lastModified>" +
         "\n\t<created>" + self.created + "</created>" +
         "\n\t<extension>" + self.extension +
         "</extension>" +
         "\n\t<contents>" + escape(self.contents) +
         "</contents>" +
         "\n</file>")

The code above assembles XML from strings. Another approach uses a DOMImplementation object to create individual elements and insert them in the document structure, as explained in Python and distributed systems design.

These two classes build a long XML document containing files and metadata for any part of your file system. The complete listing of index.py appears in the following example.

 

Example: index.py

#!/usr/bin/env python
"""
index.py
Benutzung: python index.py <starting-dir> <output-file>
"""
import os
import sys

from os import stat
from os import listdir
from os import popen
from stat import S_ISDIR
from time import ctime

from xml.sax.saxutils import escape

XML_ENC = "ISO-8859-1"

"""""""""""""""""""""""""""""""""""""""""""""""""""
Klasse: Index(startingDir, outputFile)
"""""""""""""""""""""""""""""""""""""""""""""""""""
class Index:      
      """
      Diese Klasse indexiert Dateien und erstellt ein daraus resultierendes XML-Dokument.
      """
      def __init__(self, startingDir, outputFile):
      """init: setzt Start-Verzeichnis und Ausgabedatei"""
      self.outputFile = outputFile
      self.startingDir = startingDir
      def indexDirectoryFiles(self, dir):
      """Indexiert eine Verzeichnisstruktur und erzeugt eine XML-Ausgabedatei."""
      # Bereite XML-Ausgabedatei vor
      self.__fd = open(self.outputFile, "w")
      self.__fd.write('<?xml version="1.0" encoding="' +
      XML_ENC + '"?>\n')
      self.__fd.write("<IndexedFiles>\n")
      # Führe Indexierung durch
      self.__indexDir(dir)
      # Schließe XML-Datei
      self.__fd.write("</IndexedFiles>\n")
      self.__fd.close( )
      def __indexDir(self, dir):
      """Rekursive Funktion für das eigentliche Indexieren."""
      # Erzeuge ein indexFile für jede normale Datei, und
      # rufe die Funktion erneut bei jedem Verzeichnis auf
      files = listdir(dir)
      for file in files:
      fullname = os.path.join(dir, file)
      st_values = stat(fullname)
      # Prüfe, ob es ein Verzeichnis ist
      if S_ISDIR(st_values[0]):
      print file
      # Erzeuge Verzeichniselement
      self.__fd.write("<Directory ")
      self.__fd.write(' name="' + escape(fullname) + '">\n')
      self.__indexDir(fullname)
      self.__fd.write("</Directory>\n")
      else:
      # Erzeuge Eintrag für normale Datei
      print dir + file
      lf = IndexFile(fullname, st_values)
      self.__fd.write(lf.getXML( ))

"""""""""""""""""""""""""""""""""""""""""""""""""""
Klasse: IndexFile(filename, stat-tuple)
"""""""""""""""""""""""""""""""""""""""""""""""""""
class IndexFile:
"""
      Einfaches Objekt zur Darstellung einer Datei mit XML
      """
      def __init__(self, filename, st_vals):
      """Extrahiere Attribute vom angegebenen stat-Objekt."""
      self.filename = filename
     self.uid = st_vals[4]
      elf.gid = st_vals[5]
      size = st_vals[6]
      v.accessed = ctime(st_vals[7])
      self.modified = ctime(st_vals[8])
      self.created = ctime(st_vals[9])
      # Versuche es mit einer Dateinamenserweiterung
      self.extension = os.path.splitext(filename)[1]
      # Prüfe Inhalt mit file-Befehl unter Linux
      if os.name == "posix":
      # Öffne einen Prozeß für die Prüfung des Dateiinhalts
      fd = popen("file \"" + filename + "\"")
      self.contents = fd.readline().rstrip( )
      fd.close( )
      else:
      # Keine Informationen über den Inhalt
      self.contents = self.extension
      def getXML(self):
      """Gibt XML-Version aller Dateneinträge zurück."""
      return ("<file name=\"" + escape(self.filename) + "\">" +
      "\n<userID>" + str(self.uid) + "</userID>" +
      "\n<groupID>" + str(self.gid) + "</groupID>" +
      "\n<lastAccessed>" + self.accessed +
      "</lastAccessed>" +
      "\n<lastModified>" + self.modified +
      "</lastModified>" +
      "\n\t<created>" + self.created + "</created>" +
      "\n\t<extension>" + self.extension +
      "</extension>" +
      "\n\t<contents>" + escape(self.contents) +
      "</contents>" +
      "\n</file>")

"""""""""""""""""""""""""""""""""""""""""""""""""""
Hauptprogramm
"""""""""""""""""""""""""""""""""""""""""""""""""""
if __name__ == "__main__":
index = Index(sys.argv[1], sys.argv[2])
print "Start-Verzeichnis:", index.startingDir
print "Ausgabedatei:", index.outputFile
index.indexDirectoryFiles(index.startingDir)

Running index.py

To run index.py from the command line, supply a starting directory and an output XML filename:

 $> python index.py /usr/bin/ usrbin.xml 

The script prints directory names like the find command; when it finishes, however, the file usrbin.xml contains something resembling this:

<?xml version="1.0" encoding=" ISO-8859-1"?>
<IndexedFiles>
  <Directory name="/usr/bin/X11">
    <file name="/usr/bin/X11/Magick-config">
      <userID>0</userID>
      <groupID>0</groupID>
      <size>1786</size>
      <lastAccessed>Fri Jan 19 22:29:34 2001</lastAccessed>
      <lastModified>Mon Aug 30 20:49:06 1999</lastModified>
      <created>Mon Sep 11 17:22:01 2000</created>
      <extension>None</extension>
      <contents>/usr/bin/X11/Magick-config: Bourne shell script text</contents>
    </file>
    <file name="/usr/bin/X11/animate">
      <userID>0</userID>
      <groupID>0</groupID>
      <size>16720</size>
      <lastAccessed>Fri Jan 19 22:29:34 2001</lastAccessed>
      <lastModified>Mon Aug 30 20:49:09 1999</lastModified>
      <created>Mon Sep 11 17:22:01 2000</created>
      <extension>None</extension>
      <contents>/usr/bin/X11/animate: ELF 32-bit LSB executable, Intel 80386,version 1, dynamically linked (uses shared libs), stripped</contents>
    </file>

XML file size depends on the starting directory. By default the program follows symbolic links—Unix directories or files standing for other directories or files—which risks infinite recursion. Be careful! A sensible choice is probably your home directory or the directory of downloaded open-source software.

Searching the index

With the files abstracted as XML, write a SAX event handler to search the list. SAX is a good choice because the document may easily reach several megabytes. Interpreting it as it is read uses the fewest resources.

The script saxfinder.py expects one argument, the search text, parses the XML file and uses SAX handler interfaces to check for files of interest.

It expects XML generated earlier by index.py .

If your XML file’s contents element contains the character data supplied on the command line, the file matches and a message is printed. On Windows, your contents tags contain only extensions, limiting the search to extensions unless you modify the code to examine more than the contents element.

Implement the metadata search with three SAX methods. First, implement startElement to remember the current file element’s name and when character data after a contents tag begins:

def startElement(self, name, attrs):
  if name == "file":
    self.filename = attrs.get('name', "")

elif name == "contents":
  self.getCont = 1

Entering a contents element sets a flag (self.getCont) telling the characters method when to collect character data and store it in another instance variable:

def characters(self, ch):
   if self.getCont:
      self.contents += ch

On an endElement event, the script checks any collected content against the original command-line parameter. If it matches, the filename is printed; otherwise SAX continues with the next XML file entry:

def endElement(self, name):
   if name == "contents":
      self.getCont = 0
      if self.contents.find(self.contentType) > -1:
         print self.filename, "hat", self.contentType, "als Inhalt."
      self.contents = ""

The self.getCont flag is also disabled after leaving a contents element, so the characters method stops collecting data.

SAX lets you process an XML index representing an entire file system, easily taking 20 megabytes on disk. Parsing such a huge document with DOM can be difficult and unbearably slow.

The next example shows the complete listing of saxfinder.py.

Example: saxfinder.py

"""
saxfinder.py - sucht in der Ausgabe von index.py
"""
import sys

from xml.sax import make_parser      
from xml.sax import ContentHandler

class FileHandler(ContentHandler):
  def __init__(self, contentType):
      self.getCont = 0
      self.contents = ""
      self.filename = ""
      self.contentType = contentType

def startElement(self, name, attrs):
  if name == "file":
      self.filename = attrs.get('name', "")

      elif name == "contents":
      self.getCont = 1

def characters(self, ch):
  if self.getCont:
      self.contents += ch

def endElement(self, name):
  if name == "contents":
      self.getCont = 0
      if self.contents.find(self.contentType) > -1:
        print self.filename, "hat", self.contentType, "als Inhalt."
      self.contents = ""

# Hauptprogramm

fh = FileHandler(sys.argv[1])
parser = make_parser( )
parser.setContentHandler(fh)
parser.parse(sys.stdin)

You can run saxfinder.py from the Unix or Windows command line. Supply a search string as the first parameter and redirect or pipe an XML document generated by index.py to standard input:

 $> python saxfinder.py "C program" < nard.xml 

The result should resemble this:

/home/shm00/nard/xd/server.cpp hat C program als Inhalt.
/home/shm00/nard/xd/shmoo.cpp hat C program als Inhalt.
/home/shm00/nard/gl-misc/array.cpp hat C program als Inhalt.
/home/shm00/nard/gl-misc/vertex.cpp hat C program als Inhalt.
/home/shm00/nard/gl-misc/mecogl.cpp hat C program als Inhalt.
/home/shm00/nard/gl-misc/drewgl/smugl.cpp hat C program als Inhalt.
/home/shm00/nard/gl-misc/drewgl/pal.cpp hat C program als Inhalt.
/home/shm00/nard/gl-misc/drewgl/pal.h hat C program als Inhalt.
/home/shm00/nard/gl-misc/drewgl/gl.cpp hat C program als Inhalt.

  

 

 

 

back to top