home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / doc / diveintopython / examples / kgp / toolbox.py < prev   
Encoding:
Python Source  |  2004-05-05  |  1.8 KB  |  59 lines

  1. """Miscellaneous utility functions
  2.  
  3. This program is part of "Dive Into Python", a free Python book for
  4. experienced programmers.  Visit http://diveintopython.org/ for the
  5. latest version.
  6. """
  7.  
  8. __author__ = "Mark Pilgrim (mark@diveintopython.org)"
  9. __version__ = "$Revision: 1.3 $"
  10. __date__ = "$Date: 2004/05/05 21:57:20 $"
  11. __copyright__ = "Copyright (c) 2001 Mark Pilgrim"
  12. __license__ = "Python"
  13.  
  14. def openAnything(source):
  15.     """URI, filename, or string --> stream
  16.  
  17.     This function lets you define parsers that take any input source
  18.     (URL, pathname to local or network file, or actual data as a string)
  19.     and deal with it in a uniform manner.  Returned object is guaranteed
  20.     to have all the basic stdio read methods (read, readline, readlines).
  21.     Just .close() the object when you're done with it.
  22.     
  23.     Examples:
  24.     >>> from xml.dom import minidom
  25.     >>> sock = openAnything("http://localhost/kant.xml")
  26.     >>> doc = minidom.parse(sock)
  27.     >>> sock.close()
  28.     >>> sock = openAnything("c:\\inetpub\\wwwroot\\kant.xml")
  29.     >>> doc = minidom.parse(sock)
  30.     >>> sock.close()
  31.     >>> sock = openAnything("<ref id='conjunction'><text>and</text><text>or</text></ref>")
  32.     >>> doc = minidom.parse(sock)
  33.     >>> sock.close()
  34.     """
  35.  
  36.     if hasattr(source, "read"):
  37.         return source
  38.     
  39.     if source == "-":
  40.         import sys
  41.         return sys.stdin
  42.  
  43.     # try to open with urllib (if source is http, ftp, or file URL)
  44.     import urllib
  45.     try:
  46.         return urllib.urlopen(source)
  47.     except (IOError, OSError):
  48.         pass
  49.     
  50.     # try to open with native open function (if source is pathname)
  51.     try:
  52.         return open(source)
  53.     except (IOError, OSError):
  54.         pass
  55.     
  56.     # treat source as string
  57.     import StringIO
  58.     return StringIO.StringIO(str(source))
  59.