Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
pydoc Namespace Reference

Data Structures

class  ErrorDuringImport
 
class  Doc
 
class  HTMLRepr
 
class  HTMLDoc
 
class  TextRepr
 
class  TextDoc
 
class  Helper
 
class  Scanner
 
class  ModuleScanner
 

Functions

def pathdirs
 
def getdoc
 
def splitdoc
 
def classname
 
def isdata
 
def replace
 
def cram
 
def stripid
 
def allmethods
 
def ispackage
 
def synopsis
 
def importfile
 
def safeimport
 
def pager
 
def getpager
 
def plain
 
def pipepager
 
def tempfilepager
 
def ttypager
 
def plainpager
 
def describe
 
def locate
 
def doc
 
def writedoc
 
def writedocs
 
def apropos
 
def serve
 
def gui
 
def ispath
 
def cli
 

Variables

string __author__ = "Ka-Ping Yee <ping@lfw.org>"
 
string __date__ = "26 February 2001"
 
string __version__ = "$Revision: 5816 $"
 
string __credits__
 
tuple text = TextDoc()
 
tuple html = HTMLDoc()
 
tuple help = Helper(sys.stdin, sys.stdout)
 
 encodingheader
 
 typeheader
 
 address
 
 url
 
 callback
 
 quit
 
 window
 
 server
 
 scanner
 
 server_frm
 
 title_lbl
 
 open_btn
 
 quit_btn
 
 search_frm
 
 search_lbl
 
 search_ent
 
 stop_btn
 
 result_lst
 
 result_scr
 
 result_frm
 
 goto_btn
 
 hide_btn
 
 minwidth
 
 minheight
 
 bigminheight
 
 bigheight
 
 expanded
 
 bigwidth
 

Function Documentation

def pydoc.allmethods (   cl)

Definition at line 117 of file pydoc.py.

References inspect.getmembers().

118 def allmethods(cl):
119  methods = {}
120  for key, value in inspect.getmembers(cl, _is_some_method):
121  methods[key] = 1
122  for base in cl.__bases__:
123  methods.update(allmethods(base)) # all your base are belong to us
124  for key in methods.keys():
125  methods[key] = getattr(cl, key)
126  return methods
def pydoc.apropos (   key)
Print all the one-line module summaries that contain a substring.

Definition at line 1745 of file pydoc.py.

References callback, warnings.filterwarnings(), and imaplib.run().

1746 def apropos(key):
1747  """Print all the one-line module summaries that contain a substring."""
1748  def callback(path, modname, desc):
1749  if modname[-9:] == '.__init__':
1750  modname = modname[:-9] + ' (package)'
1751  print modname, desc and '- ' + desc
1752  try: import warnings
1753  except ImportError: pass
1754  else: warnings.filterwarnings('ignore') # ignore problems during import
1755  ModuleScanner().run(callback, key)
1756 
1757 # --------------------------------------------------- web browser interface
def pydoc.classname (   object,
  modname 
)
Get a class name and qualify it with a module name if necessary.

Definition at line 78 of file pydoc.py.

78 
79 def classname(object, modname):
80  """Get a class name and qualify it with a module name if necessary."""
81  name = object.__name__
82  if object.__module__ != modname:
83  name = object.__module__ + '.' + name
84  return name
def pydoc.cli ( )
Command-line interface (looks at sys.argv to decide what to do).

Definition at line 2030 of file pydoc.py.

References apropos(), doc(), getopt.getopt(), gui(), importfile(), ispath(), serve(), writedoc(), and writedocs().

2031 def cli():
2032  """Command-line interface (looks at sys.argv to decide what to do)."""
2033  import getopt
2034  class BadUsage: pass
2035 
2036  # Scripts don't get the current directory in their path by default.
2037  scriptdir = os.path.dirname(sys.argv[0])
2038  if scriptdir in sys.path:
2039  sys.path.remove(scriptdir)
2040  sys.path.insert(0, '.')
2041 
2042  try:
2043  opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
2044  writing = 0
2045 
2046  for opt, val in opts:
2047  if opt == '-g':
2048  gui()
2049  return
2050  if opt == '-k':
2051  apropos(val)
2052  return
2053  if opt == '-p':
2054  try:
2055  port = int(val)
2056  except ValueError:
2057  raise BadUsage
2058  def ready(server):
2059  print 'pydoc server ready at %s' % server.url
2060  def stopped():
2061  print 'pydoc server stopped'
2062  serve(port, ready, stopped)
2063  return
2064  if opt == '-w':
2065  writing = 1
2066 
2067  if not args: raise BadUsage
2068  for arg in args:
2069  try:
2070  if ispath(arg) and os.path.isfile(arg):
2071  arg = importfile(arg)
2072  if writing:
2073  if ispath(arg) and os.path.isdir(arg):
2074  writedocs(arg)
2075  else:
2076  writedoc(arg)
2077  else:
2078  doc(arg)
2079  except ErrorDuringImport, value:
2080  print value
2081 
2082  except (getopt.error, BadUsage):
2083  cmd = sys.argv[0]
2084  print """pydoc - the Python documentation tool
2085 
2086 %s <name> ...
2087  Show text documentation on something. <name> may be the name of a
2088  function, module, or package, or a dotted reference to a class or
2089  function within a module or module in a package. If <name> contains
2090  a '%s', it is used as the path to a Python source file to document.
2091 
2092 %s -k <keyword>
2093  Search for a keyword in the synopsis lines of all available modules.
2094 
2095 %s -p <port>
2096  Start an HTTP server on the given port on the local machine.
2097 
2098 %s -g
2099  Pop up a graphical interface for finding and serving documentation.
2100 
2101 %s -w <name> ...
2102  Write out the HTML documentation for a module to a file in the current
2103  directory. If <name> contains a '%s', it is treated as a filename; if
2104  it names a directory, documentation is written for all the contents.
2105 """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
def pydoc.cram (   text,
  maxlen 
)
Omit part of a string if needed to make it fit in a maximum length.

Definition at line 98 of file pydoc.py.

References sre_parse.max.

98 
99 def cram(text, maxlen):
100  """Omit part of a string if needed to make it fit in a maximum length."""
101  if len(text) > maxlen:
102  pre = max(0, (maxlen-3)/2)
103  post = max(0, maxlen-3-pre)
104  return text[:pre] + '...' + text[len(text)-post:]
105  return text
def pydoc.describe (   thing)
Produce a short description of the given thing.

Definition at line 1275 of file pydoc.py.

References inspect.isbuiltin(), inspect.isclass(), inspect.isfunction(), inspect.ismethod(), and inspect.ismodule().

1276 def describe(thing):
1277  """Produce a short description of the given thing."""
1278  if inspect.ismodule(thing):
1279  if thing.__name__ in sys.builtin_module_names:
1280  return 'built-in module ' + thing.__name__
1281  if hasattr(thing, '__path__'):
1282  return 'package ' + thing.__name__
1283  else:
1284  return 'module ' + thing.__name__
1285  if inspect.isbuiltin(thing):
1286  return 'built-in function ' + thing.__name__
1287  if inspect.isclass(thing):
1288  return 'class ' + thing.__name__
1289  if inspect.isfunction(thing):
1290  return 'function ' + thing.__name__
1291  if inspect.ismethod(thing):
1292  return 'method ' + thing.__name__
1293  if type(thing) is types.InstanceType:
1294  return 'instance of ' + thing.__class__.__name__
1295  return type(thing).__name__
def pydoc.doc (   thing,
  title = 'Python Library Documentation: %s',
  forceload = 0 
)
Display text documentation, given an object or a path to an object.

Definition at line 1320 of file pydoc.py.

References describe(), inspect.getmodule(), dospath.join(), locate(), pager(), and dospath.split().

1321 def doc(thing, title='Python Library Documentation: %s', forceload=0):
1322  """Display text documentation, given an object or a path to an object."""
1323  suffix, name = '', None
1324  if type(thing) is type(''):
1325  try:
1326  object = locate(thing, forceload)
1327  except ErrorDuringImport, value:
1328  print value
1329  return
1330  if not object:
1331  print 'no Python documentation found for %s' % repr(thing)
1332  return
1333  parts = split(thing, '.')
1334  if len(parts) > 1: suffix = ' in ' + join(parts[:-1], '.')
1335  name = parts[-1]
1336  thing = object
1337 
1338  desc = describe(thing)
1339  module = inspect.getmodule(thing)
1340  if not suffix and module and module is not thing:
1341  suffix = ' in module ' + module.__name__
1342  pager(title % (desc + suffix) + '\n\n' + text.document(thing, name))
def pydoc.getdoc (   object)
Get the doc string or comments for an object.

Definition at line 64 of file pydoc.py.

References inspect.getcomments(), inspect.getdoc(), and string.rstrip().

64 
65 def getdoc(object):
66  """Get the doc string or comments for an object."""
67  result = inspect.getdoc(object) or inspect.getcomments(object)
68  return result and re.sub('^ *\n', '', rstrip(result)) or ''
def pydoc.getpager ( )
Decide what method to use for paging through text.

Definition at line 1177 of file pydoc.py.

References aifc.close(), tempfile.mktemp(), aifc.open(), pipepager(), plain(), and tempfilepager().

1178 def getpager():
1179  """Decide what method to use for paging through text."""
1180  if type(sys.stdout) is not types.FileType:
1181  return plainpager
1182  if not sys.stdin.isatty() or not sys.stdout.isatty():
1183  return plainpager
1184  if os.environ.get('TERM') in ['dumb', 'emacs']:
1185  return plainpager
1186  if os.environ.has_key('PAGER'):
1187  if sys.platform == 'win32': # pipes completely broken in Windows
1188  return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
1189  elif os.environ.get('TERM') in ['dumb', 'emacs']:
1190  return lambda text: pipepager(plain(text), os.environ['PAGER'])
1191  else:
1192  return lambda text: pipepager(text, os.environ['PAGER'])
1193  if sys.platform == 'win32':
1194  return lambda text: tempfilepager(plain(text), 'more <')
1195  if hasattr(os, 'system') and os.system('less 2>/dev/null') == 0:
1196  return lambda text: pipepager(text, 'less')
1197 
1198  import tempfile
1199  filename = tempfile.mktemp()
1200  open(filename, 'w').close()
1201  try:
1202  if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
1203  return lambda text: pipepager(text, 'more')
1204  else:
1205  return ttypager
1206  finally:
1207  os.unlink(filename)
def pydoc.gui ( )
Graphical interface (starts web server and pops up a control window).

Definition at line 1849 of file pydoc.py.

References audiodev.__init__().

1850 def gui():
1851  """Graphical interface (starts web server and pops up a control window)."""
1852  class GUI:
1853  def __init__(self, window, port=7464):
1854  self.window = window
1855  self.server = None
1856  self.scanner = None
1857 
1858  import Tkinter
1859  self.server_frm = Tkinter.Frame(window)
1860  self.title_lbl = Tkinter.Label(self.server_frm,
1861  text='Starting server...\n ')
1862  self.open_btn = Tkinter.Button(self.server_frm,
1863  text='open browser', command=self.open, state='disabled')
1864  self.quit_btn = Tkinter.Button(self.server_frm,
1865  text='quit serving', command=self.quit, state='disabled')
1867  self.search_frm = Tkinter.Frame(window)
1868  self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
1869  self.search_ent = Tkinter.Entry(self.search_frm)
1870  self.search_ent.bind('<Return>', self.search)
1871  self.stop_btn = Tkinter.Button(self.search_frm,
1872  text='stop', pady=0, command=self.stop, state='disabled')
1873  if sys.platform == 'win32':
1874  # Trying to hide and show this button crashes under Windows.
1875  self.stop_btn.pack(side='right')
1876 
1877  self.window.title('pydoc')
1878  self.window.protocol('WM_DELETE_WINDOW', self.quit)
1879  self.title_lbl.pack(side='top', fill='x')
1880  self.open_btn.pack(side='left', fill='x', expand=1)
1881  self.quit_btn.pack(side='right', fill='x', expand=1)
1882  self.server_frm.pack(side='top', fill='x')
1883 
1884  self.search_lbl.pack(side='left')
1885  self.search_ent.pack(side='right', fill='x', expand=1)
1886  self.search_frm.pack(side='top', fill='x')
1887  self.search_ent.focus_set()
1888 
1889  font = ('helvetica', sys.platform == 'win32' and 8 or 10)
1890  self.result_lst = Tkinter.Listbox(window, font=font, height=6)
1891  self.result_lst.bind('<Button-1>', self.select)
1892  self.result_lst.bind('<Double-Button-1>', self.goto)
1893  self.result_scr = Tkinter.Scrollbar(window,
1894  orient='vertical', command=self.result_lst.yview)
1895  self.result_lst.config(yscrollcommand=self.result_scr.set)
1897  self.result_frm = Tkinter.Frame(window)
1898  self.goto_btn = Tkinter.Button(self.result_frm,
1899  text='go to selected', command=self.goto)
1900  self.hide_btn = Tkinter.Button(self.result_frm,
1901  text='hide results', command=self.hide)
1902  self.goto_btn.pack(side='left', fill='x', expand=1)
1903  self.hide_btn.pack(side='right', fill='x', expand=1)
1904 
1905  self.window.update()
1906  self.minwidth = self.window.winfo_width()
1907  self.minheight = self.window.winfo_height()
1908  self.bigminheight = (self.server_frm.winfo_reqheight() +
1909  self.search_frm.winfo_reqheight() +
1910  self.result_lst.winfo_reqheight() +
1911  self.result_frm.winfo_reqheight())
1912  self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
1913  self.expanded = 0
1914  self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
1915  self.window.wm_minsize(self.minwidth, self.minheight)
1916 
1917  import threading
1919  target=serve, args=(port, self.ready, self.quit)).start()
1920 
1921  def ready(self, server):
1922  self.server = server
1923  self.title_lbl.config(
1924  text='Python documentation server at\n' + server.url)
1925  self.open_btn.config(state='normal')
1926  self.quit_btn.config(state='normal')
1927 
1928  def open(self, event=None, url=None):
1929  url = url or self.server.url
1930  try:
1931  import webbrowser
1932  webbrowser.open(url)
1933  except ImportError: # pre-webbrowser.py compatibility
1934  if sys.platform == 'win32':
1935  os.system('start "%s"' % url)
1936  elif sys.platform == 'mac':
1937  try: import ic
1938  except ImportError: pass
1939  else: ic.launchurl(url)
1940  else:
1941  rc = os.system('netscape -remote "openURL(%s)" &' % url)
1942  if rc: os.system('netscape "%s" &' % url)
1943 
1944  def quit(self, event=None):
1945  if self.server:
1946  self.server.quit = 1
1947  self.window.quit()
1948 
1949  def search(self, event=None):
1950  key = self.search_ent.get()
1951  self.stop_btn.pack(side='right')
1952  self.stop_btn.config(state='normal')
1953  self.search_lbl.config(text='Searching for "%s"...' % key)
1954  self.search_ent.forget()
1955  self.search_lbl.pack(side='left')
1956  self.result_lst.delete(0, 'end')
1957  self.goto_btn.config(state='disabled')
1958  self.expand()
1959 
1960  import threading
1961  if self.scanner:
1962  self.scanner.quit = 1
1963  self.scanner = ModuleScanner()
1964  threading.Thread(target=self.scanner.run,
1965  args=(self.update, key, self.done)).start()
1966 
1967  def update(self, path, modname, desc):
1968  if modname[-9:] == '.__init__':
1969  modname = modname[:-9] + ' (package)'
1970  self.result_lst.insert('end',
1971  modname + ' - ' + (desc or '(no description)'))
1972 
1973  def stop(self, event=None):
1974  if self.scanner:
1975  self.scanner.quit = 1
1976  self.scanner = None
1977 
1978  def done(self):
1979  self.scanner = None
1980  self.search_lbl.config(text='Search for')
1981  self.search_lbl.pack(side='left')
1982  self.search_ent.pack(side='right', fill='x', expand=1)
1983  if sys.platform != 'win32': self.stop_btn.forget()
1984  self.stop_btn.config(state='disabled')
1985 
1986  def select(self, event=None):
1987  self.goto_btn.config(state='normal')
1988 
1989  def goto(self, event=None):
1990  selection = self.result_lst.curselection()
1991  if selection:
1992  modname = split(self.result_lst.get(selection[0]))[0]
1993  self.open(url=self.server.url + modname + '.html')
1994 
1995  def collapse(self):
1996  if not self.expanded: return
1997  self.result_frm.forget()
1998  self.result_scr.forget()
1999  self.result_lst.forget()
2000  self.bigwidth = self.window.winfo_width()
2001  self.bigheight = self.window.winfo_height()
2002  self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
2003  self.window.wm_minsize(self.minwidth, self.minheight)
2004  self.expanded = 0
2005 
2006  def expand(self):
2007  if self.expanded: return
2008  self.result_frm.pack(side='bottom', fill='x')
2009  self.result_scr.pack(side='right', fill='y')
2010  self.result_lst.pack(side='top', fill='both', expand=1)
2011  self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
2012  self.window.wm_minsize(self.minwidth, self.bigminheight)
2013  self.expanded = 1
2014 
2015  def hide(self, event=None):
2016  self.stop()
2017  self.collapse()
2018 
2019  import Tkinter
2020  try:
2021  gui = GUI(Tkinter.Tk())
2022  Tkinter.mainloop()
2023  except KeyboardInterrupt:
2024  pass
2025 
2026 # -------------------------------------------------- command-line interface
def pydoc.importfile (   path)
Import a Python source file or compiled file given its path.

Definition at line 198 of file pydoc.py.

References aifc.open().

199 def importfile(path):
200  """Import a Python source file or compiled file given its path."""
201  magic = imp.get_magic()
202  file = open(path, 'r')
203  if file.read(len(magic)) == magic:
204  kind = imp.PY_COMPILED
205  else:
206  kind = imp.PY_SOURCE
207  file.close()
208  filename = os.path.basename(path)
209  name, ext = os.path.splitext(filename)
210  file = open(path, 'r')
211  try:
212  module = imp.load_module(name, file, path, (ext, 'r', kind))
213  except:
214  raise ErrorDuringImport(path, sys.exc_info())
215  file.close()
216  return module
def pydoc.isdata (   object)
Check if an object is of a type that probably means it's data.

Definition at line 85 of file pydoc.py.

References inspect.isclass(), inspect.iscode(), inspect.isframe(), inspect.ismodule(), inspect.isroutine(), and inspect.istraceback().

85 
86 def isdata(object):
87  """Check if an object is of a type that probably means it's data."""
88  return not (inspect.ismodule(object) or inspect.isclass(object) or
89  inspect.isroutine(object) or inspect.isframe(object) or
90  inspect.istraceback(object) or inspect.iscode(object))
def pydoc.ispackage (   path)
Guess whether a path refers to a package directory.

Definition at line 146 of file pydoc.py.

147 def ispackage(path):
148  """Guess whether a path refers to a package directory."""
149  if os.path.isdir(path):
150  for ext in ['.py', '.pyc', '.pyo']:
151  if os.path.isfile(os.path.join(path, '__init__' + ext)):
152  return 1
def pydoc.ispath (   x)

Definition at line 2027 of file pydoc.py.

References gettext.find().

2028 def ispath(x):
2029  return type(x) is types.StringType and find(x, os.sep) >= 0
def pydoc.locate (   path,
  forceload = 0 
)
Locate an object by name or dotted path, importing as necessary.

Definition at line 1296 of file pydoc.py.

References dospath.join(), safeimport(), and dospath.split().

1297 def locate(path, forceload=0):
1298  """Locate an object by name or dotted path, importing as necessary."""
1299  parts = split(path, '.')
1300  module, n = None, 0
1301  while n < len(parts):
1302  nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
1303  if nextmodule: module, n = nextmodule, n + 1
1304  else: break
1305  if module:
1306  object = module
1307  for part in parts[n:]:
1308  try: object = getattr(object, part)
1309  except AttributeError: return None
1310  return object
1311  else:
1312  import __builtin__
1313  if hasattr(__builtin__, path):
1314  return getattr(__builtin__, path)
1315 
1316 # --------------------------------------- interactive interpreter interface
def pydoc.pager (   text)
The first time this is called, determine what kind of pager to use.

Definition at line 1171 of file pydoc.py.

References getpager().

1172 def pager(text):
1173  """The first time this is called, determine what kind of pager to use."""
1174  global pager
1175  pager = getpager()
1176  pager(text)
def pydoc.pathdirs ( )
Convert sys.path into a list of absolute, existing, unique paths.

Definition at line 52 of file pydoc.py.

52 
53 def pathdirs():
54  """Convert sys.path into a list of absolute, existing, unique paths."""
55  dirs = []
56  normdirs = []
57  for dir in sys.path:
58  dir = os.path.abspath(dir or '.')
59  normdir = os.path.normcase(dir)
60  if normdir not in normdirs and os.path.isdir(dir):
61  dirs.append(dir)
62  normdirs.append(normdir)
63  return dirs
def pydoc.pipepager (   text,
  cmd 
)
Page through text by feeding it to another program.

Definition at line 1212 of file pydoc.py.

1213 def pipepager(text, cmd):
1214  """Page through text by feeding it to another program."""
1215  pipe = os.popen(cmd, 'w')
1216  try:
1217  pipe.write(text)
1218  pipe.close()
1219  except IOError:
1220  pass # Ignore broken pipes caused by quitting the pager program.
def pydoc.plain (   text)
Remove boldface formatting from text.

Definition at line 1208 of file pydoc.py.

1209 def plain(text):
1210  """Remove boldface formatting from text."""
1211  return re.sub('.\b', '', text)
def pydoc.plainpager (   text)
Simply print unformatted text.  This is the ultimate fallback.

Definition at line 1271 of file pydoc.py.

References plain().

1272 def plainpager(text):
1273  """Simply print unformatted text. This is the ultimate fallback."""
1274  sys.stdout.write(plain(text))
def pydoc.replace (   text,
  pairs 
)
Do a series of global replacements on a string.

Definition at line 91 of file pydoc.py.

References dospath.join(), and dospath.split().

91 
92 def replace(text, *pairs):
93  """Do a series of global replacements on a string."""
94  while pairs:
95  text = join(split(text, pairs[0]), pairs[1])
96  pairs = pairs[2:]
97  return text
def pydoc.safeimport (   path,
  forceload = 0,
  cache = {} 
)
Import a module; handle errors; return None if the module isn't found.

If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised.  Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning.  If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension).

Definition at line 217 of file pydoc.py.

References inspect.getmoduleinfo(), string.lower(), dospath.split(), and locale.str().

218 def safeimport(path, forceload=0, cache={}):
219  """Import a module; handle errors; return None if the module isn't found.
220 
221  If the module *is* found but an exception occurs, it's wrapped in an
222  ErrorDuringImport exception and reraised. Unlike __import__, if a
223  package path is specified, the module at the end of the path is returned,
224  not the package at the beginning. If the optional 'forceload' argument
225  is 1, we reload the module from disk (unless it's a dynamic extension)."""
226  if forceload and sys.modules.has_key(path):
227  # This is the only way to be sure. Checking the mtime of the file
228  # isn't good enough (e.g. what if the module contains a class that
229  # inherits from another module that has changed?).
230  if path not in sys.builtin_module_names:
231  # Python never loads a dynamic extension a second time from the
232  # same path, even if the file is changed or missing. Deleting
233  # the entry in sys.modules doesn't help for dynamic extensions,
234  # so we're not even going to try to keep them up to date.
235  info = inspect.getmoduleinfo(sys.modules[path].__file__)
236  if info[3] != imp.C_EXTENSION:
237  cache[path] = sys.modules[path] # prevent module from clearing
238  del sys.modules[path]
239  try:
240  module = __import__(path)
241  except:
242  # Did the error occur before or after the module was found?
243  (exc, value, tb) = info = sys.exc_info()
244  if sys.modules.has_key(path):
245  # An error occured while executing the imported module.
246  raise ErrorDuringImport(sys.modules[path].__file__, info)
247  elif exc is SyntaxError:
248  # A SyntaxError occurred before we could execute the module.
249  raise ErrorDuringImport(value.filename, info)
250  elif exc is ImportError and \
251  split(lower(str(value)))[:2] == ['no', 'module']:
252  # The module was not found.
253  return None
254  else:
255  # Some other error occurred during the importing process.
256  raise ErrorDuringImport(path, sys.exc_info())
257  for part in split(path, '.')[1:]:
258  try: module = getattr(module, part)
259  except AttributeError: return None
260  return module
261 
262 # ---------------------------------------------------- formatter base class
def pydoc.serve (   port,
  callback = None,
  completer = None 
)

Definition at line 1758 of file pydoc.py.

References audiodev.__init__().

1759 def serve(port, callback=None, completer=None):
1760  import BaseHTTPServer, mimetools, select
1761 
1762  # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
1763  class Message(mimetools.Message):
1764  def __init__(self, fp, seekable=1):
1765  Message = self.__class__
1766  Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
1767  self.encodingheader = self.getheader('content-transfer-encoding')
1768  self.typeheader = self.getheader('content-type')
1769  self.parsetype()
1770  self.parseplist()
1771 
1772  class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
1773  def send_document(self, title, contents):
1774  try:
1775  self.send_response(200)
1776  self.send_header('Content-Type', 'text/html')
1777  self.end_headers()
1778  self.wfile.write(html.page(title, contents))
1779  except IOError: pass
1780 
1781  def do_GET(self):
1782  path = self.path
1783  if path[-5:] == '.html': path = path[:-5]
1784  if path[:1] == '/': path = path[1:]
1785  if path and path != '.':
1786  try:
1787  obj = locate(path, forceload=1)
1788  except ErrorDuringImport, value:
1789  self.send_document(path, html.escape(str(value)))
1790  return
1791  if obj:
1792  self.send_document(describe(obj), html.document(obj, path))
1793  else:
1794  self.send_document(path,
1795 'no Python documentation found for %s' % repr(path))
1796  else:
1797  heading = html.heading(
1798 '<big><big><strong>Python: Index of Modules</strong></big></big>',
1799 '#ffffff', '#7799ee')
1800  def bltinlink(name):
1801  return '<a href="%s.html">%s</a>' % (name, name)
1802  names = filter(lambda x: x != '__main__',
1803  sys.builtin_module_names)
1804  contents = html.multicolumn(names, bltinlink)
1805  indices = ['<p>' + html.bigsection(
1806  'Built-in Modules', '#ffffff', '#ee77aa', contents)]
1807 
1808  seen = {}
1809  for dir in pathdirs():
1810  indices.append(html.index(dir, seen))
1811  contents = heading + join(indices) + '''<p align=right>
1812 <font color="#909090" face="helvetica, arial"><strong>
1813 pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>'''
1814  self.send_document('Index of Modules', contents)
1815 
1816  def log_message(self, *args): pass
1817 
1818  class DocServer(BaseHTTPServer.HTTPServer):
1819  def __init__(self, port, callback):
1820  host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
1821  self.address = ('', port)
1822  self.url = 'http://%s:%d/' % (host, port)
1823  self.callback = callback
1824  self.base.__init__(self, self.address, self.handler)
1825 
1826  def serve_until_quit(self):
1827  import select
1828  self.quit = 0
1829  while not self.quit:
1830  rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
1831  if rd: self.handle_request()
1832 
1833  def server_activate(self):
1834  self.base.server_activate(self)
1835  if self.callback: self.callback(self)
1836 
1837  DocServer.base = BaseHTTPServer.HTTPServer
1838  DocServer.handler = DocHandler
1839  DocHandler.MessageClass = Message
1840  try:
1841  try:
1842  DocServer(port, callback).serve_until_quit()
1843  except (KeyboardInterrupt, select.error):
1844  pass
1845  finally:
1846  if completer: completer()
1847 
1848 # ----------------------------------------------------- graphical interface
def pydoc.splitdoc (   doc)
Split a doc string into a synopsis line (if any) and the rest.

Definition at line 69 of file pydoc.py.

References dospath.join(), string.rstrip(), dospath.split(), and string.strip().

69 
70 def splitdoc(doc):
71  """Split a doc string into a synopsis line (if any) and the rest."""
72  lines = split(strip(doc), '\n')
73  if len(lines) == 1:
74  return lines[0], ''
75  elif len(lines) >= 2 and not rstrip(lines[1]):
76  return lines[0], join(lines[2:], '\n')
77  return '', join(lines, '\n')
def pydoc.stripid (   text)
Remove the hexadecimal id from a Python object representation.

Definition at line 106 of file pydoc.py.

References inspect.ismethod(), and inspect.ismethoddescriptor().

107 def stripid(text):
108  """Remove the hexadecimal id from a Python object representation."""
109  # The behaviour of %p is implementation-dependent; we check two cases.
110  for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']:
111  if re.search(pattern, repr(Exception)):
112  return re.sub(pattern, '>', text)
113  return text
def pydoc.synopsis (   filename,
  cache = {} 
)
Get the one-line summary out of a module file.

Definition at line 153 of file pydoc.py.

References inspect.getmoduleinfo(), aifc.open(), dospath.split(), and string.strip().

154 def synopsis(filename, cache={}):
155  """Get the one-line summary out of a module file."""
156  mtime = os.stat(filename)[stat.ST_MTIME]
157  lastupdate, result = cache.get(filename, (0, None))
158  if lastupdate < mtime:
159  info = inspect.getmoduleinfo(filename)
160  file = open(filename)
161  if info and 'b' in info[2]: # binary modules have to be imported
162  try: module = imp.load_module('__temp__', file, filename, info[1:])
163  except: return None
164  result = split(module.__doc__ or '', '\n')[0]
165  del sys.modules['__temp__']
166  else: # text modules can be directly examined
167  line = file.readline()
168  while line[:1] == '#' or not strip(line):
169  line = file.readline()
170  if not line: break
171  line = strip(line)
172  if line[:4] == 'r"""': line = line[1:]
173  if line[:3] == '"""':
174  line = line[3:]
175  if line[-1:] == '\\': line = line[:-1]
176  while not strip(line):
177  line = file.readline()
178  if not line: break
179  result = strip(split(line, '"""')[0])
180  else: result = None
181  file.close()
182  cache[filename] = (mtime, result)
183  return result
def pydoc.tempfilepager (   text,
  cmd 
)
Page through text by invoking a program on a temporary file.

Definition at line 1221 of file pydoc.py.

References tempfile.mktemp(), and aifc.open().

1222 def tempfilepager(text, cmd):
1223  """Page through text by invoking a program on a temporary file."""
1224  import tempfile
1225  filename = tempfile.mktemp()
1226  file = open(filename, 'w')
1227  file.write(text)
1228  file.close()
1229  try:
1230  os.system(cmd + ' ' + filename)
1231  finally:
1232  os.unlink(filename)
def pydoc.ttypager (   text)
Page through text on a text terminal.

Definition at line 1233 of file pydoc.py.

References dospath.join(), plain(), tty.setcbreak(), and dospath.split().

1234 def ttypager(text):
1235  """Page through text on a text terminal."""
1236  lines = split(plain(text), '\n')
1237  try:
1238  import tty
1239  fd = sys.stdin.fileno()
1240  old = tty.tcgetattr(fd)
1241  tty.setcbreak(fd)
1242  getchar = lambda: sys.stdin.read(1)
1243  except (ImportError, AttributeError):
1244  tty = None
1245  getchar = lambda: sys.stdin.readline()[:-1][:1]
1246 
1247  try:
1248  r = inc = os.environ.get('LINES', 25) - 1
1249  sys.stdout.write(join(lines[:inc], '\n') + '\n')
1250  while lines[r:]:
1251  sys.stdout.write('-- more --')
1252  sys.stdout.flush()
1253  c = getchar()
1254 
1255  if c in ['q', 'Q']:
1256  sys.stdout.write('\r \r')
1257  break
1258  elif c in ['\r', '\n']:
1259  sys.stdout.write('\r \r' + lines[r] + '\n')
1260  r = r + 1
1261  continue
1262  if c in ['b', 'B', '\x1b']:
1263  r = r - inc - inc
1264  if r < 0: r = 0
1265  sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
1266  r = r + inc
1267 
1268  finally:
1269  if tty:
1270  tty.tcsetattr(fd, tty.TCSAFLUSH, old)
def pydoc.writedoc (   key,
  forceload = 0 
)
Write HTML documentation to a file in the current directory.

Definition at line 1343 of file pydoc.py.

References describe(), locate(), and aifc.open().

1344 def writedoc(key, forceload=0):
1345  """Write HTML documentation to a file in the current directory."""
1346  try:
1347  object = locate(key, forceload)
1348  except ErrorDuringImport, value:
1349  print value
1350  else:
1351  if object:
1352  page = html.page(describe(object),
1353  html.document(object, object.__name__))
1354  file = open(key + '.html', 'w')
1355  file.write(page)
1356  file.close()
1357  print 'wrote', key + '.html'
1358  else:
1359  print 'no Python documentation found for %s' % repr(key)
def pydoc.writedocs (   dir,
  pkgpath = '',
  done = None 
)
Write out HTML documentation for all modules in a directory tree.

Definition at line 1360 of file pydoc.py.

References inspect.getmodulename(), ispackage(), and writedoc().

1361 def writedocs(dir, pkgpath='', done=None):
1362  """Write out HTML documentation for all modules in a directory tree."""
1363  if done is None: done = {}
1364  for file in os.listdir(dir):
1365  path = os.path.join(dir, file)
1366  if ispackage(path):
1367  writedocs(path, pkgpath + file + '.', done)
1368  elif os.path.isfile(path):
1369  modname = inspect.getmodulename(path)
1370  if modname:
1371  modname = pkgpath + modname
1372  if not done.has_key(modname):
1373  done[modname] = 1
1374  writedoc(modname)

Variable Documentation

string __author__ = "Ka-Ping Yee <ping@lfw.org>"

Definition at line 28 of file pydoc.py.

string __credits__
Initial value:
1 = """Guido van Rossum, for an excellent programming language.
2 Tommy Burnette, the original creator of manpy.
3 Paul Prescod, for all his work on onlinehelp.
4 Richard Chamberlain, for the first implementation of textdoc.
5 
6 Mynd you, møøse bites Kan be pretty nasti..."""

Definition at line 31 of file pydoc.py.

string __date__ = "26 February 2001"

Definition at line 29 of file pydoc.py.

string __version__ = "$Revision: 5816 $"

Definition at line 30 of file pydoc.py.

address

Definition at line 1820 of file pydoc.py.

bigheight

Definition at line 1911 of file pydoc.py.

bigminheight

Definition at line 1907 of file pydoc.py.

bigwidth

Definition at line 1999 of file pydoc.py.

callback

Definition at line 1822 of file pydoc.py.

encodingheader

Definition at line 1766 of file pydoc.py.

expanded

Definition at line 1912 of file pydoc.py.

goto_btn

Definition at line 1897 of file pydoc.py.

tuple help = Helper(sys.stdin, sys.stdout)

Definition at line 1664 of file pydoc.py.

hide_btn

Definition at line 1899 of file pydoc.py.

tuple html = HTMLDoc()

Definition at line 1318 of file pydoc.py.

minheight

Definition at line 1906 of file pydoc.py.

minwidth

Definition at line 1905 of file pydoc.py.

open_btn

Definition at line 1861 of file pydoc.py.

quit

Definition at line 1827 of file pydoc.py.

quit_btn

Definition at line 1863 of file pydoc.py.

result_frm

Definition at line 1896 of file pydoc.py.

result_lst

Definition at line 1889 of file pydoc.py.

result_scr

Definition at line 1892 of file pydoc.py.

scanner

Definition at line 1855 of file pydoc.py.

search_ent

Definition at line 1868 of file pydoc.py.

search_frm

Definition at line 1866 of file pydoc.py.

search_lbl

Definition at line 1867 of file pydoc.py.

server

Definition at line 1854 of file pydoc.py.

server_frm

Definition at line 1858 of file pydoc.py.

stop_btn

Definition at line 1870 of file pydoc.py.

tuple text = TextDoc()

Definition at line 1317 of file pydoc.py.

title_lbl

Definition at line 1859 of file pydoc.py.

typeheader

Definition at line 1767 of file pydoc.py.

url

Definition at line 1821 of file pydoc.py.

window

Definition at line 1853 of file pydoc.py.